>- **🍨 本文为[🔗365天深度学习训练营](https://mp.weixin.qq.com/s/0dvHCaOoFnW8SCp3JpzKxg) 中的学习记录博客**
>- **🍖 原作者:[K同学啊](https://mtyjkh.blog.csdn.net/)**
我的环境
语言环境:Python 3.9.13
编译器:jupyter notebook
深度学习环境:Tensorflow-gpu 2.7.0
一、前期准备
1.设置GPU(没有GPU的可以忽略)
#设置GPU
import tensorflow as tf
gpus = tf.config.list_physical_devices("GPU")
2.导入数据
#导入数据
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()
3.归一化
#归一化
# 将像素的值标准化至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
((50000, 32, 32, 3), (10000, 32, 32, 3), (50000, 1), (10000, 1))
4.可视化
# 可视化。
class_names = ['airpalne', '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网络
构建CNN网络模型
#构建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(),
layers.Dense(64, activation='relu'), #Flatten层,连接卷积层与全连接层
layers.Dense(10)
])
model.summary() #打印网络结构
Model: "sequential_1" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= conv2d_3 (Conv2D) (None, 30, 30, 32) 896 max_pooling2d_2 (MaxPooling (None, 15, 15, 32) 0 2D) conv2d_4 (Conv2D) (None, 13, 13, 64) 18496 max_pooling2d_3 (MaxPooling (None, 6, 6, 64) 0 2D) conv2d_5 (Conv2D) (None, 4, 4, 64) 36928 flatten_1 (Flatten) (None, 1024) 0 dense_2 (Dense) (None, 64) 65600 dense_3 (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))
Epoch 1/10 1563/1563 [==============================] - 4s 2ms/step - loss: 1.5697 - accuracy: 0.4254 - val_loss: 1.2839 - val_accuracy: 0.5417 Epoch 2/10 1563/1563 [==============================] - 4s 2ms/step - loss: 1.2034 - accuracy: 0.5723 - val_loss: 1.1407 - val_accuracy: 0.5947 Epoch 3/10 1563/1563 [==============================] - 4s 2ms/step - loss: 1.0472 - accuracy: 0.6318 - val_loss: 1.0527 - val_accuracy: 0.6282 Epoch 4/10 1563/1563 [==============================] - 4s 3ms/step - loss: 0.9459 - accuracy: 0.6668 - val_loss: 0.9622 - val_accuracy: 0.6634 Epoch 5/10 1563/1563 [==============================] - 4s 3ms/step - loss: 0.8667 - accuracy: 0.6952 - val_loss: 0.9198 - val_accuracy: 0.6762 Epoch 6/10 1563/1563 [==============================] - 4s 2ms/step - loss: 0.8090 - accuracy: 0.7161 - val_loss: 0.8993 - val_accuracy: 0.6831 Epoch 7/10 1563/1563 [==============================] - 4s 3ms/step - loss: 0.7539 - accuracy: 0.7365 - val_loss: 0.8768 - val_accuracy: 0.6982 Epoch 8/10 1563/1563 [==============================] - 4s 2ms/step - loss: 0.7082 - accuracy: 0.7507 - val_loss: 0.8688 - val_accuracy: 0.7049 Epoch 9/10 1563/1563 [==============================] - 4s 3ms/step - loss: 0.6712 - accuracy: 0.7647 - val_loss: 0.8618 - val_accuracy: 0.7039 Epoch 10/10 1563/1563 [==============================] - 4s 3ms/step - loss: 0.6319 - accuracy: 0.7779 - val_loss: 0.8827 - val_accuracy: 0.7008
五、预测模型
#预测模型
plt.imshow(test_images[1])
<matplotlib.image.AxesImage at 0x14adecf0ac0>
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('Accurary')
plt.ylim([0.5, 1])
plt.legend(loc = 'lower right')
plt.show()
test_loss, test_acc = model.evaluate(test_images, test_labels, verbose=2)
313/313 - 0s - loss: 0.8827 - accuracy: 0.7008 - 444ms/epoch - 1ms/step
print(test_acc)
0.7008000016212463