目录
一、前言
>- **🍨 本文为[🔗365天深度学习训练营](https://mp.weixin.qq.com/s/xLjALoOD8HPZcH563En8bQ) 中的学习记录博客**
>- **🍦 参考文章:365天深度学习训练营-第7周:咖啡豆识别(训练营内部成员可读)**
>- **🍖 原作者:[K同学啊|接辅导、项目定制](https://mtyjkh.blog.csdn.net/)**
● 难度:夯实基础⭐⭐
● 语言:Python3、TensorFlow2
● 时间:9月5-9月9日
🍺 要求:
1. 自己搭建VGG-16网络框架
2. 调用官方的VGG-16网络框架
🍻 拔高(可选):
1. 验证集准确率达到100%
2. 使用PPT画出VGG-16算法框架图(发论文需要这项技能)
🔎 探索(难度有点大)
1. 在不影响准确率的前提下轻量化模型
○ 目前VGG16的Total params是134,276,932
二、我的环境
语言环境:Python3.7
编译器:jupyter notebook
深度学习环境:TensorFlow2
三、代码实现
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_devices([gpus[0]],"GPU")
from tensorflow.keras import layers
import numpy as np
import matplotlib.pyplot as plt
import pathlib
data_dir = "./49-data/"
data_dir = pathlib.Path(data_dir)
image_count = len(list(data_dir.glob('*/*.png')))
print("图片总数为:",image_count)
batch_size = 32
img_height = 224
img_width = 224
"""
关于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=123,
image_size=(img_height, img_width),
batch_size=batch_size)
"""
关于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=123,
image_size=(img_height, img_width),
batch_size=batch_size)
class_names = train_ds.class_names
print(class_names)
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")
for image_batch, labels_batch in train_ds:
print(image_batch.shape)
print(labels_batch.shape)
break
AUTOTUNE = tf.data.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))
# model = tf.keras.applications.VGG16(weights='imagenet')
# model.summary()
from tensorflow.keras import Input
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Conv2D, MaxPooling2D, Dense, Flatten
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()
# 设置初始学习率
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
)
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()
四、VGG-16框架
五、LeNet5模型
def LeNet5(nb_classes, input_shape):
input_tensor = Input(shape=input_shape)
# 1st block
x = Conv2D(6, (5,5), activation='sigmoid', 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)
x = Conv2D(16, (5,5), activation='sigmoid', padding='same',name='block2_conv1')(x)
x =MaxPooling2D((2,2),strides=(2,2),name = 'block2_pool')(x)
# full connection
x = Flatten()(x)
x = Dense(120, activation='sigmoid', name='fc1')(x)
x = Dense(84, activation='sigmoid', name='fc2')(x)
output_tensor = Dense(nb_classes, activation='softmax', name='predictions')(x)
model = Model(input_tensor, output_tensor)
return model
model=LeNet5(len(class_names), (img_width, img_height, 3))
model.summary()
效果极差,下次一定不用
六、模型改进
1、调低学习率(或按迭代次数衰减)
2、调整参数的初始化方法
3、调整输入数据的标准化方法
4、修改Loss函数
5、增加正则化
6、使用BN/GN层(中间层数据的标准化)
7、使用dropout
优化1
model = keras.models.Sequential()
# 优化 增加L2正则化
model.add(keras.layers.Conv2D(64, (3, 3), padding='same', kernel_regularizer=keras.regularizers.l2(weight_decay)))
model.add(keras.layers.Activation('relu'))
# 优化 添加BN层和Dropout
model.add(keras.layers.BatchNormalization())
model.add(keras.layers.Dropout(0.3))
model.add(keras.layers.Conv2D(64, (3, 3), padding='same', activation='relu'))
model.add(keras.layers.MaxPooling2D(pool_size=(2, 2), strides=2))
model.add(keras.layers.Conv2D(128, (3, 3), padding='same', activation='relu'))
model.add(keras.layers.Conv2D(128, (3, 3), padding='same', activation='relu'))
model.add(keras.layers.MaxPooling2D(pool_size=(2, 2), strides=2))
model.add(keras.layers.Conv2D(256, (3, 3), padding='same', activation='relu'))
model.add(keras.layers.Conv2D(256, (3, 3), padding='same', activation='relu'))
model.add(keras.layers.MaxPooling2D(pool_size=(2, 2), strides=2))
model.add(keras.layers.Conv2D(512, (3, 3), padding='same', activation='relu'))
model.add(keras.layers.Conv2D(512, (3, 3), padding='same', activation='relu'))
model.add(keras.layers.MaxPooling2D(pool_size=(2, 2), strides=2))
model.add(keras.layers.Conv2D(512, (3, 3), padding='same', activation='relu'))
model.add(keras.layers.Conv2D(512, (3, 3), padding='same', activation='relu'))
model.add(keras.layers.MaxPooling2D(pool_size=(2, 2), strides=2))
model.add(keras.layers.Flatten())
model.add(keras.layers.Dense(256, activation='relu')) # VGG16为4096
model.add(keras.layers.Dense(128, activation='relu')) # VGG16为4096
model.add(keras.layers.Dense(num_classes, activation='softmax')) # VGG16为1000
优化2
model = models.Sequential([
layers.experimental.preprocessing.Rescaling( 1. ,input_shape=(img_height, img_width, 3)),
layers.Conv2D(filters=64, kernel_size=(3, 3), padding='same'), # 卷积层1
#layers.BatchNormalization(), # BN层1
layers.Activation('relu'), # 激活层1
layers.Conv2D(filters=64, kernel_size=(3, 3), padding='same', ),
#layers.BatchNormalization(), # BN层1
layers.Activation('relu') , # 激活层1
layers.MaxPool2D(pool_size=(2, 2), strides=2, padding='same'),
#layers.Dropout(0.2), # dropout层
#
layers.Conv2D(filters=128, kernel_size=(3, 3), padding='same'),
#layers.BatchNormalization(), # BN层1
layers.Activation('relu'), # 激活层1
layers.Conv2D(filters=128, kernel_size=(3, 3), padding='same'),
#layers.BatchNormalization(), # BN层1
layers.Activation('relu'), # 激活层1
layers.MaxPool2D(pool_size=(2, 2), strides=2, padding='same'),
#layers.Dropout(0.2), # dropout层
#
layers.Conv2D(filters=256, kernel_size=(3, 3), padding='same'),
#layers.BatchNormalization() , # BN层1
layers.Activation('relu'), # 激活层1
layers.Conv2D(filters=256, kernel_size=(3, 3), padding='same'),
#layers.BatchNormalization() , # BN层1
layers.Activation('relu') , # 激活层1
layers.Conv2D(filters=256, kernel_size=(3, 3), padding='same'),
# layers.BatchNormalization(),
layers.Activation('relu'),
layers.MaxPool2D(pool_size=(2, 2), strides=2, padding='same'),
#layers.Dropout(0.2),
#
layers.Conv2D(filters=512, kernel_size=(3, 3), padding='same'),
# layers.BatchNormalization() , # BN层1
layers.Activation('relu') , # 激活层1
layers.Conv2D(filters=512, kernel_size=(3, 3), padding='same'),
#layers.BatchNormalization() , # BN层1
layers.Activation('relu'), # 激活层1
layers.Conv2D(filters=512, kernel_size=(3, 3), padding='same'),
#layers.BatchNormalization(),
layers.Activation('relu'),
layers.MaxPool2D(pool_size=(2, 2), strides=2, padding='same'),
#layers.Dropout(0.2),
#
layers.Conv2D(filters=512, kernel_size=(3, 3), padding='same'),
# layers.BatchNormalization() , # BN层1
layers.Activation('relu'), # 激活层1
layers.Conv2D(filters=512, kernel_size=(3, 3), padding='same'),
#layers.BatchNormalization(), # BN层1
layers.Activation('relu'), # 激活层1
layers.Conv2D(filters=512, kernel_size=(3, 3), padding='same'),
# layers.BatchNormalization(),
layers.Activation('relu'),
layers.MaxPool2D(pool_size=(2, 2), strides=2, padding='same'),
#layers.Dropout(0.2),
layers.Flatten(), # Flatten层,连接卷积层与全连接层
layers.Dense(4096, activation='relu'), # 全连接层,特征进一步提取
layers.Dense(4096, activation='relu'), # 全连接层,特征进一步提取
layers.Dense(len(class_names),activation='softmax') # 输出层,输出预期结果
])
model.summary()