>- **🍨 本文为[🔗365天深度学习训练营](https://mp.weixin.qq.com/s/rbOOmire8OocQ90QM78DRA) 中的学习记录博客**
>- **🍖 原作者:[K同学啊 | 接辅导、项目定制](https://mtyjkh.blog.csdn.net/)**
🏡 我的环境:
- 语言环境:Python3.7
- 编译器:jupyter lab
- 深度学习环境:Pytorch
一、前期工作
1. 设置GPU
如果使用的是CPU可以忽略这步
import tensorflow as tf
gpus = tf.config.list_physical_devices("GPU")
if gpus:
gpu0 = gpus[0]
tf.config.experimental.set_memory_growth(gpu0, True)
tf.config.set_visible_devices([gpu0],"GPU")
2. 导入数据
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()
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
"""
输出:((60000, 28, 28), (10000, 28, 28), (60000,), (10000,))
"""
4. 可视化图片
plt.figure(figsize=(20,5))
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()
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
"""
输出:((60000, 28, 28, 1), (10000, 28, 28, 1), (60000,), (10000,))
"""
((60000, 28, 28, 1), (10000, 28, 28, 1), (60000,), (10000,))
二、构建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()
Model: "sequential" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= conv2d_2 (Conv2D) (None, 26, 26, 32) 320 _________________________________________________________________ max_pooling2d_2 (MaxPooling2 (None, 13, 13, 32) 0 _________________________________________________________________ conv2d_3 (Conv2D) (None, 11, 11, 64) 18496 _________________________________________________________________ max_pooling2d_3 (MaxPooling2 (None, 5, 5, 64) 0 _________________________________________________________________ flatten_1 (Flatten) (None, 1600) 0 _________________________________________________________________ dense (Dense) (None, 64) 102464 _________________________________________________________________ dense_1 (Dense) (None, 10) 650 ================================================================= Total params: 121,930 Trainable params: 121,930 Non-trainable params: 0 _________________________________________________________________
三、编译模型
model.compile(
optimizer='adam',
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=['accuracy'])
四、训练模型
"""
这里设置输入训练数据集(图片及标签)、验证数据集(图片及标签)以及迭代次数epochs
关于model.fit()函数的具体介绍可参考我的博客:
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))
Train on 60000 samples, validate on 10000 samples Epoch 1/10 60000/60000 [==============================] - 29s 479us/sample - loss: 0.1371 - accuracy: 0.9580 - val_loss: 0.0533 - val_accuracy: 0.9828 Epoch 2/10 60000/60000 [==============================] - 43s 713us/sample - loss: 0.0453 - accuracy: 0.9861 - val_loss: 0.0502 - val_accuracy: 0.9837 Epoch 3/10 60000/60000 [==============================] - 41s 678us/sample - loss: 0.0329 - accuracy: 0.9897 - val_loss: 0.0307 - val_accuracy: 0.9905 Epoch 4/10 60000/60000 [==============================] - 34s 565us/sample - loss: 0.0241 - accuracy: 0.9922 - val_loss: 0.0321 - val_accuracy: 0.9900 Epoch 5/10 60000/60000 [==============================] - 38s 633us/sample - loss: 0.0182 - accuracy: 0.9942 - val_loss: 0.0293 - val_accuracy: 0.9906 Epoch 6/10 60000/60000 [==============================] - 28s 464us/sample - loss: 0.0137 - accuracy: 0.9955 - val_loss: 0.0311 - val_accuracy: 0.9901 Epoch 7/10 60000/60000 [==============================] - 28s 474us/sample - loss: 0.0114 - accuracy: 0.9960 - val_loss: 0.0268 - val_accuracy: 0.9914 Epoch 8/10 60000/60000 [==============================] - 28s 473us/sample - loss: 0.0090 - accuracy: 0.9968 - val_loss: 0.0255 - val_accuracy: 0.9924 Epoch 9/10 60000/60000 [==============================] - 30s 497us/sample - loss: 0.0085 - accuracy: 0.9970 - val_loss: 0.0331 - val_accuracy: 0.9908 Epoch 10/10 60000/60000 [==============================] - 32s 528us/sample - loss: 0.0070 - accuracy: 0.9977 - val_loss: 0.0354 - val_accuracy: 0.9898
五、预测
通过下面的网络结构我们可以简单理解为,输入一张图片,将会得到一组数,这组代表这张图片上的数字为0~9中每一个数字的几率(并非概率),out数字越大可能性越大,仅此而已。
plt.imshow(test_images[1])
输出测试集中第一张图片的预测结果
pre = model.predict(test_images) # 对所有测试图片进行预测
pre[1] # 输出第一张图片的预测结果
array([ -5.368167 , 1.1820979, 25.743433 , -12.965738 , 3.3225708, -20.655327 , -2.0122333, -5.63238 , -3.7606869, -6.555772 ], dtype=float32)