第四周:猴痘识别
- 🍨 本文为🔗365天深度学习训练营 中的学习记录博客
- 🍦 参考文章地址: 🔗深度学习100例-卷积神经网络(CNN)猴痘病识别 | 第45天
- 🍖 作者:K同学啊
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.experimental.list_physical_devices(device_type='GPU')
if gpus:
gpu0 = gpus[0]
tf.config.experimental.set_memory_growth(gpu0,True)
tf.config.set_visible_devices([gpu0],"GPU")
print(gpus)
可以通过打印出的来检查是否启用GPU,使用CPU的可以忽略这步
2 导入数据
数据集为我本地地址
# 导入数据
data_dir = "C:/study/artificialIntelligence/data/fourthWeek/"
data_dir = pathlib.Path(data_dir)
查看数据
#查看数据
image_count = len(list(data_dir.glob('*/*.jpg')))
print("图片总数为:",image_count)
打印一张看看
#打印一张看看
Monkeypox = list(data_dir.glob('Monkeypox/*.jpg'))
PIL.Image.open(str(Monkeypox[1]))
3 加载数据
使用image_dataset_from_directory方法将磁盘中的数据加载到tf.data.Dataset中
验证集并没有参与训练过程梯度下降过程的,狭义上来讲是没有参与模型的参数训练更新的。
但是广义上来讲,验证集存在的意义确实参与了一个“人工调参”的过程,我们根据每一个epoch训练之后模型在valid data上的表现来决定是否需要训练进行early stop,或者根据这个过程模型的性能变化来调整模型的超参数,如学习率,batch_size等等。
#加载数据
batch_size = 32
image_height=224
image_width = 224
train_ds = tf.keras.preprocessing.image_dataset_from_directory(
data_dir,
validation_split=0.2,
subset="training",
seed=123,
image_size=(image_height,image_width),
batch_size= batch_size
)
查看加载的训练数据
batch_size = 32
image_height=224
image_width = 224
val_ds = tf.keras.preprocessing.image_dataset_from_directory(
data_dir,
validation_split=0.2,
subset="validation",
seed=123,
image_size=(image_height,image_width),
batch_size= batch_size
)
查看加载的验证数据
batch_size = 32
image_height=224
image_width = 224
val_ds = tf.keras.preprocessing.image_dataset_from_directory(
data_dir,
validation_split=0.2,
subset="validation",
seed=123,
image_size=(image_height,image_width),
batch_size= batch_size
)
4 数据可视化
标签可视化:
class_names = train_ds.class_names
print(class_names)
图片可视化:
#可视化数据
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")
格式可视化:
#检查数据格式
for image_batch,labels_batch in train_ds:
print(image_batch.shape)
print(labels_batch.shape)
break
5 配置数据集
● shuffle() :打乱数据,关于此函数的详细介绍可以参考:https://zhuanlan.zhihu.com/p/42417456
● 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)
6 构建cnn
卷积神经网络(CNN)的输入是张量 (Tensor) 形式的 (image_height, image_width, color_channels),包含了图像高度、宽度及颜色信息。不需要输入batch size。color_channels 为 (R,G,B) 分别对应 RGB 的三个颜色通道(color channel)。在此示例中,我们的 CNN 输入的形状是 (224, 224, 4)即彩色图像。我们需要在声明第一层时将形状赋值给参数input_shape。
num_classes=2
#构建cnn
model = models.Sequential([
layers.experimental.preprocessing.Rescaling(1./255,input_shape=(image_height,image_width,3)),
layers.Conv2D(16,(3,3),activation ='relu',input_shape=(image_height,image_width,3)),#卷积层 3x3
layers.AveragePooling2D((2,2)),#平均池化层
layers.Conv2D(32,(3,3),activation ='relu'),
layers.AveragePooling2D((2,2)),#平均池化层
layers.Dropout(0.3),
layers.Conv2D(64,(3,3),activation ='relu'),
layers.Dropout(0.3),
layers.Flatten(),
layers.Dense(128,activation='relu'),
layers.Dense(num_classes)
])
model.summary()#打印
7 编译
● 损失函数(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']
)
8 训练!
#训练模型
from tensorflow.keras.callbacks import ModelCheckpoint
epochs =50
checkpointer = ModelCheckpoint('best_model.h5',
monitor='val_accuraacy',
verbose=1,
save_best_only=True,
save_weights_only= True)
history =model.fit(train_ds,
validation_data=val_ds,
epochs=epochs,
callbacks=[checkpointer])
9 模型评估
#模型评估
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()