卷积神经网络(CNN)猴痘病识别 | 项目二

🍺要求:
1.训练过程中保存效果最好的模型参数。(完成)
2.加载最佳模型参数识别本地的一张图片。(完成)
3.测试集accuracy到达88%。(完成)

🍻拔高(可选):
1.调整模型参数并观察测试集的准确率变化。(完成)
batch_size、img_height、img_width、learning_rate、epochs以及其他相关参数
加深网络(增加卷积层)
2.尝试设置动态学习率。(完成)
3.测试集accuracy到达89

一.前期工作

1.设置GPU

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

[PhysicalDevice(name='/physical_device:GPU:0', device_type='GPU')]

2.导入数据

data_dir = "/home/mw/input/HD4506/45-data/"
data_dir = pathlib.Path(data_dir)

3.查看数据

image_count = len(list(data_dir.glob('*/*.jpg')))
print("图片总数为:",image_count)
图片总数为: 2142
Monkeypox = list(data_dir.glob('Monkeypox/*.jpg'))
PIL.Image.open(str(Monkeypox[1]))

二.数据预处理

1.加载数据

使用image_dataset_from_directory方法将磁盘中的数据加载到tf.data.Dataset中

测试集与验证集的关系:

验证集并没有参与训练过程梯度下降过程的,狭义上来讲是没有参与模型的参数训练更新的。
但是广义上来讲,验证集存在的意义确实参与了一个“人工调参”的过程,我们根据每一个epoch训练之后模型在valid data上的表现来决定是否需要训练进行early stop,或者根据这个过程模型的性能变化来调整模型的超参数,如学习率,batch_size等等。
因此,我们也可以认为,验证集也参与了训练,但是并没有使得模型去overfit验证集

batch_size = 32
img_height = 180
img_width = 180

"""
关于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)

Found 2142 files belonging to 2 classes.
Using 1714 files for training.
"""
关于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)

Found 2142 files belonging to 2 classes.
Using 428 files for validation.
class_names = train_ds.class_names
print(class_names)

['Monkeypox', 'Others']

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

(32, 180, 180, 3)
(32,)

Image_batch是形状的张量(32,224,224,3)。这是一批形状224x224x3的32张图片(最后一维指的是彩色通道RGB)。
Label_batch是形状(32,)的张量,这些标签对应32张图片

4.配置数据集

shuffle() :打乱数据,关于此函数的详细介绍可以参考:https://zhuanlan.zhihu.com/p/42417456

prefetch() :预取数据,加速运行
prefetch()功能详细介绍:CPU 正在准备数据时,加速器处于空闲状态。相反,当加速器正在训练模型时,CPU 处于空闲状态。因此,训练所用的时间是 CPU 预处理时间和加速器训练时间的总和。prefetch()将训练步骤的预处理和模型执行过程重叠到一起。当加速器正在执行第 N 个训练步时,CPU 正在准备第 N+1 步的数据。这样做不仅可以最大限度地缩短训练的单步用时(而不是总用时),而且可以缩短提取和转换数据所需的时间。如果不使用prefetch(),CPU 和 GPU/TPU 在大部分时间都处于空闲状态

cache() :将数据集缓存到内存当中,加速运行

AUTOTUNE = tf.data.experimental.AUTOTUNE
train_ds = train_ds.cache().shuffle(1000).prefetch(buffer_size=AUTOTUNE)
val_ds = val_ds.cache().prefetch(buffer_size=AUTOTUNE)

三.构建CNN网络

卷积神经网络(CNN)的输入是张量 (Tensor) 形式的 (image_height, image_width, color_channels),包含了图像高度、宽度及颜色信息。不需要输入
batch size。color_channels 为 (R,G,B) 分别对应 RGB 的三个颜色通道(color channel)。在此示例中,我们的 CNN 输入的形状是 (224, 224, 3)即彩色图像。我们需要在声明第一层时将形状赋值给参数input_shape。

num_classes = 2

"""
关于卷积核的计算不懂的可以参考文章:https://blog.csdn.net/qq_38251616/article/details/114278995

layers.Dropout(0.4) 作用是防止过拟合,提高模型的泛化能力。
在上一篇文章花朵识别中,训练准确率与验证准确率相差巨大就是由于模型过拟合导致的

关于Dropout层的更多介绍可以参考文章:https://mtyjkh.blog.csdn.net/article/details/115826689
"""

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.MaxPooling2D((2, 2)),               # 池化层1,2*2采样
    layers.Conv2D(32, (3, 3), activation='relu'),  # 卷积层2,卷积核3*3
    layers.MaxPooling2D((2, 2)),               # 池化层2,2*2采样
    layers.Dropout(0.3),  
    layers.Conv2D(64, (3, 3), activation='relu'),  # 卷积层3,卷积核3*3
    layers.Conv2D(256, (3, 3), activation='relu'),
    layers.Dropout(0.3), 
    layers.Conv2D(128, (3, 3), activation='relu'),
    layers.Dropout(0.3), 
    layers.Conv2D(64, (3, 3), activation='relu'),
    layers.Conv2D(32, (3, 3), activation='relu'),
    layers.Dropout(0.3),  
    
    layers.Flatten(),                       # Flatten层,连接卷积层与全连接层
    layers.Dense(128, activation='relu'),   # 全连接层,特征进一步提取
    layers.Dense(64, activation='relu'),
    layers.Dense(32, activation='relu'),
    layers.Dense(num_classes)               # 输出层,输出预期结果
])

model.summary()  # 打印网络结构

Model: "sequential"
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
rescaling (Rescaling)        (None, 180, 180, 3)       0         
_________________________________________________________________
conv2d (Conv2D)              (None, 178, 178, 16)      448       
_________________________________________________________________
max_pooling2d (MaxPooling2D) (None, 89, 89, 16)        0         
_________________________________________________________________
conv2d_1 (Conv2D)            (None, 87, 87, 32)        4640      
_________________________________________________________________
max_pooling2d_1 (MaxPooling2 (None, 43, 43, 32)        0         
_________________________________________________________________
dropout (Dropout)            (None, 43, 43, 32)        0         
_________________________________________________________________
conv2d_2 (Conv2D)            (None, 41, 41, 64)        18496     
_________________________________________________________________
conv2d_3 (Conv2D)            (None, 39, 39, 256)       147712    
_________________________________________________________________
dropout_1 (Dropout)          (None, 39, 39, 256)       0         
_________________________________________________________________
conv2d_4 (Conv2D)            (None, 37, 37, 128)       295040    
_________________________________________________________________
dropout_2 (Dropout)          (None, 37, 37, 128)       0         
_________________________________________________________________
conv2d_5 (Conv2D)            (None, 35, 35, 64)        73792     
_________________________________________________________________
conv2d_6 (Conv2D)            (None, 33, 33, 32)        18464     
_________________________________________________________________
dropout_3 (Dropout)          (None, 33, 33, 32)        0         
_________________________________________________________________
flatten (Flatten)            (None, 34848)             0         
_________________________________________________________________
dense (Dense)                (None, 128)               4460672   
_________________________________________________________________
dense_1 (Dense)              (None, 64)                8256      
_________________________________________________________________
dense_2 (Dense)              (None, 32)                2080      
_________________________________________________________________
dense_3 (Dense)              (None, 2)                 66        
=================================================================
Total params: 5,029,666
Trainable params: 5,029,666
Non-trainable params: 0
_________________________________________________________________

四.编译

在准备对模型进行训练之前,还需要再对其进行一些设置。以下内容是在模型的编译步骤中添加的:

损失函数(loss):用于衡量模型在训练期间的准确率。
优化器(optimizer):决定模型如何根据其看到的数据和自身的损失函数进行更新。
指标(metrics):用于监控训练和测试步骤。以下示例使用了准确率,即被正确分类的图像的比率。

动态学习率:

1.指数衰减

tf.keras.optimizers.schedules.ExponentialDecay(
initial_learning_rate,
decay_steps,
decay_rate,
staircase=False,
name=None
)

1.initial_learning_rate 为事先设定的初始学习率。
2.decay_steps 用来控制衰减速度,经过多少step学习率更新一次
3.decay_rate 为衰减系数
4.staircase 默认为False,如果是False,学习率会平滑地衰减,而非每迭代decay_steps轮才衰减一次,如果为True,则会每迭代decay_steps次才衰减一次,这种称为阶梯函数。

decayed_learning_rate= initial_learning_rate*decay_rate^(step/decay_steps)

这里的step指的是一个batch。

2.分段常数衰减

对于前1000步,学习率为0.001,对于接下来的1000步,学习率为0.01,对于任何其他步骤,学习率为0.1

step = tf.Variable(0, trainable=False)
boundaries = [1000, 11000]
values = [0.001, 0.01, 0.1]
learning_rate_fn = tf.keras.optimizers.schedules.PiecewiseConstantDecay( boundaries, values)

3.多项式衰减

给定一个初始学习率和一个结束学习率,优化过程中使用指定多项式形式从初始学习率降到一个结束学习率,比如用2次、3次多项式。

def decayed_learning_rate(step):
step = min(step, decay_steps)
return ((initial_learning_rate - end_learning_rate) * (1 - step / decay_steps) ^ (power) ) + end_learning_rate

例子:starter_learning_rate = 0.1
end_learning_rate = 0.01
decay_steps = 1000
learning_rate_fn = tf.keras.optimizers.schedules.PolynomialDecay(
starter_learning_rate,
decay_steps,
end_learning_rate,
power=0.5)

4.逆时间衰减

def decayed_learning_rate(step):
return initial_learning_rate / (1 + decay_rate * step / decay_step)

例:
initial_learning_rate = 0.1
decay_steps = 1.0
decay_rate = 0.5
learning_rate_fn = keras.optimizers.schedules.InverseTimeDecay(
initial_learning_rate, decay_steps, decay_rate)

#动态学习率:
initial_learning_rate=tf.keras.optimizers.schedules.ExponentialDecay(
    initial_learning_rate =1e-4,
    decay_steps=1000,
    decay_rate=0.98
)
# 设置优化器
# opt = tf.keras.optimizers.Adam(learning_rate=1e-4)
opt = tf.keras.optimizers.Adam(initial_learning_rate)
model.compile(optimizer=opt,
              loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
              metrics=['accuracy'])

五.训练模型

关于ModelCheckpoint的详细介绍可参考文章🔗ModelCheckpoint 讲解【TensorFlow2入门手册】

from tensorflow.keras.callbacks import ModelCheckpoint

epochs = 60

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 1/60
53/54 [============================>.] - ETA: 0s - loss: 0.0050 - accuracy: 0.9982
Epoch 00001: val_accuracy improved from -inf to 0.89720, saving model to best_model.h5
54/54 [==============================] - 3s 53ms/step - loss: 0.0063 - accuracy: 0.9977 - val_loss: 1.2932 - val_accuracy: 0.8972
Epoch 2/60
53/54 [============================>.] - ETA: 0s - loss: 0.0041 - accuracy: 0.9988
Epoch 00002: val_accuracy improved from 0.89720 to 0.90888, saving model to best_model.h5
54/54 [==============================] - 3s 50ms/step - loss: 0.0040 - accuracy: 0.9988 - val_loss: 1.3743 - val_accuracy: 0.9089
Epoch 3/60
53/54 [============================>.] - ETA: 0s - loss: 0.0026 - accuracy: 0.9994
Epoch 00003: val_accuracy improved from 0.90888 to 0.91589, saving model to best_model.h5
54/54 [==============================] - 3s 51ms/step - loss: 0.0026 - accuracy: 0.9994 - val_loss: 1.1345 - val_accuracy: 0.9159
Epoch 4/60
53/54 [============================>.] - ETA: 0s - loss: 7.8182e-05 - accuracy: 1.0000
Epoch 00004: val_accuracy improved from 0.91589 to 0.92056, saving model to best_model.h5
54/54 [==============================] - 3s 51ms/step - loss: 7.6776e-05 - accuracy: 1.0000 - val_loss: 1.1900 - val_accuracy: 0.9206
Epoch 5/60
53/54 [============================>.] - ETA: 0s - loss: 0.0106 - accuracy: 0.9970
Epoch 00005: val_accuracy did not improve from 0.92056
54/54 [==============================] - 3s 47ms/step - loss: 0.0104 - accuracy: 0.9971 - val_loss: 1.0101 - val_accuracy: 0.9112
Epoch 6/60
53/54 [============================>.] - ETA: 0s - loss: 0.0253 - accuracy: 0.9958
Epoch 00006: val_accuracy did not improve from 0.92056
54/54 [==============================] - 3s 47ms/step - loss: 0.0253 - accuracy: 0.9959 - val_loss: 0.9696 - val_accuracy: 0.9112
Epoch 7/60
53/54 [============================>.] - ETA: 0s - loss: 0.0033 - accuracy: 0.9994
Epoch 00007: val_accuracy did not improve from 0.92056
54/54 [==============================] - 3s 47ms/step - loss: 0.0057 - accuracy: 0.9988 - val_loss: 1.1420 - val_accuracy: 0.8949
Epoch 8/60
53/54 [============================>.] - ETA: 0s - loss: 3.9260e-04 - accuracy: 1.0000
Epoch 00008: val_accuracy did not improve from 0.92056
54/54 [==============================] - 3s 47ms/step - loss: 3.8587e-04 - accuracy: 1.0000 - val_loss: 0.9936 - val_accuracy: 0.9112
Epoch 9/60
53/54 [============================>.] - ETA: 0s - loss: 0.0053 - accuracy: 0.9994
Epoch 00009: val_accuracy did not improve from 0.92056
54/54 [==============================] - 3s 48ms/step - loss: 0.0052 - accuracy: 0.9994 - val_loss: 0.8870 - val_accuracy: 0.9089
Epoch 10/60
53/54 [============================>.] - ETA: 0s - loss: 7.2920e-04 - accuracy: 1.0000
Epoch 00010: val_accuracy did not improve from 0.92056
54/54 [==============================] - 3s 48ms/step - loss: 7.1885e-04 - accuracy: 1.0000 - val_loss: 0.9347 - val_accuracy: 0.9112
Epoch 11/60
53/54 [============================>.] - ETA: 0s - loss: 7.6600e-05 - accuracy: 1.0000
Epoch 00011: val_accuracy did not improve from 0.92056
54/54 [==============================] - 3s 48ms/step - loss: 8.0364e-05 - accuracy: 1.0000 - val_loss: 0.9536 - val_accuracy: 0.9159
Epoch 12/60
53/54 [============================>.] - ETA: 0s - loss: 3.9092e-05 - accuracy: 1.0000
Epoch 00012: val_accuracy did not improve from 0.92056
54/54 [==============================] - 3s 48ms/step - loss: 3.8726e-05 - accuracy: 1.0000 - val_loss: 0.9584 - val_accuracy: 0.9182
Epoch 13/60
53/54 [============================>.] - ETA: 0s - loss: 2.2678e-05 - accuracy: 1.0000
Epoch 00013: val_accuracy did not improve from 0.92056
54/54 [==============================] - 3s 48ms/step - loss: 2.2498e-05 - accuracy: 1.0000 - val_loss: 0.9669 - val_accuracy: 0.9182
Epoch 14/60
53/54 [============================>.] - ETA: 0s - loss: 6.3825e-05 - accuracy: 1.0000
Epoch 00014: val_accuracy did not improve from 0.92056
54/54 [==============================] - 3s 48ms/step - loss: 6.2711e-05 - accuracy: 1.0000 - val_loss: 0.9723 - val_accuracy: 0.9136
Epoch 15/60
53/54 [============================>.] - ETA: 0s - loss: 3.3404e-05 - accuracy: 1.0000
Epoch 00015: val_accuracy did not improve from 0.92056
54/54 [==============================] - 3s 48ms/step - loss: 3.4088e-05 - accuracy: 1.0000 - val_loss: 0.9766 - val_accuracy: 0.9159
Epoch 16/60
53/54 [============================>.] - ETA: 0s - loss: 1.6575e-05 - accuracy: 1.0000
Epoch 00016: val_accuracy did not improve from 0.92056
54/54 [==============================] - 3s 48ms/step - loss: 1.6413e-05 - accuracy: 1.0000 - val_loss: 0.9802 - val_accuracy: 0.9182
Epoch 17/60
53/54 [============================>.] - ETA: 0s - loss: 1.8803e-05 - accuracy: 1.0000
Epoch 00017: val_accuracy did not improve from 0.92056
54/54 [==============================] - 3s 48ms/step - loss: 1.9470e-05 - accuracy: 1.0000 - val_loss: 0.9873 - val_accuracy: 0.9182
Epoch 18/60
53/54 [============================>.] - ETA: 0s - loss: 2.4461e-05 - accuracy: 1.0000
Epoch 00018: val_accuracy did not improve from 0.92056
54/54 [==============================] - 3s 48ms/step - loss: 2.4083e-05 - accuracy: 1.0000 - val_loss: 1.0077 - val_accuracy: 0.9136
Epoch 19/60
53/54 [============================>.] - ETA: 0s - loss: 1.0685e-05 - accuracy: 1.0000
Epoch 00019: val_accuracy did not improve from 0.92056
54/54 [==============================] - 3s 48ms/step - loss: 1.1629e-05 - accuracy: 1.0000 - val_loss: 1.0141 - val_accuracy: 0.9136
Epoch 20/60
53/54 [============================>.] - ETA: 0s - loss: 8.6738e-06 - accuracy: 1.0000
Epoch 00020: val_accuracy did not improve from 0.92056
54/54 [==============================] - 3s 48ms/step - loss: 8.5314e-06 - accuracy: 1.0000 - val_loss: 1.0205 - val_accuracy: 0.9136
Epoch 21/60
53/54 [============================>.] - ETA: 0s - loss: 8.3925e-06 - accuracy: 1.0000
Epoch 00021: val_accuracy did not improve from 0.92056
54/54 [==============================] - 3s 48ms/step - loss: 8.3665e-06 - accuracy: 1.0000 - val_loss: 1.0274 - val_accuracy: 0.9159
Epoch 22/60
53/54 [============================>.] - ETA: 0s - loss: 7.9510e-06 - accuracy: 1.0000
Epoch 00022: val_accuracy did not improve from 0.92056
54/54 [==============================] - 3s 48ms/step - loss: 7.8208e-06 - accuracy: 1.0000 - val_loss: 1.0317 - val_accuracy: 0.9159
Epoch 23/60
53/54 [============================>.] - ETA: 0s - loss: 1.1366e-05 - accuracy: 1.0000
Epoch 00023: val_accuracy did not improve from 0.92056
54/54 [==============================] - 3s 48ms/step - loss: 1.1174e-05 - accuracy: 1.0000 - val_loss: 1.0382 - val_accuracy: 0.9159
Epoch 24/60
53/54 [============================>.] - ETA: 0s - loss: 1.1966e-05 - accuracy: 1.0000
Epoch 00024: val_accuracy did not improve from 0.92056
54/54 [==============================] - 3s 48ms/step - loss: 1.1897e-05 - accuracy: 1.0000 - val_loss: 1.0424 - val_accuracy: 0.9159
Epoch 25/60
53/54 [============================>.] - ETA: 0s - loss: 1.2861e-05 - accuracy: 1.0000
Epoch 00025: val_accuracy did not improve from 0.92056
54/54 [==============================] - 3s 48ms/step - loss: 1.2924e-05 - accuracy: 1.0000 - val_loss: 1.0479 - val_accuracy: 0.9182
Epoch 26/60
53/54 [============================>.] - ETA: 0s - loss: 6.8087e-06 - accuracy: 1.0000
Epoch 00026: val_accuracy did not improve from 0.92056
54/54 [==============================] - 3s 49ms/step - loss: 6.7205e-06 - accuracy: 1.0000 - val_loss: 1.0530 - val_accuracy: 0.9159
Epoch 27/60
53/54 [============================>.] - ETA: 0s - loss: 9.3084e-06 - accuracy: 1.0000
Epoch 00027: val_accuracy did not improve from 0.92056
54/54 [==============================] - 3s 48ms/step - loss: 9.2614e-06 - accuracy: 1.0000 - val_loss: 1.0555 - val_accuracy: 0.9159
Epoch 28/60
53/54 [============================>.] - ETA: 0s - loss: 4.8505e-06 - accuracy: 1.0000
Epoch 00028: val_accuracy did not improve from 0.92056
54/54 [==============================] - 3s 48ms/step - loss: 4.8538e-06 - accuracy: 1.0000 - val_loss: 1.0623 - val_accuracy: 0.9159
Epoch 29/60
53/54 [============================>.] - ETA: 0s - loss: 9.3251e-06 - accuracy: 1.0000
Epoch 00029: val_accuracy did not improve from 0.92056
54/54 [==============================] - 3s 48ms/step - loss: 9.1991e-06 - accuracy: 1.0000 - val_loss: 1.0600 - val_accuracy: 0.9136
Epoch 30/60
53/54 [============================>.] - ETA: 0s - loss: 4.6604e-06 - accuracy: 1.0000
Epoch 00030: val_accuracy did not improve from 0.92056
54/54 [==============================] - 3s 48ms/step - loss: 4.5880e-06 - accuracy: 1.0000 - val_loss: 1.0614 - val_accuracy: 0.9136
Epoch 31/60
53/54 [============================>.] - ETA: 0s - loss: 7.5916e-06 - accuracy: 1.0000
Epoch 00031: val_accuracy did not improve from 0.92056
54/54 [==============================] - 3s 48ms/step - loss: 7.8569e-06 - accuracy: 1.0000 - val_loss: 1.0644 - val_accuracy: 0.9136
Epoch 32/60
53/54 [============================>.] - ETA: 0s - loss: 6.1165e-06 - accuracy: 1.0000
Epoch 00032: val_accuracy did not improve from 0.92056
54/54 [==============================] - 3s 48ms/step - loss: 6.0615e-06 - accuracy: 1.0000 - val_loss: 1.0694 - val_accuracy: 0.9136
Epoch 33/60
53/54 [============================>.] - ETA: 0s - loss: 7.8328e-06 - accuracy: 1.0000
Epoch 00033: val_accuracy did not improve from 0.92056
54/54 [==============================] - 3s 48ms/step - loss: 7.6878e-06 - accuracy: 1.0000 - val_loss: 1.0708 - val_accuracy: 0.9136
Epoch 34/60
53/54 [============================>.] - ETA: 0s - loss: 5.9232e-06 - accuracy: 1.0000
Epoch 00034: val_accuracy did not improve from 0.92056
54/54 [==============================] - 3s 48ms/step - loss: 5.9905e-06 - accuracy: 1.0000 - val_loss: 1.0751 - val_accuracy: 0.9089
Epoch 35/60
53/54 [============================>.] - ETA: 0s - loss: 9.6137e-06 - accuracy: 1.0000
Epoch 00035: val_accuracy did not improve from 0.92056
54/54 [==============================] - 3s 48ms/step - loss: 9.8573e-06 - accuracy: 1.0000 - val_loss: 1.0735 - val_accuracy: 0.9136
Epoch 36/60
53/54 [============================>.] - ETA: 0s - loss: 5.2670e-06 - accuracy: 1.0000
Epoch 00036: val_accuracy did not improve from 0.92056
54/54 [==============================] - 3s 48ms/step - loss: 5.4055e-06 - accuracy: 1.0000 - val_loss: 1.0731 - val_accuracy: 0.9112
Epoch 37/60
53/54 [============================>.] - ETA: 0s - loss: 5.5615e-06 - accuracy: 1.0000
Epoch 00037: val_accuracy did not improve from 0.92056
54/54 [==============================] - 3s 48ms/step - loss: 5.7156e-06 - accuracy: 1.0000 - val_loss: 1.0746 - val_accuracy: 0.9112
Epoch 38/60
53/54 [============================>.] - ETA: 0s - loss: 2.7589e-06 - accuracy: 1.0000
Epoch 00038: val_accuracy did not improve from 0.92056
54/54 [==============================] - 3s 48ms/step - loss: 2.9299e-06 - accuracy: 1.0000 - val_loss: 1.0776 - val_accuracy: 0.9112
Epoch 39/60
53/54 [============================>.] - ETA: 0s - loss: 6.5470e-06 - accuracy: 1.0000
Epoch 00039: val_accuracy did not improve from 0.92056
54/54 [==============================] - 3s 48ms/step - loss: 6.4877e-06 - accuracy: 1.0000 - val_loss: 1.0848 - val_accuracy: 0.9112
Epoch 40/60
53/54 [============================>.] - ETA: 0s - loss: 2.6372e-06 - accuracy: 1.0000
Epoch 00040: val_accuracy did not improve from 0.92056
54/54 [==============================] - 3s 48ms/step - loss: 2.6875e-06 - accuracy: 1.0000 - val_loss: 1.0902 - val_accuracy: 0.9112
Epoch 41/60
53/54 [============================>.] - ETA: 0s - loss: 7.3409e-06 - accuracy: 1.0000
Epoch 00041: val_accuracy did not improve from 0.92056
54/54 [==============================] - 3s 48ms/step - loss: 7.2177e-06 - accuracy: 1.0000 - val_loss: 1.0883 - val_accuracy: 0.9136
Epoch 42/60
53/54 [============================>.] - ETA: 0s - loss: 2.8747e-06 - accuracy: 1.0000
Epoch 00042: val_accuracy did not improve from 0.92056
54/54 [==============================] - 3s 48ms/step - loss: 2.8236e-06 - accuracy: 1.0000 - val_loss: 1.0881 - val_accuracy: 0.9136
Epoch 43/60
53/54 [============================>.] - ETA: 0s - loss: 4.8318e-06 - accuracy: 1.0000
Epoch 00043: val_accuracy did not improve from 0.92056
54/54 [==============================] - 3s 48ms/step - loss: 4.8381e-06 - accuracy: 1.0000 - val_loss: 1.0980 - val_accuracy: 0.9136
Epoch 44/60
53/54 [============================>.] - ETA: 0s - loss: 2.3741e-05 - accuracy: 1.0000
Epoch 00044: val_accuracy did not improve from 0.92056
54/54 [==============================] - 3s 48ms/step - loss: 2.3302e-05 - accuracy: 1.0000 - val_loss: 1.1117 - val_accuracy: 0.9112
Epoch 45/60
53/54 [============================>.] - ETA: 0s - loss: 4.2355e-06 - accuracy: 1.0000
Epoch 00045: val_accuracy did not improve from 0.92056
54/54 [==============================] - 3s 48ms/step - loss: 4.2420e-06 - accuracy: 1.0000 - val_loss: 1.1208 - val_accuracy: 0.9112
Epoch 46/60
53/54 [============================>.] - ETA: 0s - loss: 4.3874e-06 - accuracy: 1.0000
Epoch 00046: val_accuracy did not improve from 0.92056
54/54 [==============================] - 3s 48ms/step - loss: 4.3756e-06 - accuracy: 1.0000 - val_loss: 1.1239 - val_accuracy: 0.9112
Epoch 47/60
53/54 [============================>.] - ETA: 0s - loss: 7.9267e-06 - accuracy: 1.0000
Epoch 00047: val_accuracy did not improve from 0.92056
54/54 [==============================] - 3s 48ms/step - loss: 7.7832e-06 - accuracy: 1.0000 - val_loss: 1.1404 - val_accuracy: 0.9112
Epoch 48/60
53/54 [============================>.] - ETA: 0s - loss: 1.0336e-04 - accuracy: 1.0000
Epoch 00048: val_accuracy did not improve from 0.92056
54/54 [==============================] - 3s 48ms/step - loss: 1.0195e-04 - accuracy: 1.0000 - val_loss: 1.0769 - val_accuracy: 0.9065
Epoch 49/60
53/54 [============================>.] - ETA: 0s - loss: 5.9365e-05 - accuracy: 1.0000
Epoch 00049: val_accuracy did not improve from 0.92056
54/54 [==============================] - 3s 48ms/step - loss: 5.8409e-05 - accuracy: 1.0000 - val_loss: 1.0978 - val_accuracy: 0.9019
Epoch 50/60
53/54 [============================>.] - ETA: 0s - loss: 1.8070e-05 - accuracy: 1.0000
Epoch 00050: val_accuracy did not improve from 0.92056
54/54 [==============================] - 3s 48ms/step - loss: 2.1067e-05 - accuracy: 1.0000 - val_loss: 1.1090 - val_accuracy: 0.9136
Epoch 51/60
53/54 [============================>.] - ETA: 0s - loss: 9.4564e-06 - accuracy: 1.0000
Epoch 00051: val_accuracy did not improve from 0.92056
54/54 [==============================] - 3s 48ms/step - loss: 1.1124e-05 - accuracy: 1.0000 - val_loss: 1.1198 - val_accuracy: 0.9065
Epoch 52/60
53/54 [============================>.] - ETA: 0s - loss: 6.2085e-06 - accuracy: 1.0000
Epoch 00052: val_accuracy did not improve from 0.92056
54/54 [==============================] - 3s 48ms/step - loss: 6.0947e-06 - accuracy: 1.0000 - val_loss: 1.1339 - val_accuracy: 0.9089
Epoch 53/60
53/54 [============================>.] - ETA: 0s - loss: 6.8576e-06 - accuracy: 1.0000
Epoch 00053: val_accuracy did not improve from 0.92056
54/54 [==============================] - 3s 48ms/step - loss: 6.7385e-06 - accuracy: 1.0000 - val_loss: 1.1444 - val_accuracy: 0.9136
Epoch 54/60
53/54 [============================>.] - ETA: 0s - loss: 2.3266e-06 - accuracy: 1.0000
Epoch 00054: val_accuracy did not improve from 0.92056
54/54 [==============================] - 3s 48ms/step - loss: 2.3660e-06 - accuracy: 1.0000 - val_loss: 1.1482 - val_accuracy: 0.9136
Epoch 55/60
53/54 [============================>.] - ETA: 0s - loss: 6.9108e-06 - accuracy: 1.0000
Epoch 00055: val_accuracy did not improve from 0.92056
54/54 [==============================] - 3s 48ms/step - loss: 6.8309e-06 - accuracy: 1.0000 - val_loss: 1.1652 - val_accuracy: 0.9112
Epoch 56/60
53/54 [============================>.] - ETA: 0s - loss: 2.6830e-06 - accuracy: 1.0000
Epoch 00056: val_accuracy did not improve from 0.92056
54/54 [==============================] - 3s 48ms/step - loss: 2.6953e-06 - accuracy: 1.0000 - val_loss: 1.1656 - val_accuracy: 0.9112
Epoch 57/60
53/54 [============================>.] - ETA: 0s - loss: 3.5077e-06 - accuracy: 1.0000
Epoch 00057: val_accuracy did not improve from 0.92056
54/54 [==============================] - 3s 48ms/step - loss: 3.4460e-06 - accuracy: 1.0000 - val_loss: 1.1725 - val_accuracy: 0.9136
Epoch 58/60
53/54 [============================>.] - ETA: 0s - loss: 2.5810e-06 - accuracy: 1.0000
Epoch 00058: val_accuracy did not improve from 0.92056
54/54 [==============================] - 3s 48ms/step - loss: 2.5596e-06 - accuracy: 1.0000 - val_loss: 1.1768 - val_accuracy: 0.9136
Epoch 59/60
53/54 [============================>.] - ETA: 0s - loss: 9.7414e-07 - accuracy: 1.0000
Epoch 00059: val_accuracy did not improve from 0.92056
54/54 [==============================] - 3s 48ms/step - loss: 9.5727e-07 - accuracy: 1.0000 - val_loss: 1.1797 - val_accuracy: 0.9136
Epoch 60/60
53/54 [============================>.] - ETA: 0s - loss: 2.4624e-06 - accuracy: 1.0000
Epoch 00060: val_accuracy did not improve from 0.92056
54/54 [==============================] - 3s 48ms/step - loss: 2.4237e-06 - accuracy: 1.0000 - val_loss: 1.1821 - val_accuracy: 0.9136

六.模型评估

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()

2.指定图片进行预测

# 加载效果最好的模型权重
model.load_weights('best_model.h5')
val_loss,val_acc=model.evaluate(val_ds,verbose=2)
14/14 - 0s - loss: 1.1900 - accuracy: 0.9206
from PIL import Image
import numpy as np

# img = Image.open("./45-data/Monkeypox/M06_01_04.jpg")  #这里选择你需要预测的图片
img = Image.open("/home/mw/input/HD4506/45-data/Monkeypox/M01_01_13.jpg")  #这里选择你需要预测的图片
img=np.array(img)
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)])

预测结果为: Monkeypox

实验结果:

1.在原网络结构不变的情况下:

使用CPU训练,epochs=50,60,70分别运行2次后,accuracy最好准确率分别为0.8949,0.8879,0.8879,epochs=200时,最好准确率为0.9042
使用GPU训练,epochs=50,60,70分别运行2次后,accuracy最好准确率分别为0.8995,0.90654,0.8972,epochs=200时,最好准确率为0.9019
cpu和GPU训练好像并没有什么差别,但是刚开始训练时epochs=50,GPU准确率只有0.53。

2.改为MaxPooling,epochs=60,accuracy=0.8972
3.增加全连接,epochs=60,accuracy最好是0.9042,不稳定,增加卷积层,accuracy最好是0.91121,稳定。
4.batch_size=64,accuracy并未增加,算力增加,训练时间加长。
5.图片(180,180)accuracy=0.9229 图片尺寸一般为(180×180)或者(224×224)

  • 0
    点赞
  • 3
    收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
©️2022 CSDN 皮肤主题:深蓝海洋 设计师:CSDN官方博客 返回首页
评论
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值