• DLINACT01 第一个网络


    1. 导入MNIST数据集

    from keras.datasets import mnist
    
    (train_images, train_labels), (test_images, test_labels) = mnist.load_data()
    
    train_images.shape
    
    (60000, 28, 28)
    
    train_labels
    
    array([5, 0, 4, ..., 5, 6, 8], dtype=uint8)
    
    test_images.shape
    
    (10000, 28, 28)
    
    test_labels
    
    array([7, 2, 1, ..., 4, 5, 6], dtype=uint8)
    

    2. 构建网络结构

    from keras import models
    from keras import layers
    
    network = models.Sequential()
    network.add(layers.Dense(512, activation='relu', input_shape=(28 * 28,)))
    network.add(layers.Dense(10, activation='softmax')) # 10路的softmax层,返回10个概率
    network.compile(optimizer='rmsprop',
                   loss='categorical_crossentropy',
                   metrics=['accuracy']) # 选择loss function, optimizer, metrics
    

    3. 准备图像数据

    train_images = train_images.reshape((60000, 28 * 28))
    train_images = train_images.astype('float32') / 255
    
    test_images = test_images.reshape((10000, 28 * 28))
    test_images = test_images.astype('float32') / 255
    

    4. 准备标签

    from keras.utils import to_categorical
    
    train_labels = to_categorical(train_labels)
    test_labels = to_categorical(test_labels)
    

    5. 训练模型

    network.fit(train_images, train_labels, epochs=5, batch_size=128)
    
    Epoch 1/5
    60000/60000 [==============================] - 5s 79us/step - loss: 0.2603 - acc: 0.9248
    Epoch 2/5
    60000/60000 [==============================] - 5s 76us/step - loss: 0.1049 - acc: 0.9687
    Epoch 3/5
    60000/60000 [==============================] - 5s 77us/step - loss: 0.0686 - acc: 0.9794
    Epoch 4/5
    60000/60000 [==============================] - 4s 73us/step - loss: 0.0504 - acc: 0.9849
    Epoch 5/5
    60000/60000 [==============================] - 5s 81us/step - loss: 0.0372 - acc: 0.9886
    
    
    
    
    
    <keras.callbacks.History at 0x20f3012a390>
    

    6. 评估模型

    test_loss, test_acc = network.evaluate(test_images, test_labels)
    print('test_acc', test_acc)
    
    10000/10000 [==============================] - 1s 53us/step
    test_acc 0.9805
    CS专业在读,热爱编程。
    专业之外,喜欢阅读,尤爱哲学、金庸、马尔克斯。
  • 相关阅读:
    在react中使用css module
    Hoisting(变量提升)
    JS 实现货币格式化
    使用promise封装一个retry
    【要命的神奇bug】if条件 使用 正则表达式
    iframe内媒体查询的问题
    iframe嵌套登录页-页面无法加载
    Sketch Measure切图插件无法导出标注 (换插件绕过解决)
    python项目中获取当前文件所在目录
    上传文件踩到的坑
  • 原文地址:https://www.cnblogs.com/jmhwsrr/p/15755938.html
Copyright © 2020-2023  润新知