- 本文为🔗365天深度学习训练营 中的学习记录博客
- 🍖 原作者:K同学啊 | 接辅导、项目定制
1、 前言
这周学习的主要内容是,使用tensorflow编写代码,使用vgg-16网络模型,完成咖啡豆的识别。
2、完整代码
import tensorflow as tfgpus = 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 import keras
from keras import layers,models
import numpy as np
import matplotlib.pyplot as plt
import os,PIL,pathlibdata_dir = "./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) # ['Dark', 'Green', 'Light', 'Medium']# 可视化数据
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")
plt.show()for image_batch, labels_batch in train_ds:print(image_batch.shape) # (32, 224, 224, 3)print(labels_batch.shape) # (32,)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 = keras.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))# 构建VGG16神经网络
'''VGG优缺点分析:【优点】:VGG的结构非常简洁,整个网络都使用了同样大小的卷积核尺寸(3x3),和最大池化尺寸(2x2)。【缺点】:(1)训练时间过长,调参难度大(2)需要的存储容量大,不利于部署
'''# 方式一:使用官方模型
model = tf.keras.applications.VGG16(weights='imagenet')
model.summary()# 方式二:使用自建模型
# from keras import layers, models, Input
# from keras.models import Model
# from 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))# 网络结构图
'''结构图说明:13个卷积层,分别用blockX_convX表示3个全连接层,分别用fcX与predictions表示5个池化层。分别用BlockX_pool表示VGG-16 包含了16个隐藏层(13个卷积层+3个全连接层),故称为VGG-16
'''# 编译
'''在准备对模型进行训练之前,需要设置一些参数:损失函数:用于衡量模型在训练期间的准确率。优化器:决定模型如何根据其看到的数据和自身的损失函数进行更新。指标:用于监控训练和测试步骤。
'''
# 设置初始学习率
initial_learning_rate = 1e-4
lr_schedule = tf.keras.optimizers.schedules.ExponentialDecay(initial_learning_rate,decay_steps=30, # 敲黑板!!!这里是指 steps,不是指epochsdecay_rate=0.92, # lr经过一次衰减就会变成 decay_rate*lrstaircase=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 = 20history = 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.savefig("/data/jupyter/deep_demo/yolov8/t07_coffeedou/resultImg.jpg")
plt.show()
3、重点代码模块
3.1 理解vgg-16网络结构模型图
结构图说明:13个卷积层,分别用blockX_convX表示3个全连接层,分别用fcX与predictions表示5个池化层。分别用BlockX_pool表示 VGG-16 包含了16个隐藏层(13个卷积层+3个全连接层),故称为VGG-16
3.2 搭建vgg-16网络的两种方式
方式一:使用官方模型
model = tf.keras.applications.VGG16(weights='imagenet')
model.summary()
方式二:使用自己构建的模型
from keras import layers, models, Input
from keras.models import Model
from 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(len(class_names), (img_width, img_height, 3))
4、运行过程结果