>- **🍨 本文为[🔗365天深度学习训练营](小团体~第六波) 中的学习记录博客**
>- **🍖 原作者:[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
(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 = ['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)),
layers.MaxPooling2D((2,2)),
layers.Conv2D(64,(3,3),activation='relu'),
layers.MaxPooling2D((2,2)),
layers.Conv2D(64,(3,3),activation='relu'),
layers.Dropout(0.3),
layers.Flatten(),
layers.Dense(64,activation='relu'),
layers.Dense(10)
])
三、编译
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))
Train on 50000 samples, validate on 10000 samples Epoch 1/12 50000/50000 [==============================] - 91s 2ms/sample - loss: 1.5793 - accuracy: 0.4201 - val_loss: 1.2517 - val_accuracy: 0.5556 Epoch 2/12 50000/50000 [==============================] - 74s 1ms/sample - loss: 1.2183 - accuracy: 0.5663 - val_loss: 1.0955 - val_accuracy: 0.6137 Epoch 3/12 50000/50000 [==============================] - 82s 2ms/sample - loss: 1.0833 - accuracy: 0.6190 - val_loss: 1.0281 - val_accuracy: 0.6345 Epoch 4/12 50000/50000 [==============================] - 70s 1ms/sample - loss: 0.9939 - accuracy: 0.6496 - val_loss: 0.9479 - val_accuracy: 0.6675 Epoch 5/12 50000/50000 [==============================] - 71s 1ms/sample - loss: 0.9087 - accuracy: 0.6801 - val_loss: 0.8683 - val_accuracy: 0.6989 Epoch 6/12 50000/50000 [==============================] - 46s 928us/sample - loss: 0.8534 - accuracy: 0.6996 - val_loss: 0.8908 - val_accuracy: 0.6935 Epoch 7/12 50000/50000 [==============================] - 41s 823us/sample - loss: 0.8180 - accuracy: 0.7115 - val_loss: 0.8270 - val_accuracy: 0.7138 Epoch 8/12 50000/50000 [==============================] - 43s 858us/sample - loss: 0.7790 - accuracy: 0.7270 - val_loss: 0.8048 - val_accuracy: 0.7198 Epoch 9/12 50000/50000 [==============================] - 42s 842us/sample - loss: 0.7536 - accuracy: 0.7346 - val_loss: 0.8498 - val_accuracy: 0.7085 Epoch 10/12 50000/50000 [==============================] - 41s 827us/sample - loss: 0.7250 - accuracy: 0.7439 - val_loss: 0.7828 - val_accuracy: 0.7333 Epoch 11/12 50000/50000 [==============================] - 42s 835us/sample - loss: 0.7000 - accuracy: 0.7543 - val_loss: 0.8128 - val_accuracy: 0.7200 Epoch 12/12 50000/50000 [==============================] - 41s 829us/sample - loss: 0.6784 - accuracy: 0.7610 - val_loss: 0.7695 - val_accuracy: 0.7377
五、预测
通过模型进行预测得到的是每一个类别的概率,数字越大该图片为该类别的可能性越大
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)
print(test_loss)
print(test_acc)
0.7694846038818359 0.7377