本文为365天深度学习训练营内部限免文章
参考本文所写记录性文章,请在文章开头保留以下内容
- 本文为365天深度学习训练营 中的学习记录博客
- 参考文章:365天深度学习训练营-第8周:猫狗识别(训练营内部成员可读)
- 原作者:K同学啊|接辅导、项目定制
● 难度:夯实基础⭐⭐
● 语言:Python3、TensorFlow2
● 时间:9月12-9月16日
要求:
- 了解model.train_on_batch()并运用
- 了解tqdm,并使用tqdm实现可视化进度条
拔高(可选):
- 本文代码中存在一个严重的BUG,请找出它并配以文字说明
探索(难度有点大)
- 修改代码,处理BUG
这篇文章中我放弃了以往的model.fit()训练方法,改用model.train_on_batch方法。两种方法的比较:
model.fit()
:用起来十分简单,对新手非常友好model.train_on_batch()
:封装程度更低,可以玩更多花样。此外我也引入了进度条的显示方式,更加方便我们及时查看模型训练过程中的情况,可以及时打印各项指标。
我的环境:
如果使用的是CPU可以注释掉这部分的代码。
import tensorflow as tf
gpus = tf.config.list_physical_devices("GPU")
if gpus:
tf.config.experimental.set_memory_growth(gpus[0], True) #设置GPU显存用量按需使用
tf.config.set_visible_devicese_devices([gpus[0]],"GPU")
# 打印显卡信息,确认GPU可用
print(gpus)
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 = "./365-7-data"
data_dir = pathlib.Path(data_dir)
image_count = len(list(data_dir.glob('*/*')))
print("图片总数为:",image_count)
图片总数为: 3400
使用image_dataset_from_directory
方法将磁盘中的数据加载到tf.data.Dataset
中
batch_size = 8
img_height = 224
img_width = 224
TensorFlow版本是2.2.0的同学可能会遇到module 'tensorflow.keras.preprocessing' has no attribute 'image_dataset_from_directory'
的报错,升级一下TensorFlow就OK了。
"""
关于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)
Found 3400 files belonging to 2 classes.
Using 2720 files for training.
"""
关于image_dataset_from_directory()的详细介绍可以参考文章:https://mtyjkh.blog.csdn.net/article/details/117018789
"""
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 3400 files belonging to 2 classes.
Using 680 files for validation.
我们可以通过class_names输出数据集的标签。标签将按字母顺序对应于目录名称。
class_names = train_ds.class_names
print(class_names)
['cat', 'dog']
for image_batch, labels_batch in train_ds:
print(image_batch.shape)
print(labels_batch.shape)
break
(8, 224, 224, 3)
(8,)
Image_batch
是形状的张量(8, 224, 224, 3)。这是一批形状224x224x3的8张图片(最后一维指的是彩色通道RGB)。Label_batch
是形状(8,)的张量,这些标签对应8张图片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)
如果报 AttributeError: module 'tensorflow._api.v2.data' has no attribute 'AUTOTUNE'
错误,就将 AUTOTUNE = tf.data.AUTOTUNE
更换为 AUTOTUNE = tf.data.experimental.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")
VGG优缺点分析:
VGG的结构非常简洁,整个网络都使用了同样大小的卷积核尺寸(3x3)和最大池化尺寸(2x2)。
1)训练时间过长,调参难度大。2)需要的存储容量大,不利于部署。例如存储VGG-16权重值文件的大小为500多MB,不利于安装到嵌入式系统中。
结构说明:
blockX_convX
表示fcX
与predictions
表示blockX_pool
表示VGG-16
包含了16个隐藏层(13个卷积层和3个全连接层),故称为VGG-16
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
_________________________________________________________________
在准备对模型进行训练之前,还需要再对其进行一些设置。以下内容是在模型的编译步骤中添加的:
model.compile(optimizer="adam",
loss ='sparse_categorical_crossentropy',
metrics =['accuracy'])
from tqdm import tqdm
import tensorflow.keras.backend as K
epochs = 5
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)
for image,label in train_ds:
"""
训练模型,简单理解train_on_batch就是:它是比model.fit()更高级的一个用法
想详细了解 train_on_batch 的同学,
可以看看我的这篇文章:https://www.yuque.com/mingtian-fkmxf/hv4lcq/ztt4gy
"""
history = model.train_on_batch(image,label)
train_loss = history[0]
train_accuracy = history[1]
pbar.set_postfix({"loss": "%.4f"%train_loss,
"accuracy":"%.4f"%train_accuracy,
"lr": K.get_value(model.optimizer.lr)})
pbar.update(1)
history_train_loss.append(train_loss)
history_train_accuracy.append(train_accuracy)
print('开始验证!')
with tqdm(total=val_total, desc=f'Epoch {epoch + 1}/{epochs}',mininterval=0.3,ncols=100) as pbar:
for image,label in val_ds:
history = model.test_on_batch(image,label)
val_loss = history[0]
val_accuracy = history[1]
pbar.set_postfix({"loss": "%.4f"%val_loss,
"accuracy":"%.4f"%val_accuracy})
pbar.update(1)
history_val_loss.append(val_loss)
history_val_accuracy.append(val_accuracy)
print('结束验证!')
print("验证loss为:%.4f"%val_loss)
print("验证准确率为:%.4f"%val_accuracy)
Epoch 1/5: 100%|█████████| 340/340 [15:43<00:00, 2.78s/it, loss=0.6659, accuracy=0.6250, lr=9.2e-5]
开始验证!
Epoch 1/5: 100%|██████████████████████| 85/85 [00:18<00:00, 4.65it/s, loss=0.6411, accuracy=0.6250]
结束验证!
验证loss为:0.6411
验证准确率为:0.6250
Epoch 2/5: 100%|████████| 340/340 [15:32<00:00, 2.74s/it, loss=0.2041, accuracy=0.8750, lr=8.46e-5]
开始验证!
Epoch 2/5: 100%|██████████████████████| 85/85 [00:18<00:00, 4.63it/s, loss=0.1111, accuracy=1.0000]
结束验证!
验证loss为:0.1111
验证准确率为:1.0000
Epoch 3/5: 100%|████████| 340/340 [15:33<00:00, 2.75s/it, loss=0.0193, accuracy=1.0000, lr=7.79e-5]
开始验证!
Epoch 3/5: 100%|██████████████████████| 85/85 [00:17<00:00, 4.88it/s, loss=0.0298, accuracy=1.0000]
结束验证!
验证loss为:0.0298
验证准确率为:1.0000
Epoch 4/5: 100%|████████| 340/340 [15:31<00:00, 2.74s/it, loss=0.0035, accuracy=1.0000, lr=7.16e-5]
开始验证!
Epoch 4/5: 100%|██████████████████████| 85/85 [00:17<00:00, 4.76it/s, loss=0.0006, accuracy=1.0000]
结束验证!
验证loss为:0.0006
验证准确率为:1.0000
Epoch 5/5: 100%|████████| 340/340 [15:31<00:00, 2.74s/it, loss=0.0003, accuracy=1.0000, lr=6.59e-5]
开始验证!
Epoch 5/5: 100%|██████████████████████| 85/85 [00:18<00:00, 4.55it/s, loss=0.0013, accuracy=1.0000]
结束验证!
验证loss为:0.0013
验证准确率为:1.0000
# 这是我们之前的训练方法。
# history = model.fit(
# train_ds,
# validation_data=val_ds,
# epochs=epochs
# )
epochs_range = range(epochs)
plt.figure(figsize=(12, 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()
findfont: Font family ['sans-serif'] not found. Falling back to DejaVu Sans.
findfont: Generic family 'sans-serif' not found because none of the following families were found: SimHei
from pyecharts.charts import *
import pyecharts.options as opts
from pyecharts.globals import ThemeType
loss = history_train_loss
val_loss = history_val_loss
acc = history_train_accuracy
val_acc = history_val_accuracy
line_loss = Line()
line_loss.add_xaxis([i for i in range(5)])
line_loss.add_yaxis('loss', loss, label_opts=opts.LabelOpts(is_show=False))
line_loss.add_yaxis('val_loss', val_loss, label_opts=opts.LabelOpts(is_show=False))
line_loss.set_global_opts(legend_opts=opts.LegendOpts(pos_top='5%',pos_left='20%'),
tooltip_opts=opts.TooltipOpts(trigger="axis", axis_pointer_type="line"))
line_acc = Line()
line_acc.add_xaxis([i for i in range(5)])
line_acc.add_yaxis('accuracy', acc, label_opts=opts.LabelOpts(is_show=False))
line_acc.add_yaxis('val_accuracy', val_acc, label_opts=opts.LabelOpts(is_show=False))
line_acc.set_global_opts(title_opts=opts.TitleOpts('模型训练过程效果记录', pos_left='center'),
legend_opts=opts.LegendOpts(pos_top='5%', pos_left='65%'),
yaxis_opts=opts.AxisOpts(is_scale=True),
tooltip_opts=opts.TooltipOpts(trigger="axis", axis_pointer_type="line"))
grid = Grid(init_opts=opts.InitOpts(theme=ThemeType.CHALK))
grid.add(line_loss,grid_opts=opts.GridOpts(pos_left='5%', pos_right='55%'))
grid.add(line_acc,grid_opts=opts.GridOpts(pos_left='55%', pos_right='5%'))
grid.render_notebook()
import numpy as np
# 采用加载的模型(new_model)来看预测结果
plt.figure(figsize=(18, 3)) # 图形的宽为18高为5
plt.suptitle("The prediction")
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 134ms/step
1/1 [==============================] - 0s 137ms/step
1/1 [==============================] - 0s 147ms/step
1/1 [==============================] - 0s 141ms/step
1/1 [==============================] - 0s 132ms/step
1/1 [==============================] - 0s 129ms/step
1/1 [==============================] - 0s 149ms/step
1/1 [==============================] - 0s 123ms/step
#隐藏警告
import warnings
warnings.filterwarnings('ignore')
data_dir = "./test/"
data_dir = pathlib.Path(data_dir)
image_count = len(list(data_dir.glob('*/*')))
print("图片总数为:",image_count)
图片总数为: 4
from PIL import Image
import numpy as np
for images, labels in testbyme_ds.take(1):
for i in range(4):
ax = plt.subplot(1,4, i + 1)
# 显示图片
plt.imshow(images[i].numpy().astype("uint8"))
# 需要给图片增加一个维度
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 148ms/step
1/1 [==============================] - 0s 126ms/step
1/1 [==============================] - 0s 121ms/step
1/1 [==============================] - 0s 146ms/step
plt.figure(figsize=(10, 4)) # 图形的宽为10高为5
for images, labels in testbyme_ds.take(1):
for i in range(4):
ax = plt.subplot(2, 5, i + 1)
plt.imshow(images[i].numpy().astype("uint8"))
plt.title(class_names[labels[i]])
plt.axis("off")
模型还是有一些欠佳,需要进一步完善优化,待续……