>- **🍨 本文为[🔗365天深度学习训练营](https://mp.weixin.qq.com/s/xLjALoOD8HPZcH563En8bQ) 中的学习记录博客**
>- **🍦 参考文章地址: [🔗深度学习100例-卷积神经网络(CNN)猴痘病识别 | 第45天](https://blog.csdn.net/qq_38251616/article/details/126284706)**
>- **🍖 作者:[K同学啊](https://mp.weixin.qq.com/s/k-vYaC8l7uxX51WoypLkTw)**
配置环境:
● 语言环境:Python3.6.5
● 编译器:jupyter notebook
● 深度学习框架:TensorFlow2.4.1
● 显卡(GPU):NVIDIA GeForce RTX 3080
一、前期工作
1.设置GPU
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers, models
import os, PIL, pathlib
import matplotlib.pyplot as plt
gpus = tf.config.list_physical_devices("GPU")
if gpus:
gpu0 = gpus[0]
tf.config.experimental.set_memory_growth(gpu0, True)
tf.config.set_visible_devices([gpu0], "GPU")
data_dir = "D:\\deeplearning\\day04\\dataset\\04"
data_dir = pathlib.Path(data_dir)
image_count = len(list(data_dir.glob('*/*.jpg')))
print("图片总数为:", image_count)
2.导入数据
data_dir = "D:\\deeplearning\\day04\\dataset\\04"
data_dir = pathlib.Path(data_dir)
3.查看数据
image_count = len(list(data_dir.glob('*/*.jpg')))
print("图片总数为:", image_count)
Monkeypox = list(data_dir.glob('Monkeypox/*.jpg'))
PIL.Image.open(str(Monkeypox[0]))
二、数据预处理
1. 加载数据
使用image_dataset_from_directory方法将磁盘中的数据加载到tf.data.Dataset中
训练集、验证集、测试集的作用
训练集(Training set)
作用时来拟合模型,通过设置分类器的参数,训练分类模型。后续结合验证集作用时,会选出同一参数的不同取值,拟合出多个分类器。
验证集(Validation set)
作用是通过训练集训练出多个模型之后,为了能找出效果最佳的模型,使用各个模型对验证集数据进行预测,并记录模型的准确率
选出效果最佳的模型所对应的参数,即用来调整模型参数。
测试集(Test set)
通过训练集和验证集得出最优模型后,使用测试集进行模型预测。用来衡量该最优模型的性能和分类能力。
即把测试集当作从来不存在的数据集,当已经确定模型参数后,使用测试集进行模型性能评价。
对原始数据进行三个数据集的划分,也是为了防止模型过拟合。
当使用了所有的原始数据去训练模型,得到的结果很可能是该模型最大程度地拟合了原始数据,亦即该模型是为了拟合所有原始数据而存在。
当新的样本出现,再使用该模型进行预测,效果可能还不如只使用一部分数据训练的模型。
=参考文章=
https://blog.youkuaiyun.com/Neleuska/article/details/73193096?ops_request_misc=&request_id=&biz_id=102&utm_term=%E8%AE%AD%E7%BB%83%E9%9B%86%E5%92%8C%E6%B5%8B%E8%AF%95%E9%9B%86%E7%9A%84%E4%BD%9C%E7%94%A8&utm_medium=distribute.pc_search_result.none-task-blog-2~all~sobaiduweb~default-4-73193096.nonecase&spm=1018.2226.3001.4187
关于image_dataset_from_directory()的详细介绍可以参考文章:https://mtyjkh.blog.youkuaiyun.com/article/details/117018789
batch_size = 32
img_height = 224
img_width = 224
train_ds = tf.keras.preprocessing.image_dataset_from_directory(
data_dir, # 数据集
validation_split=0.2, # 用于验证集的为数据集的20%
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_names输出数据集的标签。标签将按字母的顺序对应于目录名称。
class_names = train_ds.class_names
print(class_names)
2.可视化数据
plt.figure(figsize=(20, 10))
for images, labels in train_ds.take(1):
for i in range(20):
ax = plt.subplot(5, 10, i + 1)
plt.imshow(images[i].numpy().astype("uint8"))
plt.title(class_names[labels[i]])
plt.axis("off")
3.再次检查数据
for image_batch, labels_batch in train_ds:
print(image_batch.shape)
print(labels_batch.shape)
break
4.配置数据集
● shuffle() :打乱数据,关于此函数的详细介绍可以参考:https://zhuanlan.zhihu.com/p/42417456
● prefetch() :预取数据,加速运行
prefetch()功能详细介绍:CPU 正在准备数据时,加速器处于空闲状态。相反,当加速器正在训练模型时,CPU 处于空闲状态。因此,训练所用的时间是 CPU 预处理时间和加速器训练时间的总和。prefetch()将训练步骤的预处理和模型执行过程重叠到一起。当加速器正在执行第 N 个训练步时,CPU 正在准备第 N+1 步的数据。这样做不仅可以最大限度地缩短训练的单步用时(而不是总用时),而且可以缩短提取和转换数据所需的时间。如果不使用prefetch(),CPU 和 GPU/TPU 在大部分时间都处于空闲状态:
使用prefetch()可显著减少空闲时间:
cache():将数据集缓存到内存当中,加速运行
AUTOTUNE = tf.data.AUTOTUNE
train_ds = train_ds.cache().shuffle(1000).prefetch(buffer_size=AUTOTUNE)
val_ds = val_ds.cache().prefetch(buffer_size=AUTOTUNE)
三、构建CNN网络
关于卷积核的计算不懂的可以参考文章:https://blog.youkuaiyun.com/qq_38251616/article/details/114278995
layers.Dropout(0.4) 作用是防止过拟合,提高模型的泛化能力。
关于Dropout层的更多介绍可以参考文章:https://mtyjkh.blog.youkuaiyun.com/article/details/115826689
num_classes = 2
model = models.Sequential([
layers.experimental.preprocessing.Rescaling(1. / 255, input_shape=(img_height, img_width, 3)),
layers.Conv2D(16, (3, 3), activation='relu', input_shape=(img_height, img_width, 3)), # 卷积层1,卷积核3*3
layers.AveragePooling2D((2, 2)), # 池化层1,2*2采样
layers.Conv2D(32, (3, 3), activation='relu'), # 卷积层2,卷积核3*3
layers.AveragePooling2D((2, 2)), # 池化层2,2*2采样
layers.Dropout(0.3),
layers.Conv2D(64, (3, 3), activation='relu'), # 卷积层3,卷积核3*3
layers.Dropout(0.3),
layers.Flatten(), # Flatten层,连接卷积层与全连接层
layers.Dense(128, activation='relu'), # 全连接层,特征进一步提取
layers.Dense(num_classes) # 输出层,输出预期结果
])
model.summary() # 打印网络结构
四、编译
在准备对模型进行训练之前,还需要再对其进行一些设置。以下内容是在模型的编译步骤中添加的:
● 损失函数(loss):用于衡量模型在训练期间的准确率。
● 优化器(optimizer):决定模型如何根据其看到的数据和自身的损失函数进行更新。
● 指标(metrics):用于监控训练和测试步骤。以下示例使用了准确率,即被正确分类的图像的比率。
# 设置优化器
opt = tf.keras.optimizers.Adam(learning_rate=1e-4)
model.compile(optimizer=opt,
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=['accuracy'])
五、训练模型
关于ModelCheckpoint方法详解
参考文章:https://blog.youkuaiyun.com/weixin_44048809/article/details/105705272
训练完模型之后,一般需要保存模型或者只保存权重文件。可以利用Keras中的回调函数ModelCheckpoint进行保存。
keras.callbacks.ModelCheckpoint(
filepath,
monitor=‘val_loss’,
verbose=0,
save_best_only=True,
save_weights_only=False,
mode=‘auto’,
period=1
)
1.filename
模型保存在本地的路径
2.monitor
需要监视的值,val_accuracy,val_loss或者accuracy。
3.verbose
信息展示模式
4.save_best_only
当设置为True时,表示当模型这次epoch的训练评判结果(monitor的监测值)。比上一次保存训练时的结果有提升时才进行保存。
5.mode
‘auto’,‘min’,‘max’ 之一,在save_best_only=True时决定性能最佳模型的评判标准例如,当监测值为val_acc时,模式应为max,当监测值为val_loss时,模式应为min。再auto模式下,评价准则由被监测值的名字自动推断。
6.save_weights_only
若设置为True,占用内存小(只保存模型权重),但下次想调用的话,需要搭建和训练时一样的网络。
若设置为False,占用内存大(包括了模型结构和配置信息),下次调用可以直接载入,不需要再次搭建神经网络结构。
7.period:填写int值,如果填写period=3,指模型每训练3个epoch,进行保存一次。
from tensorflow.keras.callbacks import ModelCheckpoint
epochs = 50
checkpointer = ModelCheckpoint('best_model.h5',
monitor='val_accuracy',
verbose=1,
save_best_only=True,
save_weights_only=True)
history = model.fit(train_ds,
validation_data=val_ds,
epochs=epochs,
callbacks=[checkpointer]) # 回调函数采用checkpointer
六、模型评估
1.Loss与Accuracy图
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()
epoch=25时:
epoch = 50时
2.指定图片进行预测
# 加载效果最好的模型权重
model.load_weights('best_model.h5')
from PIL import Image
import numpy as np
# img = Image.open("./45-data/Monkeypox/M06_01_04.jpg") # 这里选择你需要预测的图片
img = Image.open("D:\\deeplearning\\day04\\dataset\\04\\Monkeypox\\M01_01_00.jpg") # 这里选择你需要预测的图片
plt.title("test_img")
plt.axis('off')
plt.imshow(img)
plt.show()
image = tf.image.resize(img, [img_height, img_width])
img_array = tf.expand_dims(image, 0)
predictions = model.predict(img_array) # 这里选用你已经训练好的模型
print("预测结果为:", class_names[np.argmax(predictions)])
七、总结
进一步加深读CNN模型的理解,