zoukankan      html  css  js  c++  java
  • tensorflow(二十四):fashion mnist数据集,训练与测试

    一、代码

    import tensorflow as tf
    from  tensorflow import keras
    from  tensorflow.keras import datasets, layers, optimizers, Sequential, metrics
    import  os
    
    os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
    
    def preprocess(x, y):  #数据预处理
        x = tf.cast(x, dtype=tf.float32)/ 255.
        y = tf.cast(y, dtype=tf.int32)
        return x,y
    
    (x, y),(x_test, y_test) = datasets.fashion_mnist.load_data()
    print(x.shape, y.shape)
    
    batchsize = 128
    
    #训练集预处理
    db = tf.data.Dataset.from_tensor_slices((x,y)) #构造数据集,这里可以自动的转换为tensor类型了
    db = db.map(preprocess).shuffle(10000).batch(batchsize)
    
    #测试集预处理
    db_test = tf.data.Dataset.from_tensor_slices((x_test,y_test)) #构造数据集
    db_test = db_test.map(preprocess).shuffle(10000).batch(batchsize)
    
    
    db_iter = iter(db)
    sample = next(db_iter)
    print("batch: ", sample[0].shape, sample[1].shape)
    
    
    #准备一个网络,5层。
    model = Sequential([
        layers.Dense(256, activation=tf.nn.relu), # [b, 784] => [b, 256]
        layers.Dense(128, activation=tf.nn.relu), # [b, 256] => [b, 128]
        layers.Dense(64, activation=tf.nn.relu), # [b, 128] => [b, 64]
        layers.Dense(32, activation=tf.nn.relu), # [b, 64] => [b, 32]
        layers.Dense(10) # [b, 32] => [b, 10], 330 = 32*10 + 10
    ])
    
    # 拿到这个层,喂给它一个权值,构建这样的一个输入。
    model.build(input_shape=[None, 28*28])
    model.summary() #调试的功能,可以打印网络结构。可以看出来总共有24万个,24万跟线,4字节的float.参数量一共100kb左右。gradient可能更大。
    
    # 优化器
    # w = w - lr*grads
    optimizer = optimizers.Adam(lr=1e-3)
    
    def main():
    
        for epoch in range(30):
    
            for step, (x, y) in enumerate(db):
    
                # x: [b, 28, 28]   =>  [b, 784]
                # y: [b]
                x = tf.reshape(x, [-1, 28*28])
    
                with tf.GradientTape() as tape:
                    # 前向传播,这里非常的简单。
                    # [b, 784] => [b, 10]
                    logits = model(x)     #调用完成前向传播。
                    y_onehot = tf.one_hot(y, depth=10)        #one-hot 标签编码
                    # 返回shape为[b],每个instance求一个实例。
                    loss_mse = tf.reduce_mean(tf.losses.MSE(y_onehot, logits))
                    # loss_ce = tf.losses.categorical_crossentropy(y_onehot, logits, from_logits=True)
                    # loss_ce = tf.reduce_mean(loss_ce)
    
                grads = tape.gradient(loss_mse, model.trainable_variables)
                #根据w=w-lr*grads把所有参数进行原地更新。zip的作用就是:把2个list(grads和mode...)中都为第0个的元素拼在一起,第1个同样2,3。
                optimizer.apply_gradients(zip(grads, model.trainable_variables))
    
                if step % 100 == 0:
                    print(epoch,step,'loss: ', float(loss_mse))
    
            #test: 只需要做前向传播。
            total_correct = 0  #总的正确的个数。
            total_num = 0      #总的测试的个数。
            for (x, y)  in db_test:
    
                # x: [b, 28, 28]   =>  [b, 784]
                # y: [b]
                x = tf.reshape(x, [-1, 28*28])
    
                #同样的道理这里我们不需要做一个GradientTape()的包围。
                logits = model(x)  # 调用完成前向传播。
                # 首先把logits => problity
                prob = tf.nn.softmax(logits, axis=1)
                # [b, 10] => [b]
                pred = tf.argmax(prob, axis=1)
                pred = tf.cast(pred, dtype=tf.int32)
                # pred: [b]
                # y: [b]
                #correct: [b], True: equal, False: not equal
                correct = tf.equal(pred, y)
                correct = tf.reduce_sum(tf.cast(correct, dtype=tf.int32))
    
                # 这里为什么需要做一个int,因为correct其实为一个tensor,但是我们这里的total_correct为一个numpy。
                # 需要把correct转换为一个numpy。
                total_correct += int(correct)
                total_num +=x.shape[0]
    
            acc = total_correct / total_num
            print(epoch, 'test acc: ', acc)
    
    if __name__ == '__main__':
        main()
  • 相关阅读:
    Linux考试题附答案
    MariaDB数据库主从复制实现步骤
    LinuxCentos系统安装Mariadb过程记录
    LinuxCentos系统安装Nginx过程记录
    VMware虚拟机不能联网的解决办法
    Linux centos下设置定时备份任务
    如何修改本地hosts文件?
    mysql用户授权以及权限收回
    Ubuntu系统下完全卸载和安装Mysql
    C++之类和对象的使用(一)
  • 原文地址:https://www.cnblogs.com/zhangxianrong/p/14629488.html
Copyright © 2011-2022 走看看