from tensorflow import keras
from tensorflow.keras import layers,models
import os, PIL, pathlib
import matplotlib.pyplot as plt
import tensorflow as tf
gpus = tf.config.list_physical_devices("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")
gpus
data_dir = "./houdou/"
data_dir = pathlib.Path(data_dir)
image_count = len(list(data_dir.glob('*/*.jpg')))
print("图片总数为:",image_count)
图片总数为: 2142
Monkeypox = list(data_dir.glob('Monkeypox/*.jpg'))
PIL.Image.open(str(Monkeypox[0]))
使用image_dataset_from_directory
方法将磁盘中的数据加载到tf.data.Dataset
中
batch_size = 32
img_height = 240
img_width = 240
"""
关于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)
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)
['Monkeypox', 'Others']
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
(32, 240, 240, 3) (32,)
● Image_batch是形状的张量(32,240,240,3)。这是一批形状240x240x3的32张图片(最后一维指的是彩色通道RGB)。
● Label_batch是形状(32,)的张量,这些标签对应32张图片
prefetch()
功能详细介绍:CPU 正在准备数据时,加速器处于空闲状态。相反,当加速器正在训练模型时,CPU 处于空闲状态。因此,训练所用的时间是 CPU 预处理时间和加速器训练时间的总和。prefetch()
将训练步骤的预处理和模型执行过程重叠到一起。当加速器正在执行第 N 个训练步时,CPU 正在准备第 N+1 步的数据。这样做不仅可以最大限度地缩短训练的单步用时(而不是总用时),而且可以缩短提取和转换数据所需的时间。如果不使用prefetch()
,CPU 和 GPU/TPU 在大部分时间都处于空闲状态:
使用prefetch()
可显著减少空闲时间:
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)的输入是张量 (Tensor) 形式的 (image_height, image_width, color_channels)
,包含了图像高度、宽度及颜色信息。不需要输入batch size
。color_channels 为 (R,G,B) 分别对应 RGB 的三个颜色通道。
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.AveragePooling2D((2, 2)), # 池化层3,2*2采样
layers.Dropout(0.4),
layers.Conv2D(128, (3, 3), activation='relu'), # 卷积层4,卷积核3*3
layers.Dropout(0.5),
layers.Flatten(), # Flatten层,连接卷积层与全连接层
layers.Dense(256, activation='sigmoid'), # 全连接层,特征进一步提取
layers.Dense(num_classes) # 输出层,输出预期结果
])
model.summary() # 打印网络结构
Model: "sequential_4" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= rescaling_4 (Rescaling) (None, 240, 240, 3) 0 _________________________________________________________________ conv2d_16 (Conv2D) (None, 238, 238, 16) 448 _________________________________________________________________ average_pooling2d_12 (Averag (None, 119, 119, 16) 0 _________________________________________________________________ conv2d_17 (Conv2D) (None, 117, 117, 32) 4640 _________________________________________________________________ average_pooling2d_13 (Averag (None, 58, 58, 32) 0 _________________________________________________________________ dropout_12 (Dropout) (None, 58, 58, 32) 0 _________________________________________________________________ conv2d_18 (Conv2D) (None, 56, 56, 64) 18496 _________________________________________________________________ average_pooling2d_14 (Averag (None, 28, 28, 64) 0 _________________________________________________________________ dropout_13 (Dropout) (None, 28, 28, 64) 0 _________________________________________________________________ conv2d_19 (Conv2D) (None, 26, 26, 128) 73856 _________________________________________________________________ dropout_14 (Dropout) (None, 26, 26, 128) 0 _________________________________________________________________ flatten_4 (Flatten) (None, 86528) 0 _________________________________________________________________ dense_8 (Dense) (None, 256) 22151424 _________________________________________________________________ dense_9 (Dense) (None, 2) 514 ================================================================= Total params: 22,249,378 Trainable params: 22,249,378 Non-trainable params: 0 _________________________________________________________________
在准备对模型进行训练之前,还需要再对其进行一些设置。以下内容是在模型的编译步骤中添加的:
# 设置优化器
opt = tf.keras.optimizers.Adam(learning_rate=1e-4)
model.compile(optimizer=opt,
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=['accuracy'])
关于ModelCheckpoint
的详细介绍可参考文章 ModelCheckpoint 讲解【TensorFlow2入门手册】
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])
Epoch 00050: val_accuracy did not improve from 0.89252
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()
把最后全连接层ReLu换成sigmiod,val_accuracy只降低一点点,但val_loss会降低很多。
Batch_size的作用:决定了下降的方向。
在神经网络训练时,如果数据集足够小,可将数据一次性全部喂给神经网络
但我们常常面临的是比较大的数据集,一次性喂给神经网络时,往往会出现内存/显存不足的现象。
此时,我们会把比较大的数据集,分批次喂给神经网络。
在合理范围内,增大Batch_size的好处:
盲目增大Batch_size,Batch_size过大的坏处:
一些经验之谈:
总结:
输入网络的图片大小要根据网络结构来确定。
主要看pool这个操作执行了几次,比如pool是2*2的,那么一次pool图像就缩小了一半。本实验执行了3次,就是2^3,那输入图片的尺寸就必须是2的3次方,8的倍数。
输入图片大小变小之后,batchsize可以调大一些。在不超内存的情况下,batch越大越好
如果学习率过大,很可能会越过最优值,反而如果学习率过小,优化的效率可能很低,导致过长的运算时间,所以学习率对于算法性能的表现十分重要。
优化器keras.optimizers.Adam()是解决这个问题的一个方案。其大概的思想是开始的学习率设置为一个较大的值,然后根据次数的增多,动态的减小学习率,以实现效率和效果的兼得。