- 🍨 本文为🔗365天深度学习训练营 中的学习记录博客
- 🍖 原作者:K同学啊 | 接辅导、项目定制
一、我的环境
1.语言环境:Python 3.9
2.编译器:Pycharm
3.深度学习环境:TensorFlow 2.10.0
二、GPU设置
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")
三、导入数据
import tensorflow as tf
from tensorflow.keras import datasets, layers, models
import matplotlib.pyplot as plt
(train_images, train_labels), (test_images, test_labels) = datasets.cifar10.load_data()
四、归一化
归一化
与标准化
是特征缩放的两种形式,其作用是:
- 使不同量纲的特征处于同一数值量级,减少方差大的特征的影响,使模型更准确。
- 加快学习算法的收敛速度。
# 将像素的值标准化至0到1的区间内。
train_images, test_images = train_images / 255.0, test_images / 255.0
print(train_images.shape,test_images.shape,train_labels.shape,test_labels.shape)
运行结果:
"""
输出:((50000, 32, 32, 3), (10000, 32, 32, 3), (50000, 1), (10000, 1))
"""
五、可视化图片
class_names = ['airplane', 'automobile', 'bird', 'cat', 'deer','dog', 'frog', 'horse', 'ship', 'truck']
plt.figure(figsize=(20,10))
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()
运行结果:
六、构建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() # 打印网络结构
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
conv2d (Conv2D) (None, 30, 30, 32) 896
max_pooling2d (MaxPooling2D (None, 15, 15, 32) 0
)
conv2d_1 (Conv2D) (None, 13, 13, 64) 18496
max_pooling2d_1 (MaxPooling (None, 6, 6, 64) 0
2D)
conv2d_2 (Conv2D) (None, 4, 4, 64) 36928
flatten (Flatten) (None, 1024) 0
dense (Dense) (None, 64) 65600
dense_1 (Dense) (None, 10) 650
=================================================================
Total params: 122,570
Trainable params: 122,570
Non-trainable params: 0
_________________________________________________________________
七、编译模型
model.compile(optimizer='adam',
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=['accuracy'])
八、训练模型
history = model.fit(train_images, train_labels, epochs=10,
validation_data=(test_images, test_labels))
1563/1563 [==============================] - 10s 3ms/step - loss: 1.5314 - accuracy: 0.4419 - val_loss: 1.2644 - val_accuracy: 0.5410
Epoch 2/10
1563/1563 [==============================] - 11s 7ms/step - loss: 1.1895 - accuracy: 0.5756 - val_loss: 1.0597 - val_accuracy: 0.6239
Epoch 3/10
1563/1563 [==============================] - 11s 7ms/step - loss: 1.0221 - accuracy: 0.6375 - val_loss: 0.9323 - val_accuracy: 0.6695
Epoch 4/10
1563/1563 [==============================] - 11s 7ms/step - loss: 0.9086 - accuracy: 0.6790 - val_loss: 0.8628 - val_accuracy: 0.7015
Epoch 5/10
1563/1563 [==============================] - 10s 7ms/step - loss: 0.8176 - accuracy: 0.7121 - val_loss: 0.8430 - val_accuracy: 0.7025
Epoch 6/10
1563/1563 [==============================] - 11s 7ms/step - loss: 0.7458 - accuracy: 0.7364 - val_loss: 0.8303 - val_accuracy: 0.7057
Epoch 7/10
1563/1563 [==============================] - 6s 4ms/step - loss: 0.6886 - accuracy: 0.7544 - val_loss: 0.8102 - val_accuracy: 0.7214
Epoch 8/10
1563/1563 [==============================] - 4s 2ms/step - loss: 0.6308 - accuracy: 0.7764 - val_loss: 0.7761 - val_accuracy: 0.7351
Epoch 9/10
1563/1563 [==============================] - 4s 3ms/step - loss: 0.5781 - accuracy: 0.7933 - val_loss: 0.7843 - val_accuracy: 0.7302
Epoch 10/10
1563/1563 [==============================] - 8s 5ms/step - loss: 0.5338 - accuracy: 0.8095 - val_loss: 0.7941 - val_accuracy: 0.7365
313/313 [==============================] - 1s 4ms/step
九、预测
plt.imshow(test_images[1])
运行结果:
import numpy as np
pre = model.predict(test_images)
print(class_names[np.argmax(pre[1])])
运行结果:
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)
运行结果:
十一、总结
本周通过学习TensorFlow实现彩色图片分类,更加了解该框架下构建CNN模型的使用,深入了解模型评估使用方法。
CIFAR-10简介
- CIFAR-10 是3 通道的彩色RGB 图像,而MNIST 是灰度图像。
- CIFAR-10 的图片尺寸为32 × 32 , 而MNIST 的图片尺寸为28 × 28 ,比MNIST 稍大。
- 相比于手写字符,CIFAR-10含有的是现实世界中真实的物体,不仅噪声很大,而且物体的比例、特征都不尽相同,这为识别带来很大困难。直接的线性模型如Softmax 在CIFAR-10 上表现得很差。