• 深度学习训练营实现minist手写数字识别


    原文链接

    环境介绍

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

    前置工作

    设置GPU

    如果

    # K同学啊深度学习练习
    import tensorflow as tf
    gpus = tf.config.list_physical_devices("GPU")
    
    if gpus:
        gpu0 = gpus[0] #如果有多个GPU,仅使用第0个GPU
        tf.config.experimental.set_memory_growth(gpu0, True) #设置GPU显存用量按需使用
        tf.config.set_visible_devices([gpu0],"GPU")
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    导入要使用的包

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

    进行归一化操作

    # 将像素的值标准化至0到1的区间内。
    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
    • 4

    样本可视化

    使用到的是python当中专门用来画图的matplotlib.pyplot

    # 将数据集前20个图片数据可视化显示
    # 进行图像大小为20宽、10长的绘图(单位为英寸inch)
    plt.figure(figsize=(20,10))
    # 遍历MNIST数据集下标数值0~49
    for i in range(20):
        # 将整个figure分成5行10列,绘制第i+1个子图。
        plt.subplot(2,10,i+1)
        # 设置不显示x轴刻度
        plt.xticks([])
        # 设置不显示y轴刻度
        plt.yticks([])
        # 设置不显示子图网格线
        plt.grid(False)
        # 图像展示,cmap为颜色图谱,"plt.cm.binary"为matplotlib.cm中的色表
        plt.imshow(train_images[i], cmap=plt.cm.binary)
        # 设置x轴标签显示为图片对应的数字
        plt.xlabel(train_labels[i])
    # 显示图片
    plt.show()
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    在这里插入图片描述

    调整图片格式

    #调整数据到我们需要的格式
    train_images = train_images.reshape((60000, 28, 28, 1))
    test_images = test_images.reshape((10000, 28, 28, 1))
    
    train_images.shape,test_images.shape,train_labels.shape,test_labels.shape
    
    • 1
    • 2
    • 3
    • 4
    • 5

    调整图片格式为我们需要的
    在这里插入图片描述

    构建CNN网络

    CNN名为卷积神经网络,是一种专门用来处理类似网络结构的数据的神经网络

    • 卷积层:通过卷积操作对输入图像进行降维和特征抽取
    • 池化层:是一种非线性形式的下采样。主要用于特征降维,压缩数据和参数的数量,减小过拟合,同时提高模型的鲁棒性。
    • 全连接层:在经过几个卷积和池化层之后,神经网络中的高级推理通过全连接层来完成。
    model = models.Sequential([
        # 设置二维卷积层1,设置32个3*3卷积核,activation参数将激活函数设置为ReLu函数,input_shape参数将图层的输入形状设置为(28, 28, 1)
        # ReLu函数作为激活励函数可以增强判定函数和整个神经网络的非线性特性,而本身并不会改变卷积层
        # 相比其它函数来说,ReLU函数更受青睐,这是因为它可以将神经网络的训练速度提升数倍,而并不会对模型的泛化准确度造成显著影响。
        layers.Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1)),
        #池化层1,2*2采样
        layers.MaxPooling2D((2, 2)),                   
        # 设置二维卷积层2,设置64个3*3卷积核,activation参数将激活函数设置为ReLu函数
        layers.Conv2D(64, (3, 3), activation='relu'),  
        #池化层2,2*2采样
        layers.MaxPooling2D((2, 2)),                   
        
        layers.Flatten(),                    #Flatten层,连接卷积层与全连接层
        layers.Dense(64, activation='relu'), #全连接层,特征进一步提取,64为输出空间的维数,activation参数将激活函数设置为ReLu函数
        layers.Dense(10)                     #输出层,输出预期结果,10为输出空间的维数
    ])
    # 打印网络结构
    model.summary()
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    在这里插入图片描述
    Sequential:连续的,序列的
    Non-trainable params:不可训练参数

    编译模型

    # model.compile()方法用于在配置训练方法时,告知训练时用的优化器、损失函数和准确率评测标准
    model.compile(
    	# 设置优化器为Adam优化器
        optimizer='adam',
    	# 设置损失函数为交叉熵损失函数(tf.keras.losses.SparseCategoricalCrossentropy())
        # from_logits为True时,会将y_pred转化为概率(用softmax),否则不进行转换,通常情况下用True结果更稳定
        loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
        # 设置性能指标列表,将在模型训练时监控列表中的指标
        metrics=['accuracy'])
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    模型训练

    """
    这里设置输入训练数据集(图片及标签)、验证数据集(图片及标签)以及迭代次数epochs
    关于model.fit()函数的具体介绍可参考K同学的博客:
    https://blog.csdn.net/qq_38251616/category_10258234.html
    """
    history = model.fit(
        # 输入训练集图片
    	train_images, 
    	# 输入训练集标签
    	train_labels, 
    	# 设置10个epoch,每一个epoch都将会把所有的数据输入模型完成一次训练。
    	epochs=10, 
    	# 设置验证集
        validation_data=(test_images, test_labels))
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    训练过程以及结果如下
    在这里插入图片描述

    预测操作

    plt.imshow(test_images[7])
    
    • 1

    在这里插入图片描述
    查看图片的预测结果

    pre = model.predict(test_images) # 对所有测试图片进行预测
    pre[7] # 输出第七张图片的预测结果
    
    • 1
    • 2

    在这里插入图片描述
    在预测图片的过程当中,对图像进行预测,预测图像为哪一个0到9的数值,数值越大,则代表越靠近该值,所以由以上结果可以知道,图片的预测结果为9

  • 相关阅读:
    架构师系列-Nginx、OpenResty(一)- 基本使用配置
    Vue组件自定义事件父子
    电源集成INN3270C-H215-TL、INN3278C-H114-TL、INN3278C-H215-TL简化了反激式电源转换器的设计和制造。
    js_输出方式和数据类型
    网站运营怎样才能反超对手呢
    2022年6月1日启动-蓝图功能C++初级编程教学重置计划启动
    svg 知识点总结
    [找规律]Number Game 2022牛客多校第6场 J
    奇安信笔试C++
    AI赋能程序员(学生免费申请流程):Pycharm安装copilot让AI帮忙写python代码
  • 原文地址:https://blog.csdn.net/qq_62904883/article/details/128151048