- 🍨 本文为🔗365天深度学习训练营 中的学习记录博客
- 🍖 原作者:K同学啊 | 接辅导、项目定制
一、前期工作
1.设置GPU
import tensorflow as tf
gpus = tf.config.list_physical_devices("GPU")
if gpus:
tf.config.experimental.set_memory_growth(gpus[0], True)
tf.config.set_visible_devices([gpus[0]],"GPU")
print(gpus)
输出
[PhysicalDevice(name=‘/physical_device:GPU:0’, device_type=‘GPU’)]
2.导入数据
import matplotlib.pyplot as plt
# 支持中文
plt.rcParams['font.sans-serif'] = ['SimHei'] # 用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False # 用来正常显示负号
import os,PIL,pathlib
#隐藏警告
import warnings
warnings.filterwarnings('ignore')
data_dir = "./P8/"
data_dir = pathlib.Path(data_dir)
image_count = len(list(data_dir.glob('*/*')))
print("图片总数为:",image_count)
输出
图片总数为: 3402
二、数据预处理
1.加载数据
batch_size = 64
img_height = 224
img_width = 224
train_ds = tf.keras.preprocessing.image_dataset_from_directory(
data_dir,
validation_split=0.2,
subset="training",
seed=12,
image_size=(img_height, img_width),
batch_size=batch_size)
输出
Found 3403 files belonging to 2 classes.
Using 2723 files for training.
val_ds = tf.keras.preprocessing.image_dataset_from_directory(
data_dir,
validation_split=0.2,
subset="validation",
seed=12,
image_size=(img_height, img_width),
batch_size=batch_size)
输出
Found 3403 files belonging to 2 classes.
Using 680 files for validation.
class_names = train_ds.class_names
print(class_names)
输出
[‘cat’, ‘dog’]
2.再次检查数据
for image_batch, labels_batch in train_ds:
print(image_batch.shape)
print(labels_batch.shape)
break
输出
(64, 224, 224, 3)
(64,)# 3.配置数据集
代码知识点
tf.data.AUTOTUNE
是一个特殊的值,用于在TensorFlow中自动调整数据集的并行处理参数。- 定义了
preprocess_image
函数,它接受两个参数:image和label。这个函数的作用是将输入的图像进行归一化处理,即将像素值除以255,使得像素值的范围在0到1之间。同时,函数返回一个元组,包含归一化后的图像和对应的标签。- 分别对训练集(train_ds)和验证集(val_ds)进行映射操作。映射操作使用
preprocess_image
函数对每个元素进行处理,并使用num_parallel_calls=AUTOTUNE参数来指定并行调用的数量。这样可以在多个CPU核心上并行处理数据,提高数据处理速度。- 最后两行代码对训练集和验证集进行了缓存、随机打乱和预取操作。缓存操作将数据集存储在内存中,以便快速访问;随机打乱操作将数据集中的样本随机排列;预取操作则在数据读取时提前加载一部分数据到内存中,以便后续操作能够更快地获取数据。这些操作可以提高数据处理的效率。
AUTOTUNE = tf.data.experimental.AUTOTUNE
def preprocess_image(image,label):
return (image/255.0,label)
# 归一化处理
train_ds = train_ds.map(preprocess_image, num_parallel_calls=AUTOTUNE)
val_ds = val_ds.map(preprocess_image, num_parallel_calls=AUTOTUNE)
train_ds = train_ds.cache().shuffle(1000).prefetch(buffer_size=AUTOTUNE)
val_ds = val_ds.cache().prefetch(buffer_size=AUTOTUNE)
4.可视化数据
plt.figure(figsize=(15, 10)) # 图形的宽为15高为10
for images, labels in train_ds.take(1):
for i in range(8):
ax = plt.subplot(5, 8, i + 1)
plt.imshow(images[i])
plt.title(class_names[labels[i]])
plt.axis("off")
输出
三、构建VGG网络
from tensorflow.keras import layers, models, Input
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Conv2D, MaxPooling2D, Dense, Flatten, Dropout
def VGG16(nb_classes, input_shape):
input_tensor = Input(shape=input_shape)
# 1st block
x = Conv2D(64, (3,3), activation='relu', padding='same',name='block1_conv1')(input_tensor)
x = Conv2D(64, (3,3), activation='relu', padding='same',name='block1_conv2')(x)
x = MaxPooling2D((2,2), strides=(2,2), name = 'block1_pool')(x)
# 2nd block
x = Conv2D(128, (3,3), activation='relu', padding='same',name='block2_conv1')(x)
x = Conv2D(128, (3,3), activation='relu', padding='same',name='block2_conv2')(x)
x = MaxPooling2D((2,2), strides=(2,2), name = 'block2_pool')(x)
# 3rd block
x = Conv2D(256, (3,3), activation='relu', padding='same',name='block3_conv1')(x)
x = Conv2D(256, (3,3), activation='relu', padding='same',name='block3_conv2')(x)
x = Conv2D(256, (3,3), activation='relu', padding='same',name='block3_conv3')(x)
x = MaxPooling2D((2,2), strides=(2,2), name = 'block3_pool')(x)
# 4th block
x = Conv2D(512, (3,3), activation='relu', padding='same',name='block4_conv1')(x)
x = Conv2D(512, (3,3), activation='relu', padding='same',name='block4_conv2')(x)
x = Conv2D(512, (3,3), activation='relu', padding='same',name='block4_conv3')(x)
x = MaxPooling2D((2,2), strides=(2,2), name = 'block4_pool')(x)
# 5th block
x = Conv2D(512, (3,3), activation='relu', padding='same',name='block5_conv1')(x)
x = Conv2D(512, (3,3), activation='relu', padding='same',name='block5_conv2')(x)
x = Conv2D(512, (3,3), activation='relu', padding='same',name='block5_conv3')(x)
x = MaxPooling2D((2,2), strides=(2,2), name = 'block5_pool')(x)
# full connection
x = Flatten()(x)
x = Dense(4096, activation='relu', name='fc1')(x)
x = Dense(4096, activation='relu', name='fc2')(x)
output_tensor = Dense(nb_classes, activation='softmax', name='predictions')(x)
model = Model(input_tensor, output_tensor)
return model
model=VGG16(1000, (img_width, img_height, 3))
model.summary()
输出
四、编译
model.compile(optimizer="adam",
loss ='sparse_categorical_crossentropy',
metrics =['accuracy'])
五、训练模型
这是精简化后的代码
使用 with tqdm() 作为上下文管理器可以简化代码,
并在循环中直接使用 pbar 而不是手动更新进度条。
不需要在循环开始时设置学习率,可以在训练循环开始之前设置它。
可以合并训练和验证的准确性和损失值的计算,以减少重复代码。
from tqdm import tqdm
import tensorflow.keras.backend as K
epochs = 10
lr = 1e-4
history_train_loss = []
history_train_accuracy = []
history_val_loss = []
history_val_accuracy = []
for epoch in range(epochs):
train_loss = []
train_accuracy = []
val_loss = []
val_accuracy = []
pbar_train = tqdm(total=len(train_ds), desc=f'Epoch {epoch + 1}/{epochs}', mininterval=43, ncols=100)
pbar_val = tqdm(total=len(val_ds), desc=f'Epoch {epoch + 1}/{epochs}', mininterval=11, ncols=100)
lr = lr * 0.97
K.set_value(model.optimizer.lr, lr)
for image, label in train_ds:
history = model.train_on_batch(image, label)
train_loss.append(history[0])
train_accuracy.append(history[1])
pbar_train.set_postfix({"train_loss": "%.4f" % history[0],
"train_acc": "%.4f" % history[1],
"lr": K.get_value(model.optimizer.lr)})
pbar_train.update(1)
history_train_loss.append(np.mean(train_loss))
history_train_accuracy.append(np.mean(train_accuracy))
print('开始验证!')
for image, label in val_ds:
history = model.test_on_batch(image, label)
val_loss.append(history[0])
val_accuracy.append(history[1])
pbar_val.set_postfix({"val_loss": "%.4f" % history[0],
"val_acc": "%.4f" % history[1]})
pbar_val.update(1)
history_val_loss.append(np.mean(val_loss))
history_val_accuracy.append(np.mean(val_accuracy))
print('结束验证!')
print("验证loss为:%.4f" % np.mean(val_loss))
print("验证准确率为:%.4f" % np.mean(val_accuracy))
输出
Epoch 1/10: 100%|███| 86/86 [00:11<00:00, 7.64it/s, train_loss=0.1023, train_acc=0.9688, lr=9.2e-5]
开始验证!
Epoch 1/10: 100%|██████████████████| 22/22 [00:01<00:00, 17.22it/s, val_loss=0.0022, val_acc=1.0000]
结束验证!
验证loss为:0.0730
验证准确率为:0.9673
Epoch 2/10: 100%|██| 86/86 [00:11<00:00, 7.80it/s, train_loss=0.0050, train_acc=1.0000, lr=8.46e-5]
开始验证!
Epoch 2/10: 100%|██████████████████| 22/22 [00:01<00:00, 18.04it/s, val_loss=0.1671, val_acc=0.8750]
结束验证!
验证loss为:0.0382
验证准确率为:0.9830
Epoch 3/10: 100%|██| 86/86 [00:11<00:00, 7.80it/s, train_loss=0.0034, train_acc=1.0000, lr=7.79e-5]
开始验证!
Epoch 3/10: 100%|██████████████████| 22/22 [00:01<00:00, 16.95it/s, val_loss=0.6676, val_acc=0.8750]
结束验证!
验证loss为:0.0675
验证准确率为:0.9801
Epoch 4/10: 100%|██| 86/86 [00:11<00:00, 7.79it/s, train_loss=0.0008, train_acc=1.0000, lr=7.16e-5]
开始验证!
Epoch 4/10: 100%|██████████████████| 22/22 [00:01<00:00, 18.16it/s, val_loss=0.4470, val_acc=0.8750]
结束验证!
验证loss为:0.0327
验证准确率为:0.9901
Epoch 5/10: 100%|██| 86/86 [00:11<00:00, 7.80it/s, train_loss=0.0001, train_acc=1.0000, lr=6.59e-5]
开始验证!
Epoch 5/10: 100%|██████████████████| 22/22 [00:01<00:00, 17.79it/s, val_loss=0.0001, val_acc=1.0000]
结束验证!
验证loss为:0.0127
验证准确率为:0.9972
Epoch 6/10: 100%|██| 86/86 [00:10<00:00, 7.87it/s, train_loss=0.0007, train_acc=1.0000, lr=6.06e-5]
开始验证!
Epoch 6/10: 100%|██████████████████| 22/22 [00:01<00:00, 17.76it/s, val_loss=0.0000, val_acc=1.0000]
结束验证!
验证loss为:0.0211
验证准确率为:0.9972
Epoch 7/10: 100%|██| 86/86 [00:10<00:00, 7.86it/s, train_loss=0.0000, train_acc=1.0000, lr=5.58e-5]
开始验证!
Epoch 7/10: 100%|██████████████████| 22/22 [00:01<00:00, 17.68it/s, val_loss=0.0002, val_acc=1.0000]
结束验证!
验证loss为:0.0187
验证准确率为:0.9986
Epoch 8/10: 100%|██| 86/86 [00:10<00:00, 7.86it/s, train_loss=0.0000, train_acc=1.0000, lr=5.13e-5]
开始验证!
Epoch 8/10: 100%|██████████████████| 22/22 [00:01<00:00, 17.66it/s, val_loss=0.0002, val_acc=1.0000]
结束验证!
验证loss为:0.0182
验证准确率为:0.9986
Epoch 9/10: 100%|██| 86/86 [00:11<00:00, 7.76it/s, train_loss=0.0000, train_acc=1.0000, lr=4.72e-5]
开始验证!
Epoch 9/10: 100%|██████████████████| 22/22 [00:01<00:00, 17.53it/s, val_loss=0.0002, val_acc=1.0000]
结束验证!
验证loss为:0.0186
验证准确率为:0.9986
Epoch 10/10: 100%|█| 86/86 [00:11<00:00, 7.80it/s, train_loss=0.0001, train_acc=1.0000, lr=4.34e-5]
开始验证!
Epoch 10/10: 100%|█████████████████| 22/22 [00:01<00:00, 16.99it/s, val_loss=0.0002, val_acc=1.0000]
结束验证!
验证loss为:0.0186
验证准确率为:0.9986
六、模型评估
epochs_range = range(epochs)
plt.figure(figsize=(14, 4))
plt.subplot(1, 2, 1)
plt.plot(epochs_range, history_train_accuracy, label='Training Accuracy')
plt.plot(epochs_range, history_val_accuracy, label='Validation Accuracy')
plt.legend(loc='lower right')
plt.title('Training and Validation Accuracy')
plt.subplot(1, 2, 2)
plt.plot(epochs_range, history_train_loss, label='Training Loss')
plt.plot(epochs_range, history_val_loss, label='Validation Loss')
plt.legend(loc='upper right')
plt.title('Training and Validation Loss')
plt.show()
输出
七、预测
import numpy as np
plt.figure(figsize=(18, 3)) # 图形的宽为18高为5
plt.suptitle("预测结果展示")
for images, labels in val_ds.take(1):
for i in range(8):
ax = plt.subplot(1,8, i + 1)
plt.imshow(images[i].numpy())
img_array = tf.expand_dims(images[i], 0)
predictions = model.predict(img_array)
plt.title(class_names[np.argmax(predictions)])
plt.axis("off")
输出