- 本文为365天深度学习训练营 中的学习记录博客
- 参考文章:365天深度学习训练营-第7周:咖啡豆识别(训练营内部成员可读)
- 原作者:K同学啊|接辅导、项目定制
因为种种原因,我已经差不多两个星期没有更新有关深度学习方面的博客了,因为我拿不到我这个性能好的电脑,手上只有一个轻薄本没有深度学习环境也带不动这些程序。
不过现在都解决了,可以接着开始学习了,本期我们承接上文,我们仍然学习的是RNN,本期我们将自己搭建VGG-16网络框架进行操作。
浪费了两个星期的时间,我们也不再废话了直接开始工作。
导入依赖项:
from tensorflow import keras
from tensorflow.keras import layers,models
import os, PIL, 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个GPU
tf.config.experimental.set_memory_growth(gpu0, True) #设置GPU显存用量按需使用
tf.config.set_visible_devices([gpu0],"GPU")
使用CPU+GPU:
os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
data_dir = "E:\Deep_Learning\data\Day16"
data_dir = pathlib.Path(data_dir)
查看数据集内有多少张图片:
image_count = len(list(data_dir.glob('*/*.png')))
print("图片总数为:",image_count)
运行的结果是:
图片总数为: 1200
从数据集内返回一张图片查看一下:
roses = list(data_dir.glob('Dark/*.png'))
PIL.Image.open(str(roses[0]))
我们使用image_dataset_from_directory方法将我们本地的数据加载到tf.data.Dataset
中,并设置训练图片模型参数:
batch_size = 32
img_height = 224
img_width = 224
接下来加载数据:
train_ds = tf.keras.preprocessing.image_dataset_from_directory(
data_dir,
validation_split=0.2,
subset="training",
seed=123,
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=123,
image_size=(img_height, img_width),
batch_size=batch_size)
然后我们再利用class_name输出我们本地数据集的标签,标签也就是对应数据所在的文件目录名:
class_names = train_ds.class_names
print(class_names)
['Dark', 'Green', 'Light', 'Medium']
在可视化数据前,我们来检查一下我们的数据信息是否是正确的:
for image_batch, labels_batch in train_ds:
print(image_batch.shape)
print(labels_batch.shape)
break
(32, 224, 224, 3)
(32,)
这是一批形状224x224x3的32张图片,我们将数据进行可视化看看:
plt.figure(figsize=(10, 4)) # 图形的宽为10高为5
for images, labels in train_ds.take(1):
for i in range(10):
ax = plt.subplot(2, 5, i + 1)
plt.imshow(images[i].numpy().astype("uint8"))
plt.title(class_names[labels[i]])
plt.axis("off")
AUTOTUNE = tf.data.experimental.AUTOTUNE
train_ds = train_ds.cache().shuffle(1000).prefetch(buffer_size=AUTOTUNE)
val_ds = val_ds.cache().prefetch(buffer_size=AUTOTUNE)
normalization_layer = layers.experimental.preprocessing.Rescaling(1./255)
train_ds = train_ds.map(lambda x, y: (normalization_layer(x), y))
val_ds = val_ds.map(lambda x, y: (normalization_layer(x), y))
image_batch, labels_batch = next(iter(val_ds))
first_image = image_batch[0]
# 查看归一化后的数据
print(np.min(first_image), np.max(first_image))
打印结果是:
0.0 1.0
上面layers.experimental.preprocessing.Rescaling函数原型是:
tf.keras.layers.experimental.preprocessing.Rescaling(
scale, offset=0.0, name=None, **kwargs
)
其中参数:
参数 | 说明 |
---|---|
scale | 浮点数,应用于输入的比例 |
offset | 浮点数,应用于输入的偏移量 |
name | 一个字符串,图层的名称 |
这里设置scale=1./255的作用是要将[0, 255]
范围内的输入重新调整为范围[0, 1]
内,也就是缩放层将像素标准化为[0,1],在后面打印的结果也看出来我们成功将像素标准化为[0,1]。
如果我们要将[0, 255]
范围内的输入重新调整为范围[-1, 1]
内,我们需要使通过设置scale=1./127.5, offset=-1
来实现。
官方模型我在上一期博客中就用到过,训练非常的缓慢,不知道你们是不是和我一样的情况,在这里我们今天主要来试试我们自己搭建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(len(class_names), (img_width, img_height, 3))
model.summary()
打印的结果是:
Model: "functional_5"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
input_3 (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_2 (Flatten) (None, 25088) 0
_________________________________________________________________
fc1 (Dense) (None, 4096) 102764544
_________________________________________________________________
fc2 (Dense) (None, 4096) 16781312
_________________________________________________________________
predictions (Dense) (None, 4) 16388
=================================================================
Total params: 134,276,932
Trainable params: 134,276,932
Non-trainable params: 0
_________________________________________________________________
# 设置初始学习率
initial_learning_rate = 1e-4
lr_schedule = tf.keras.optimizers.schedules.ExponentialDecay(
initial_learning_rate,
decay_steps=30, # 敲黑板!!!这里是指 steps,不是指epochs
decay_rate=0.92, # lr经过一次衰减就会变成 decay_rate*lr
staircase=True)
# 设置优化器
opt = tf.keras.optimizers.Adam(learning_rate=initial_learning_rate)
model.compile(optimizer=opt,
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=['accuracy'])
epochs = 20
history = model.fit(
train_ds,
validation_data=val_ds,
epochs=epochs
)
Epoch 1/20
30/30 [==============================] - 13s 187ms/step - loss: 1.3438 - accuracy: 0.3208 - val_loss: 0.9648 - val_accuracy: 0.6750
Epoch 2/20
......
30/30 [==============================] - 4s 137ms/step - loss: 0.0537 - accuracy: 0.9781 - val_loss: 0.1639 - val_accuracy: 0.9667
Epoch 19/20
30/30 [==============================] - 4s 138ms/step - loss: 0.0580 - accuracy: 0.9781 - val_loss: 0.1093 - val_accuracy: 0.9625
Epoch 20/20
30/30 [==============================] - 4s 136ms/step - loss: 0.0765 - accuracy: 0.9740 - val_loss: 0.1346 - val_accuracy: 0.9667
acc = history.history['accuracy']
val_acc = history.history['val_accuracy']
loss = history.history['loss']
val_loss = history.history['val_loss']
epochs_range = range(epochs)
plt.figure(figsize=(12, 4))
plt.subplot(1, 2, 1)
plt.plot(epochs_range, acc, label='Training Accuracy')
plt.plot(epochs_range, val_acc, label='Validation Accuracy')
plt.legend(loc='lower right')
plt.title('Training and Validation Accuracy')
plt.subplot(1, 2, 2)
plt.plot(epochs_range, loss, label='Training Loss')
plt.plot(epochs_range, val_loss, label='Validation Loss')
plt.legend(loc='upper right')
plt.title('Training and Validation Loss')
plt.show()
本次项目的结果我并没有运行出来,上面的结果是截取K老师的博客,供大家参考一下。
我也借这次博客来记录一下这个目前无法解决的问题,我自己的结果如下:
这个图跟K老师的完全不一样,代码跟K老师的一样,然后我还在本地跑了一遍K老师项目源码,源码都跑不动,跟K老师讨论了一会,K老师说他之前也遇见过类似的情况,那是3080显卡刚出来的时候,配置的环境没有错,代码也没错但是就是运行结果异常低下,他当时重装了系统解决了问题,我也不知道我的是不是重装系统也能结果,我觉得也有可是跟显卡驱动更新有关,总之这个层面的问题很麻烦,最近快要考试了加上事挺多的,就暂时不去折腾了,如果你们也遇见过类似的问题,可以说说你们的解决办法,谢谢!