- 本文为365天深度学习训练营 中的学习记录博客
- 参考文章:365天深度学习训练营-第9周:猫狗识别-2(训练营内部成员可读)
- 原作者:K同学啊 | 接辅导、项目定制
- 文章来源:K同学的学习圈子
第9周:猫狗识别-2
要求:
- 找到并处理第8周的程序问题
拔高(可选):
- 请尝试增加数据增强部分内容以提高准确率
- 可以使用哪些方式进行数据增强?
探索(难度有点大)
- 对代码进行精简
import sys
import tensorflow as tf
import matplotlib
import matplotlib.pyplot as plt
import os,PIL,pathlib
from datetime import datetime
print("Current time: ", datetime.today())
print("tensorflow version: " + tf.__version__)
print("Python version: " + sys.version)
gpus = tf.config.list_physical_devices("GPU")
if gpus:
tf.config.experimental.set_memory_growth(gpus[0], True) #设置GPU显存用量按需使用
tf.config.set_visible_devices([gpus[0]],"GPU")
# 打印显卡信息,确认GPU可用
print("GPU: " + gpus)
else:
print("Using CPU")
Current time: 2023-11-08 22:52:49.822052
tensorflow version: 2.11.0
Python version: 3.7.8 (tags/v3.7.8:4b47a5b6ba, Jun 28 2020, 08:53:46) [MSC v.1916 64 bit (AMD64)]
Using CPU
# 支持中文
plt.rcParams['font.sans-serif'] = ['SimHei'] # 用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False # 用来正常显示负号
#隐藏警告
import warnings
warnings.filterwarnings('ignore')
data_dir = "D:/jupyter notebook/DL-100-days/datasets/Cats&Dogs Data2"
data_dir = pathlib.Path(data_dir)
image_count = len(list(data_dir.glob('*/*')))
print("图片总数为:",image_count)
图片总数为: 3400
# 设置图像
batch_size = 64
img_height = 224
img_width = 224
print("------------------------------------------------")
print("训练数据信息:")
# 设置训练数据
"""
关于image_dataset_from_directory()的详细介绍可以参考文章:https://mtyjkh.blog.csdn.net/article/details/117018789
"""
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)
print("------------------------------------------------")
print("验证数据信息:")
# 设置验证数据
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)
print("------------------------------------------------")
print("任务类别:")
# 查看类名
class_names = train_ds.class_names
print(class_names)
print("------------------------------------------------")
print("检查数据的shape:")
# 查看设置的图像数据的shape
for image_batch, labels_batch in train_ds:
print(image_batch.shape)
print(labels_batch.shape)
break
------------------------------------------------
训练数据信息:
Found 3400 files belonging to 2 classes.
Using 2720 files for training.
------------------------------------------------
验证数据信息:
Found 3400 files belonging to 2 classes.
Using 680 files for validation.
------------------------------------------------
任务类别:
['cat', 'dog']
------------------------------------------------
检查数据的shape:
(64, 224, 224, 3)
(64,)
shuffle()
: 打乱数据,关于此函数的详细介绍可以参考:https://zhuanlan.zhihu.com/p/42417456prefetch()
:预取数据,加速运行,其详细介绍可以参考我前两篇文章,里面都有讲解。cache()
:将数据集缓存到内存当中,加速运行AUTOTUNE = tf.data.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)
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")
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: "model"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
input_1 (InputLayer) [(None, 224, 224, 3)] 0
block1_conv1 (Conv2D) (None, 224, 224, 64) 1792
block1_conv2 (Conv2D) (None, 224, 224, 64) 36928
block1_pool (MaxPooling2D) (None, 112, 112, 64) 0
block2_conv1 (Conv2D) (None, 112, 112, 128) 73856
block2_conv2 (Conv2D) (None, 112, 112, 128) 147584
block2_pool (MaxPooling2D) (None, 56, 56, 128) 0
block3_conv1 (Conv2D) (None, 56, 56, 256) 295168
block3_conv2 (Conv2D) (None, 56, 56, 256) 590080
block3_conv3 (Conv2D) (None, 56, 56, 256) 590080
block3_pool (MaxPooling2D) (None, 28, 28, 256) 0
block4_conv1 (Conv2D) (None, 28, 28, 512) 1180160
block4_conv2 (Conv2D) (None, 28, 28, 512) 2359808
block4_conv3 (Conv2D) (None, 28, 28, 512) 2359808
block4_pool (MaxPooling2D) (None, 14, 14, 512) 0
block5_conv1 (Conv2D) (None, 14, 14, 512) 2359808
block5_conv2 (Conv2D) (None, 14, 14, 512) 2359808
block5_conv3 (Conv2D) (None, 14, 14, 512) 2359808
block5_pool (MaxPooling2D) (None, 7, 7, 512) 0
flatten (Flatten) (None, 25088) 0
fc1 (Dense) (None, 4096) 102764544
fc2 (Dense) (None, 4096) 16781312
predictions (Dense) (None, 1000) 4097000
=================================================================
Total params: 138,357,544
Trainable params: 138,357,544
Non-trainable params: 0
_________________________________________________________________
在准备对模型进行训练之前,还需要再对其进行一些设置。以下内容是在模型的编译步骤中添加的:
● 损失函数(loss):用于衡量模型在训练期间的准确率。
● 优化器(optimizer):决定模型如何根据其看到的数据和自身的损失函数进行更新。
● 评价函数(metrics):用于监控训练和测试步骤。以下示例使用了准确率,即被正确分类的图像的比率。
model.compile(optimizer="adam",
loss ='sparse_categorical_crossentropy',
metrics =['accuracy'])
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_total = len(train_ds)
val_total = len(val_ds)
"""
total:预期的迭代数目
ncols:控制进度条宽度
mininterval:进度更新最小间隔,以秒为单位(默认值:0.1)
"""
with tqdm(total=train_total, desc=f'Epoch {epoch + 1}/{epochs}',mininterval=1,ncols=100) as pbar:
lr = lr*0.92
K.set_value(model.optimizer.lr, lr)
train_loss = []
train_accuracy = []
for image,label in train_ds:
"""
训练模型,简单理解train_on_batch就是:它是比model.fit()更高级的一个用法
想详细了解 train_on_batch 的同学,
可以看看我的这篇文章:https://www.yuque.com/mingtian-fkmxf/hv4lcq/ztt4gy
"""
# 这里生成的是每一个batch的acc与loss
history = model.train_on_batch(image,label)
train_loss.append(history[0])
train_accuracy.append(history[1])
pbar.set_postfix({"train_loss": "%.4f"%history[0],
"train_acc":"%.4f"%history[1],
"lr": K.get_value(model.optimizer.lr)})
pbar.update(1)
history_train_loss.append(np.mean(train_loss))
history_train_accuracy.append(np.mean(train_accuracy))
print('开始验证!')
with tqdm(total=val_total, desc=f'Epoch {epoch + 1}/{epochs}',mininterval=0.3,ncols=100) as pbar:
val_loss = []
val_accuracy = []
for image,label in val_ds:
# 这里生成的是每一个batch的acc与loss
history = model.test_on_batch(image,label)
val_loss.append(history[0])
val_accuracy.append(history[1])
pbar.set_postfix({"val_loss": "%.4f"%history[0],
"val_acc":"%.4f"%history[1]})
pbar.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))
(1) jupter notebook训练速度:
Epoch 1/10: 49%|█▍ | 21/43 [15:07<15:40, 42.74s/it, train_loss=0.7520, train_acc=0.4531, lr=9.2e-5]
(2) VSCode训练速度:
VSCode训练结果如下:
Epoch 1/10: 0%| | 0/43 [00:00<?, ?it/s]2023-11-12 22:19:18.426516: W tensorflow/tsl/framework/cpu_allocator_impl.cc:82] Allocation of 822083584 exceeds 10% of free system memory.
2023-11-12 22:19:18.670829: W tensorflow/tsl/framework/cpu_allocator_impl.cc:82] Allocation of 822083584 exceeds 10% of free system memory.
2023-11-12 22:19:36.195034: W tensorflow/tsl/framework/cpu_allocator_impl.cc:82] Allocation of 822083584 exceeds 10% of free system memory.
2023-11-12 22:19:37.466240: W tensorflow/tsl/framework/cpu_allocator_impl.cc:82] Allocation of 822083584 exceeds 10% of free system memory.
Epoch 1/10: 2%| | 1/43 [00:23<16:26, 23.49s/it, train_loss=6.9070, train_acc=0.0000, lr=9.2e-5]2023-11-12 22:19:40.271657: W tensorflow/tsl/framework/cpu_allocator_impl.cc:82] Allocation of 822083584 exceeds 10% of free system memory.
Epoch 1/10: 100%|███| 43/43 [14:59<00:00, 20.91s/it, train_loss=0.6956, train_acc=0.4844, lr=9.2e-5]
开始验证!
Epoch 1/10: 100%|██████████████████| 11/11 [01:01<00:00, 5.56s/it, val_loss=0.7020, val_acc=0.5000]
结束验证!
验证loss为:0.6988
验证准确率为:0.5085
Epoch 2/10: 100%|██| 43/43 [21:52<00:00, 30.52s/it, train_loss=0.6981, train_acc=0.4375, lr=8.46e-5]
开始验证!
Epoch 2/10: 100%|██████████████████| 11/11 [00:55<00:00, 5.06s/it, val_loss=0.6970, val_acc=0.5000]
结束验证!
验证loss为:0.6884
验证准确率为:0.5085
Epoch 3/10: 100%|██| 43/43 [14:04<00:00, 19.65s/it, train_loss=0.6245, train_acc=0.7031, lr=7.79e-5]
开始验证!
Epoch 3/10: 100%|██████████████████| 11/11 [00:54<00:00, 5.00s/it, val_loss=0.7226, val_acc=0.5750]
结束验证!
验证loss为:0.6888
验证准确率为:0.5665
Epoch 4/10: 100%|██| 43/43 [13:55<00:00, 19.43s/it, train_loss=0.4985, train_acc=0.7656, lr=7.16e-5]
开始验证!
Epoch 4/10: 100%|██████████████████| 11/11 [00:54<00:00, 5.00s/it, val_loss=0.6477, val_acc=0.6250]
结束验证!
验证loss为:0.5550
验证准确率为:0.7230
Epoch 5/10: 100%|██| 43/43 [13:58<00:00, 19.49s/it, train_loss=0.3489, train_acc=0.8906, lr=6.59e-5]
开始验证!
Epoch 5/10: 100%|██████████████████| 11/11 [00:55<00:00, 5.00s/it, val_loss=0.4150, val_acc=0.8000]
结束验证!
验证loss为:0.4428
验证准确率为:0.7759
Epoch 6/10: 100%|██| 43/43 [14:00<00:00, 19.56s/it, train_loss=0.2207, train_acc=0.9219, lr=6.06e-5]
开始验证!
Epoch 6/10: 100%|██████████████████| 11/11 [00:55<00:00, 5.01s/it, val_loss=0.1597, val_acc=0.9250]
结束验证!
验证loss为:0.1626
验证准确率为:0.9534
Epoch 7/10: 100%|██| 43/43 [13:59<00:00, 19.53s/it, train_loss=0.0242, train_acc=1.0000, lr=5.58e-5]
开始验证!
Epoch 7/10: 100%|██████████████████| 11/11 [00:55<00:00, 5.02s/it, val_loss=0.0334, val_acc=1.0000]
结束验证!
验证loss为:0.0933
验证准确率为:0.9631
Epoch 8/10: 100%|██| 43/43 [14:01<00:00, 19.57s/it, train_loss=0.0312, train_acc=0.9844, lr=5.13e-5]
开始验证!
Epoch 8/10: 100%|██████████████████| 11/11 [00:55<00:00, 5.01s/it, val_loss=0.0500, val_acc=1.0000]
结束验证!
验证loss为:0.0845
验证准确率为:0.9716
Epoch 9/10: 100%|██| 43/43 [13:57<00:00, 19.47s/it, train_loss=0.0245, train_acc=1.0000, lr=4.72e-5]
开始验证!
Epoch 9/10: 100%|██████████████████| 11/11 [00:55<00:00, 5.01s/it, val_loss=0.0045, val_acc=1.0000]
结束验证!
验证loss为:0.0594
验证准确率为:0.9815
Epoch 10/10: 100%|█| 43/43 [13:58<00:00, 19.51s/it, train_loss=0.0117, train_acc=1.0000, lr=4.34e-5]
开始验证!
Epoch 10/10: 100%|█████████████████| 11/11 [00:55<00:00, 5.02s/it, val_loss=0.0018, val_acc=1.0000]
结束验证!
验证loss为:0.0667
验证准确率为:0.9801
import numpy as np
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()
# 采用加载的模型(new_model)来看预测结果
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")
1/1 [==============================] - 0s 280ms/step
1/1 [==============================] - 0s 98ms/step
1/1 [==============================] - 0s 102ms/step
1/1 [==============================] - 0s 110ms/step
1/1 [==============================] - 0s 109ms/step
1/1 [==============================] - 0s 118ms/step
1/1 [==============================] - 0s 114ms/step
1/1 [==============================] - 0s 117ms/step