• DNN识别mnist手写数字


    mnist数据下载地址:
    链接:https://pan.baidu.com/s/1GD2hI8Wf4oUR-V2NysYorw
    提取码:sg3f

    导库

    import numpy as np
    import matplotlib.pyplot as plt
    import tensorflow as tf
    from tensorflow import keras
    from tensorflow.keras import layers
    

    读取mnist数据

    import numpy as np
    path='./mnist.npz'
    f = np.load(path)
    train_x, train_y = f['x_train'], f['y_train']    # 训练集
    test_x, test_y = f['x_test'], f['y_test']    # 测试集
    f.close()
    

    查看数据格式

    print(train_x.shape)
    print(train_y.shape)
    print(test_x.shape)
    print(test_y.shape)
    

    将数据以图片形式输出

    plt.imshow(train_x[10000])
    

    将数据格式改为DNN可接收的一维格式

    train_x = train_x.reshape((60000,28*28),order='C')    # 将二维的图片展开为一维的数据(训练集)  
    test_x = test_x.reshape((10000,28*28),order='C')    # 将二维的图片展开为一维的数据(测试集)
    

    搭建DNN并训练

    model = keras.Sequential()
    model.add(layers.Dense(100,activation='relu',input_dim=28*28))
    model.add(layers.Dense(10,activation='softmax'))
    adam = keras.optimizers.Adam(lr=0.01)
    model.compile(optimizer=adam,loss='sparse_categorical_crossentropy',metrics=['acc'])
    model.fit(train_x,train_y,epochs=50,batch_size=512)
    

    经过50轮训练后,DNN在训练集上的loss和准确率如下

    DNN在测试集上的loss和准确率如下

    model.evaluate(test_x,test_y)
    

    完整的代码如下

    import numpy as np
    import matplotlib.pyplot as plt
    import tensorflow as tf
    from tensorflow import keras
    from tensorflow.keras import layers
    
    path='./mnist.npz'
    f = np.load(path)
    train_x, train_y = f['x_train'], f['y_train']    # 训练集
    test_x, test_y = f['x_test'], f['y_test']    # 测试集
    f.close()
    
    print(train_x.shape)
    print(train_y.shape)
    print(test_x.shape)
    print(test_y.shape)
    
    plt.imshow(train_x[10000])
    
    train_x = train_x.reshape((60000,28*28),order='C')    # 将二维的图片展开为一维的数据(训练集)  
    test_x = test_x.reshape((10000,28*28),order='C')    # 将二维的图片展开为一维的数据(测试集)
    
    model = keras.Sequential()
    model.add(layers.Dense(100,activation='relu',input_dim=28*28))
    model.add(layers.Dense(10,activation='softmax'))
    model.compile(optimizer='adam',loss='sparse_categorical_crossentropy',metrics=['acc'])
    model.fit(train_x,train_y,epochs=50,batch_size=512)
    
    model.evaluate(test_x,test_y)
    
  • 相关阅读:
    437. Path Sum III
    416. Partition Equal Subset Sum
    417. Pacific Atlantic Water Flow
    30.构建单机多容器环境-故障&31.构建单机多容器环境
    29.镜像容器与仓库
    【笔记目录2】【jessetalk 】ASP.NET Core快速入门_学习笔记汇总
    【笔记目录1】【jessetalk 】ASP.NET Core快速入门_学习笔记汇总
    【笔记目录2】ASP.NET Core分布式项目实战
    【笔记目录1】ASP.NET Core分布式项目实战
    技术牛人感悟
  • 原文地址:https://www.cnblogs.com/bill-h/p/13906166.html
Copyright © 2020-2023  润新知