- 🍨 本文为🔗365天深度学习训练营 中的学习记录博客
- 🍦 参考文章:365天深度学习训练营-第8周:猫狗识别(训练营内部成员可读)
- 🍖 原作者:K同学啊|接辅导、项目定制
作为深度学习入门阶段,我们一直都在学习CNN,后面我们会继续学习RNN,这两个是深度学习中比较常见和好用的方向,特别是在入门阶段,我们不能因为一直学相似的东西而厌倦,我们必须要坚持下去,在每一次的学习过程中总结出新的东西并将其化为自己的知识,这样我们就在慢慢进步。
在本期博客中我们将使用新的训练方式,使用model.train_on_batch方法替换之前一直使用的model.fit()方法,这个新方法我们放在后面详细介绍一下。此外在本期内我们也引入了进度条的显示方法,可以更加直观的观察模型训练过程中的情况,并打印出各项指标。
导入依赖项:
import os, pathlib
import matplotlib.pyplot as plt
import tensorflow as tf
import numpy as np
和之前一样,如果你GPU很好就只使用GPU进行训练,如果GPU不行就推荐使用CPU训练加GPU加速。
只使用GPU:
if gpus:gpu0 = gpus[0] #如果有多个GPU,仅使用第0个GPUtf.config.experimental.set_memory_growth(gpu0, True) #设置GPU显存用量按需使用tf.config.set_visible_devices([gpu0],"GPU")
使用CPU+GPU:
os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
# 支持中文
plt.rcParams['font.sans-serif'] = ['SimHei'] # 用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False # 用来正常显示负号#隐藏警告
import warnings
warnings.filterwarnings('ignore')data_dir = "E:\深度学习\data\Day17"
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
加载数据:
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)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 2720 files for training.
Found 3400 files belonging to 2 classes.
Using 680 files for validation.
然后我们再利用class_name输出我们本地数据集的标签,标签也就是对应数据所在的文件目录名:
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,)
这是一批形状224x224x3的8张图片。
AUTOTUNE = tf.data.experimental.AUTOTUNEdef 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高为10for 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)
VGG缺点
13个卷积层(Convolutional Layer),分别用blockX_convX
表示
3个全连接层(Fully connected Layer),分别用fcX
与predictions
表示
5个池化层(Pool layer),分别用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, Dropoutdef VGG16(nb_classes, input_shape):input_tensor = Input(shape=input_shape)# 1st blockx = 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 blockx = 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 blockx = 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 blockx = 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 blockx = 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 connectionx = 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 modelmodel=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函数给模型添加损失函数、优化器以及评价函数。
其中它们的作用是:
model.compile(optimizer="adam",loss ='sparse_categorical_crossentropy',metrics =['accuracy'])
其函数模型如下:
y_pred = Model.train_on_batch(x,y=None,sample_weight=None,class_weight=None,reset_metrics=True,return_dict=False,
)
其中的参数介绍:
参数 | 说明 |
---|---|
x | 模型输入,单输入就是一个 numpy 数组, 多输入就是 numpy 数组的列表 |
y | 标签,单输出模型就是一个 numpy 数组, 多输出模型就是 numpy 数组列表 |
sample_weight | mini-batch 中每个样本对应的权重,形状为 (batch_size) |
class_weight | 类别权重,作用于损失函数,为各个类别的损失添加权重,主要用于类别不平衡的情况, 形状为 (num_classes) |
reset_metrics | 默认True,返回的metrics只针对这个mini-batch, 如果False,metrics 会跨批次累积 |
return_dict | 默认 False, y_pred 为一个列表,如果 True 则 y_pred 是一个字典 |
我们一般都使用fit()方法训练模型,这个API使用起来方便很简单,对入门者非常的友好,但是由于其是非常深度的封装,对于希望自定义训练过程的同学就显得不是那么方便,所以使用train_on_batch可以相对自由一点,发挥我们自己的想法,另外对于以后我们要接触的GAN 这种需要分步进行训练的模型来说使用train_on_batch也更好。
tqdm是一个快速,可扩展的Python进度条,可以在Python 长循环中添加一个进度提示信息,用户只需要封装任意的迭代器tqdm(iterator)。 使用pip就可以安装。
使用方法也很简单:
tqdm
from tqdm import tqdmfor i in tqdm(range(100)):pass
在迭代的时候将range添加到tqdm()内即可。
trange
from tqdm import trangefor i in trange(100):pass
导入tadm中的tarnge模块替换range即可。
手动创建
pbar = tqdm(['a', 'b', 'c', 'd'])
for char in pbar:pbar.set_description("Processing %s" % char)
手动通过创建tqdm可迭代对象打印即可。
from tqdm import tqdm
import tensorflow.keras.backend as Kepochs = 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.92K.set_value(model.optimizer.lr, lr)for image,label in train_ds: 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/10: 100%|████████| 340/340 [14:41<00:00, 2.59s/it, loss=0.7081, accuracy=0.6250, lr=9.2e-5]
开始验证!
Epoch 1/10: 100%|█████████████████████| 85/85 [00:41<00:00, 2.03it/s, loss=0.6028, accuracy=0.7500]
结束验证!
验证loss为:0.6028
验证准确率为:0.7500
...
Epoch 10/10: 100%|██████| 340/340 [13:09<00:00, 2.32s/it, loss=0.0564, accuracy=1.0000, lr=4.34e-5]
开始验证!
Epoch 10/10: 100%|████████████████████| 85/85 [00:39<00:00, 2.15it/s, loss=0.0018, accuracy=1.0000]
结束验证!
验证loss为:0.0018
验证准确率为:1.0000
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()
# 采用加载的模型(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 129ms/step
1/1 [==============================] - 0s 19ms/step
1/1 [==============================] - 0s 18ms/step
1/1 [==============================] - 0s 18ms/step
1/1 [==============================] - 0s 17ms/step
1/1 [==============================] - 0s 18ms/step
1/1 [==============================] - 0s 17ms/step
1/1 [==============================] - 0s 17ms/step
预测结果如下:
K老师说本文存在一个BUG,看代码的话我看不出来哪里出错了,但是在我这里,训练模型阶段,第三个epoch的时候accuracy就等于1了,对我来说感觉有点快了,但我说不出原因,只能猜测可能跟训练集、验证集划分和使用有关。
大家对于这个有什么看法,可以讨论一下。
那么本期深度学习内容就到这里结束了,最后谢谢大家阅读!