深度学习笔记 - tensorflow实现手写minst数据集识别

248 阅读4分钟

本次任务拟采用tensorflow搭建深度学习训练框架,实现minst手写数字识别。

一. 环境检查

踩过的坑:

  • 我本机电脑的CUDA版本是12.2,目前tf-gpu暂不支持Windows上的tf 2.10之后的版本(即不支持高版本的cuda)。
  • 如果硬要使用gpu版本,可以选择降低本机电脑的cuda和cudnn版本。或者配置虚拟的cudnn,配置方法见链接:blog.csdn.net/hacker_NO_0…
  • 为了节约时间,如果在科研过程中用到tf框架,我会去autodl官网上租一个服务器,选择直接装好的环境。
import tensorflow as tf

gpus = tf.config.list_physical_devices("GPU")

if gpus:
    tf.config.experimental.set_memory_growth(gpus[0], True)  #设置GPU显存用量按需使用
    tf.config.set_visible_devices([gpus[0]],"GPU")

print(gpus)
# 2024-11-22 19:25:10.297934: I tensorflow/stream_executor/platform/default/dso_loader.cc:53] Successfully opened dynamic library libcudnn.so.8 2024-11-22 19:25:10.298732: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1871] Adding visible gpu devices: 0

二. 数据集加载

数据加载并归一化

from tensorflow.keras import datasets, layers, models
import matplotlib.pyplot as plt

(train_images, train_labels), (test_images, test_labels) = datasets.mnist.load_data()

# 将像素的值标准化至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
# ((60000, 28, 28), (10000, 28, 28), (60000,), (10000,))

图片可视化

# 将数据集前20个图片数据可视化显示
plt.figure(figsize=(20,10))
for i in range(20):
    plt.subplot(2,10,i+1)
    plt.xticks([])
    plt.yticks([])
    plt.grid(False)
    plt.imshow(train_images[i], cmap=plt.cm.binary)
    plt.xlabel(train_labels[i])

plt.show()

三. 模型搭建

和torch不同的是,Dense线性层只有输出的维度参数(没有输入维度) 激活函数不用重新定义,可作为线性层和卷积层的参数

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()

四. 模型训练

与torch不同的是模型编译步骤,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'])

模型训练: epoch也作为输入参数,还可设置验证集,总之代码量确实少。

history = model.fit(
    # 输入训练集图片
	train_images, 
	# 输入训练集标签
	train_labels, 
	# 设置10个epoch,每一个epoch都将会把所有的数据输入模型完成一次训练。
	epochs=10, 
	# 设置验证集
    validation_data=(test_images, test_labels))

五. 模型预测

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

# array([ 4.4334936, -1.3273712, 27.17866 , -16.181103 , -1.4394543, -30.970243 , 2.1460207, -4.7118435, -11.936753 , -12.293224 ], dtype=float32)

运行结果如下,预测的结果是数字2,对应预测向量中位置下标为1的logits值最大。

image.png