T1-实现mnist手写数字识别

发布时间:2026/8/1 9:17:56
T1-实现mnist手写数字识别 ● 本文为365天深度学习训练营中的学习记录博客● 原作者K同学啊一、前期准备1.设置GPUimport 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) print(gpus)2.导入数据一种方法是可以直接下载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()如果无法连接下载数据可以先下载好数据集在本地加载import os import gzip import numpy as np def load_mnist_local(path): files [ train-images-idx3-ubyte.gz, train-labels-idx1-ubyte.gz, t10k-images-idx3-ubyte.gz, t10k-labels-idx1-ubyte.gz ] with gzip.open(os.path.join(path, files[0]), rb) as f: x_train np.frombuffer(f.read(), np.uint8, offset16).reshape(-1,28,28) with gzip.open(os.path.join(path, files[1]), rb) as f: y_train np.frombuffer(f.read(), np.uint8, offset8) with gzip.open(os.path.join(path, files[2]), rb) as f: x_test np.frombuffer(f.read(), np.uint8, offset16).reshape(-1,28,28) with gzip.open(os.path.join(path, files[3]), rb) as f: y_test np.frombuffer(f.read(), np.uint8, offset8) return (x_train, y_train), (x_test, y_test) # 这里改成数据集所在位置 data_path rC:\Users\asus\Desktop\T1\data\MNIST\raw (train_images, train_labels), (test_images, test_labels) load_mnist_local(data_path)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.shape4.数据可视化# 将数据集前20个图片数据可视化显示 # 进行图像大小为20宽、10长的绘图(单位为英寸inch) plt.figure(figsize(20,10)) # 遍历MNIST数据集下标数值0~49 for i in range(20): # 将整个figure分成2行10列绘制第i1个子图。 plt.subplot(2,10,i1) # 设置不显示x轴刻度 plt.xticks([]) # 设置不显示y轴刻度 plt.yticks([]) # 设置不显示子图网格线 plt.grid(False) # 图像展示cmap为颜色图谱plt.cm.binary为matplotlib.cm中的色表 plt.imshow(train_images[i], cmapplt.cm.binary) # 设置x轴标签显示为图片对应的数字 plt.xlabel(train_labels[i]) # 显示图片 plt.show()5.调整图片格式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.构建CNN模型model models.Sequential([ # 设置二维卷积层1设置32个3*3卷积核activation参数将激活函数设置为ReLu函数input_shape参数将图层的输入形状设置为(28, 28, 1) # ReLu函数作为激活励函数可以增强判定函数和整个神经网络的非线性特性而本身并不会改变卷积层 # 相比其它函数来说ReLU函数更受青睐这是因为它可以将神经网络的训练速度提升数倍而并不会对模型的泛化准确度造成显著影响。 layers.Conv2D(32, (3, 3), activationrelu, input_shape(28, 28, 1)), #池化层12*2采样 layers.MaxPooling2D((2, 2)), # 设置二维卷积层2设置64个3*3卷积核activation参数将激活函数设置为ReLu函数 layers.Conv2D(64, (3, 3), activationrelu), #池化层22*2采样 layers.MaxPooling2D((2, 2)), layers.Flatten(), #Flatten层连接卷积层与全连接层 layers.Dense(64, activationrelu), #全连接层特征进一步提取64为输出空间的维数activation参数将激活函数设置为ReLu函数 layers.Dense(10) #输出层输出预期结果10为输出空间的维数 ]) # 打印网络结构 model.summary()2.编译模型model.compile( optimizeradam, losstf.keras.losses.SparseCategoricalCrossentropy(from_logitsTrue), metrics[accuracy])3.模型训练history model.fit( train_images, train_labels, epochs10, validation_data(test_images, test_labels))import matplotlib.pyplot as plt #隐藏警告 import warnings warnings.filterwarnings(ignore) plt.rcParams[font.sans-serif] [SimHei] plt.rcParams[axes.unicode_minus] False plt.rcParams[figure.dpi] 100 from datetime import datetime current_time datetime.now() epochs_range range(10) plt.figure(figsize(12, 3)) plt.subplot(1, 2, 1) plt.plot(epochs_range, train_acc, labelTraining Accuracy) plt.plot(epochs_range, test_acc, labelTest Accuracy) plt.legend(loclower right) plt.title(Training and Validation Accuracy) plt.xlabel(current_time) plt.subplot(1, 2, 2) plt.plot(epochs_range, train_loss, labelTraining Loss) plt.plot(epochs_range, test_loss, labelTest Loss) plt.legend(locupper right) plt.title(Training and Validation Loss) plt.show()三、模型预测plt.imshow(test_images[1])pre model.predict(test_images) # 对所有测试图片进行预测 pre[1] # 输出第一张图片的预测结果第三项为29.019821说明预测结果为2和图片一致。个人总结安装tensorflow2的GPU版本时一定要注意各个库的版本协调我因为在学深度学习之前就已经安装了python3.12anaconda和CUDA12.6python和CUDA的版本都过高无法适配tensorflow2所以在anaconda里建立了一个pyhon3.9的虚拟环境在该环境内下载了CUDA11.2和cudnn8.1最后安装tensorflow2.10。本周使用tensorflow实现mnist手写数字识别使用的是最简单的CNN模型 LeNet-5由输入层、卷积层1池化层1卷积层2池化层2flatten层全连接层输出层按序构成。这里的tensorflow2(Keras)是高阶API的写法能够快速搭建出CNN模型。