• 【365天深度学习训练营】第二周 彩色图片分类


    我的环境:

    • 语言环境:Python3.6.8
    • 编译器:jupyter notebook
    • 深度学习环境:TensorFlow2.1

    一、前期工作

    1. 设置 GPU

    import tensorflow as tf
    gpus = tf.config.list_physical_devices("GPU") # 获得当前主机上某种特定运算设备类型(如 GPU 或 CPU)的列表
    
    if gpus:
        gpu0 = gpus[0] # 如果有多个 GPU,仅使用第一个 GPU
        tf.config.experimental.set_memory_growth(gpu0, True) # 设置 GPU 显存用量按需使用
        tf.config.set_visible_devices([gpu0], "GPU") # 设置当前程序可见的设备范围
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    2. 导入数据

    import tensorflow as tf
    from tensorflow.keras import datasets, layers, models
    import matplotlib.pyplot as plt
    # 导入 cifar10 数据集,依次分别为训练集图片,训练集标签,测试集图片,测试集标签
    (train_images, train_labels), (test_images, test_labels) = datasets.cifar10.load_data()
    
    • 1
    • 2
    • 3
    • 4
    • 5

    3. 归一化

    数据归一化作用:

    • 使不同量纲的特征处于同一数值量级,减少方差大的特征的影响,使模型更准确。
    • 加快学习算法的收敛速度
    # 将像素值标准化至 0 到 1 的区间内(对于灰度图片来说,每个像素最大值是255,每个像素最小值是0,也就是直接除以255就可以完成归一化。)
    train_images, test_images = train_images / 255.0, test_images / 255.0
    train_images.shape, test_images.shape, train_labels.shape, test_labels.shape
    
    • 1
    • 2
    • 3

    输出
    ((50000, 32, 32, 3), (10000, 32, 32, 3), (50000, 1), (10000, 1))

    4. 可视化图片

    class_names = ['airplane', 'automobile', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck']
    
    plt.figure(figsize=(20,10)) # 指定 figure 的宽和高
    for i in range(20):
        plt.subplot(5,10,i+1)
        plt.xticks([])
        plt.yticks([])
        plt.grid(False)
        plt.imshow(train_images[i], cmap=plt.cm.binary)
        plt.xlabel(class_names[train_labels[i][0]])
    plt.show()
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    在这里插入图片描述

    二、构建 CNN 网络

    model = models.Sequential([
        layers.Conv2D(32, (3, 3), activation='relu', input_shape=(32, 32, 3)), #卷积层1,卷积核3*3
        layers.MaxPooling2D((2, 2)),                   #池化层1,2*2采样
        layers.Conv2D(64, (3, 3), activation='relu'),  #卷积层2,卷积核3*3
        layers.MaxPooling2D((2, 2)),                   #池化层2,2*2采样
        layers.Conv2D(64, (3, 3), activation='relu'),  #卷积层3,卷积核3*3
        
        layers.Flatten(),                      #Flatten层,连接卷积层与全连接层
        layers.Dense(64, activation='relu'),   #全连接层,特征进一步提取
        layers.Dense(10)                       #输出层,输出预期结果
    ])
    
    model.summary()  # 打印网络结构
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    在这里插入图片描述

    三、编译模型

    model.compile(optimizer='adam',
                  loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
                  metrics=['accuracy'])
    
    • 1
    • 2
    • 3

    四、训练模型

    history = model.fit(train_images, train_labels, epochs=10, 
                        validation_data=(test_images, test_labels))
    
    • 1
    • 2

    在这里插入图片描述

    五、预测

    plt.imshow(test_images[1])
    
    • 1


    在这里插入图片描述

    import numpy as np
    
    pre = model.predict(test_images)
    print(class_names[np.argmax(pre[1])])
    
    • 1
    • 2
    • 3
    • 4

    ship

    六、模型评估

    import matplotlib.pyplot as plt
    
    plt.plot(history.history['accuracy'], label='accuracy')
    plt.plot(history.history['val_accuracy'], label = 'val_accuracy')
    plt.xlabel('Epoch')
    plt.ylabel('Accuracy')
    plt.ylim([0.5, 1])
    plt.legend(loc='lower right')
    plt.show()
    
    test_loss, test_acc = model.evaluate(test_images,  test_labels, verbose=2)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    在这里插入图片描述

    print(test_acc)
    
    • 1

    0.6848

  • 相关阅读:
    JavaScript实现网页截屏的5种方法(详解+代码)
    2023年CSP-J1入门级第一轮题解
    Windows驱动开发(一)第一个驱动程序
    Linux redis 安装
    LeetCode 34. 在排序数组中查找元素的第一个和最后一个位置
    030-第三代软件开发-密码输入框
    linux下如何dhcp失败为获取到ip地址,如何设置为一个固定的地址
    【BOOST C++】教程3: 数据类型
    java高并发系列-第1天:必须知道的几个概念
    【C语言】递归问题(爬楼梯)
  • 原文地址:https://blog.csdn.net/lele_ne/article/details/126775667