- 本文为365天深度学习训练营 中的学习记录博客
- 原作者:K同学啊
●难度:夯实基础⭐⭐
●语言:Python3、TensorFlow2
要求:
1.了解model.train_on_batch()并运用
2.了解tqdm,并使用tqdm实现可视化进度条
拔高(可选):
本文代码中存在一个严重的BUG,请找出它并配以文字说明
探索(难度有点大):
修改代码,处理BUG
这篇文章中放弃了以往的model.fit()训练方法,改用model.train_on_batch方法。两种方法的比较:
● model.fit():用起来十分简单,对新手非常友好。
● model.train_on_batch():封装程度更低,可以玩更多花样。
此外也引入了进度条的显示方式,更加方便我们及时查看模型训练过程中的情况,可以及时打印各项指标。
我的环境:
●操作系统:ubuntu 22.04
●语言环境:python 3.8.10
●编译器:jupyter notebook
●深度学习框架:tensorflow-gpu 2.9.0
●显卡(GPU):RTX 3090(24GB) * 1
●数据集:猫狗识别数据集
一、前期工作
- 设置GPU(如果使用的是CPU可以注释掉这部分的代码。)
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")# 打印显卡信息,确认GPU可用
print(gpus)
代码输出:
[PhysicalDevice(name='/physical_device:GPU:0', device_type='GPU')]
- 导入数据
import matplotlib.pyplot as plt
# 支持中文
plt.rcParams['font.sans-serif'] = ['SimHei'] # 用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False # 用来正常显示负号import os,PIL,pathlib#隐藏警告
import warnings
warnings.filterwarnings('ignore')data_dir = "./T8/data"
data_dir = pathlib.Path(data_dir)image_count = len(list(data_dir.glob('*/*')))print("图片总数为:",image_count)
代码输出:
图片总数为: 3400
二、数据预处理
- 加载数据
使用image_dataset_from_directory方法将磁盘中的数据加载到tf.data.Dataset中。
batch_size = 8
img_height = 224
img_width = 224
TensorFlow版本是2.2.0的同学可能会遇到module ‘tensorflow.keras.preprocessing’ has no attribute 'image_dataset_from_directory’的报错,升级一下TensorFlow就OK了。
"""
关于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=12,image_size=(img_height, img_width),batch_size=batch_size)
代码输出:
Found 3400 files belonging to 2 classes.
Using 2720 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=12,image_size=(img_height, img_width),batch_size=batch_size)
代码输出:
Found 3400 files belonging to 2 classes.
Using 680 files for validation.
我们可以通过class_names输出数据集的标签。标签将按字母顺序对应于目录名称。
class_names = train_ds.class_names
print(class_names)
代码输出:
['cat', 'dog']
len(class_names)
代码输出:
2
- 再次检查数据
for image_batch, labels_batch in train_ds:print(image_batch.shape)print(labels_batch.shape)break
代码输出:
(8, 224, 224, 3)
(8,)
● Image_batch是形状的张量(8, 224, 224, 3)。这是一批形状224x224x3的8张图片(最后一维指的是彩色通道RGB)。
● Label_batch是形状(8,)的张量,这些标签对应8张图片。
- 配置数据集
● shuffle() : 打乱数据,关于此函数的详细介绍可以参考:https://zhuanlan.zhihu.com/p/42417456
● prefetch() :预取数据,加速运行,其详细介绍可以参考我前两篇文章,里面都有讲解。
● cache() :将数据集缓存到内存当中,加速运行。
AUTOTUNE = tf.data.AUTOTUNEdef preprocess_image(image,label):return (image/255.0,label)# 归一化处理
train_ds = train_ds.map(preprocess_image, num_parallel_calls=AUTOTUNE)
val_ds = val_ds.map(preprocess_image, num_parallel_calls=AUTOTUNE)train_ds = train_ds.cache().shuffle(1000).prefetch(buffer_size=AUTOTUNE)
val_ds = val_ds.cache().prefetch(buffer_size=AUTOTUNE)
如果报 AttributeError: module ‘tensorflow._api.v2.data’ has no attribute ‘AUTOTUNE’ 错误,就将 AUTOTUNE = tf.data.AUTOTUNE 更换为 AUTOTUNE = tf.data.experimental.AUTOTUNE,这个错误是由于版本问题引起的。
- 可视化数据
# 使用黑体 SimHei 显示中文字体
plt.rcParams['font.family'] = 'sans-serif'
plt.rcParams['font.sans-serif'] = ['SimHei'] # 设置默认字体为黑体
plt.rcParams['axes.unicode_minus'] = False # 解决负号显示问题plt.figure(figsize=(15, 10)) # 图形的宽为15高为10for images, labels in train_ds.take(1):for i in range(8):ax = plt.subplot(5, 8, i + 1) plt.imshow(images[i])plt.title(class_names[labels[i]])plt.axis("off")
代码输出:
三、构建VG-16网络
VGG优缺点分析:
● VGG优点
VGG的结构非常简洁,整个网络都使用了同样大小的卷积核尺寸(3x3)和最大池化尺寸(2x2)。
● VGG缺点
1)训练时间过长,调参难度大。
2)需要的存储容量大,不利于部署。例如存储VGG-16权重值文件的大小为500多MB,不利于安装到嵌入式系统中。
结构说明:
● 13个卷积层(Convolutional Layer),分别用blockX_convX表示。
● 3个全连接层(Fully connected Layer),分别用fcX与predictions表示。
● 5个池化层(Pool layer),分别用blockX_pool表示。
VGG-16包含了16个隐藏层(13个卷积层和3个全连接层),故称为VGG-16。
from tensorflow.keras import layers, models, Input
from tensorflow.keras.models import Model
from tensorflow.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(1000, (img_width, img_height, 3))
model.summary()
代码输出:
Model: "model"
_________________________________________________________________Layer (type) Output Shape Param #
=================================================================input_1 (InputLayer) [(None, 224, 224, 3)] 0 block1_conv1 (Conv2D) (None, 224, 224, 64) 1792 block1_conv2 (Conv2D) (None, 224, 224, 64) 36928 block1_pool (MaxPooling2D) (None, 112, 112, 64) 0 block2_conv1 (Conv2D) (None, 112, 112, 128) 73856 block2_conv2 (Conv2D) (None, 112, 112, 128) 147584 block2_pool (MaxPooling2D) (None, 56, 56, 128) 0 block3_conv1 (Conv2D) (None, 56, 56, 256) 295168 block3_conv2 (Conv2D) (None, 56, 56, 256) 590080 block3_conv3 (Conv2D) (None, 56, 56, 256) 590080 block3_pool (MaxPooling2D) (None, 28, 28, 256) 0 block4_conv1 (Conv2D) (None, 28, 28, 512) 1180160 block4_conv2 (Conv2D) (None, 28, 28, 512) 2359808 block4_conv3 (Conv2D) (None, 28, 28, 512) 2359808 block4_pool (MaxPooling2D) (None, 14, 14, 512) 0 block5_conv1 (Conv2D) (None, 14, 14, 512) 2359808 block5_conv2 (Conv2D) (None, 14, 14, 512) 2359808 block5_conv3 (Conv2D) (None, 14, 14, 512) 2359808 block5_pool (MaxPooling2D) (None, 7, 7, 512) 0 flatten (Flatten) (None, 25088) 0 fc1 (Dense) (None, 4096) 102764544 fc2 (Dense) (None, 4096) 16781312 predictions (Dense) (None, 1000) 4097000 =================================================================
Total params: 138,357,544
Trainable params: 138,357,544
Non-trainable params: 0
_________________________________________________________________
四、编译
在准备对模型进行训练之前,还需要再对其进行一些设置。以下内容是在模型的编译步骤中添加的:
● 损失函数(loss):用于衡量模型在训练期间的准确率。
● 优化器(optimizer):决定模型如何根据其看到的数据和自身的损失函数进行更新。
● 评价函数(metrics):用于监控训练和测试步骤。以下示例使用了准确率,即被正确分类的图像的比率。
model.compile(optimizer="adam",loss ='sparse_categorical_crossentropy',metrics =['accuracy'])
train_total = len(train_ds)
val_total = len(val_ds)
五、训练模型
from tqdm import tqdm
import tensorflow.keras.backend as Kepochs = 10
lr = 1e-4# 记录训练数据,方便后面的分析
history_train_loss = []
history_train_accuracy = []
history_val_loss = []
history_val_accuracy = []for epoch in range(epochs):train_total = len(train_ds)val_total = len(val_ds)"""total:预期的迭代数目ncols:控制进度条宽度mininterval:进度更新最小间隔,以秒为单位(默认值:0.1)"""with tqdm(total=train_total, desc=f'Epoch {epoch + 1}/{epochs}',mininterval=1,ncols=100) as pbar:lr = lr*0.92K.set_value(model.optimizer.lr, lr)for image,label in train_ds: """训练模型,简单理解train_on_batch就是:它是比model.fit()更高级的一个用法想详细了解 train_on_batch 的同学,可以看看我的这篇文章:https://www.yuque.com/mingtian-fkmxf/hv4lcq/ztt4gy"""history = model.train_on_batch(image,label)train_loss = history[0]train_accuracy = history[1]pbar.set_postfix({"loss": "%.4f"%train_loss,"accuracy":"%.4f"%train_accuracy,"lr": K.get_value(model.optimizer.lr)})pbar.update(1)history_train_loss.append(train_loss)history_train_accuracy.append(train_accuracy)print('开始验证!')with tqdm(total=val_total, desc=f'Epoch {epoch + 1}/{epochs}',mininterval=0.3,ncols=100) as pbar:for image,label in val_ds: history = model.test_on_batch(image,label)val_loss = history[0]val_accuracy = history[1]pbar.set_postfix({"loss": "%.4f"%val_loss,"accuracy":"%.4f"%val_accuracy})pbar.update(1)history_val_loss.append(val_loss)history_val_accuracy.append(val_accuracy)print('结束验证!')print("验证loss为:%.4f"%val_loss)print("验证准确率为:%.4f"%val_accuracy)
代码输出:
Epoch 1/10: 0%| | 0/340 [00:00<?, ?it/s]2024-09-14 20:44:44.561738: I tensorflow/stream_executor/cuda/cuda_dnn.cc:384] Loaded cuDNN version 8101
2024-09-14 20:44:46.215722: I tensorflow/stream_executor/cuda/cuda_blas.cc:1786] TensorFloat-32 will be used for the matrix multiplication. This will only be logged once.
Epoch 1/10: 100%|████████| 340/340 [00:23<00:00, 14.62it/s, loss=0.6074, accuracy=0.6250, lr=9.2e-5]开始验证!Epoch 1/10: 100%|█████████████████████| 85/85 [00:02<00:00, 31.36it/s, loss=0.5406, accuracy=0.5000]结束验证!
验证loss为:0.5406
验证准确率为:0.5000Epoch 2/10: 100%|███████| 340/340 [00:19<00:00, 17.57it/s, loss=0.0474, accuracy=1.0000, lr=8.46e-5]开始验证!Epoch 2/10: 100%|█████████████████████| 85/85 [00:02<00:00, 36.21it/s, loss=0.0241, accuracy=1.0000]结束验证!
验证loss为:0.0241
验证准确率为:1.0000Epoch 3/10: 100%|███████| 340/340 [00:19<00:00, 17.54it/s, loss=0.0456, accuracy=1.0000, lr=7.79e-5]开始验证!Epoch 3/10: 100%|█████████████████████| 85/85 [00:02<00:00, 35.72it/s, loss=0.5546, accuracy=0.7500]结束验证!
验证loss为:0.5546
验证准确率为:0.7500Epoch 4/10: 100%|███████| 340/340 [00:19<00:00, 17.68it/s, loss=0.0158, accuracy=1.0000, lr=7.16e-5]开始验证!Epoch 4/10: 100%|█████████████████████| 85/85 [00:02<00:00, 35.66it/s, loss=0.6066, accuracy=0.7500]结束验证!
验证loss为:0.6066
验证准确率为:0.7500Epoch 5/10: 100%|███████| 340/340 [00:19<00:00, 17.75it/s, loss=0.0034, accuracy=1.0000, lr=6.59e-5]开始验证!Epoch 5/10: 100%|█████████████████████| 85/85 [00:02<00:00, 35.88it/s, loss=0.0583, accuracy=1.0000]结束验证!
验证loss为:0.0583
验证准确率为:1.0000Epoch 6/10: 100%|███████| 340/340 [00:19<00:00, 17.69it/s, loss=0.0005, accuracy=1.0000, lr=6.06e-5]开始验证!Epoch 6/10: 100%|█████████████████████| 85/85 [00:02<00:00, 35.98it/s, loss=0.0002, accuracy=1.0000]结束验证!
验证loss为:0.0002
验证准确率为:1.0000Epoch 7/10: 100%|███████| 340/340 [00:19<00:00, 17.65it/s, loss=0.0000, accuracy=1.0000, lr=5.58e-5]开始验证!Epoch 7/10: 100%|█████████████████████| 85/85 [00:02<00:00, 35.95it/s, loss=0.0218, accuracy=1.0000]结束验证!
验证loss为:0.0218
验证准确率为:1.0000Epoch 8/10: 100%|███████| 340/340 [00:19<00:00, 17.68it/s, loss=0.0003, accuracy=1.0000, lr=5.13e-5]开始验证!Epoch 8/10: 100%|█████████████████████| 85/85 [00:02<00:00, 35.64it/s, loss=0.0022, accuracy=1.0000]结束验证!
验证loss为:0.0022
验证准确率为:1.0000Epoch 9/10: 100%|███████| 340/340 [00:19<00:00, 17.54it/s, loss=0.0000, accuracy=1.0000, lr=4.72e-5]开始验证!Epoch 9/10: 100%|█████████████████████| 85/85 [00:02<00:00, 35.49it/s, loss=0.0000, accuracy=1.0000]结束验证!
验证loss为:0.0000
验证准确率为:1.0000Epoch 10/10: 100%|██████| 340/340 [00:19<00:00, 17.63it/s, loss=0.0106, accuracy=1.0000, lr=4.34e-5]开始验证!Epoch 10/10: 100%|████████████████████| 85/85 [00:02<00:00, 35.79it/s, loss=0.0146, accuracy=1.0000]结束验证!
验证loss为:0.0146
验证准确率为:1.0000
# 这是我们之前的训练方法。
# history = model.fit(
# train_ds,
# validation_data=val_ds,
# epochs=epochs
# )
六、模型评估
epochs_range = range(epochs)plt.figure(figsize=(12, 4))
plt.subplot(1, 2, 1)plt.plot(epochs_range, history_train_accuracy, label='Training Accuracy')
plt.plot(epochs_range, history_val_accuracy, label='Validation Accuracy')
plt.legend(loc='lower right')
plt.title('Training and Validation Accuracy')plt.subplot(1, 2, 2)
plt.plot(epochs_range, history_train_loss, label='Training Loss')
plt.plot(epochs_range, history_val_loss, label='Validation Loss')
plt.legend(loc='upper right')
plt.title('Training and Validation Loss')
plt.show()
代码输出:
七、预测
import numpy as np
from matplotlib import font_manager# 使用 Noto Sans CJK 字体
plt.rcParams['font.family'] = 'sans-serif'
plt.rcParams['font.sans-serif'] = ['Noto Sans CJK SC'] # 设置为Noto Sans CJK字体
plt.rcParams['axes.unicode_minus'] = False # 解决负号显示问题# 采用加载的模型(new_model)来看预测结果
plt.figure(figsize=(18, 3)) # 图形的宽为18高为5
plt.suptitle("预测结果展示")for images, labels in val_ds.take(1):for i in range(8):ax = plt.subplot(1,8, i + 1) # 显示图片plt.imshow(images[i].numpy())# 需要给图片增加一个维度img_array = tf.expand_dims(images[i], 0) # 使用模型预测图片中的人物predictions = model.predict(img_array)plt.title(class_names[np.argmax(predictions)])plt.axis("off")
代码输出:
1/1 [==============================] - 0s 319ms/step
1/1 [==============================] - 0s 20ms/step
1/1 [==============================] - 0s 18ms/step
1/1 [==============================] - 0s 18ms/step
1/1 [==============================] - 0s 18ms/step
1/1 [==============================] - 0s 18ms/step
1/1 [==============================] - 0s 20ms/step
1/1 [==============================] - 0s 19ms/step
八、修改代码,处理BUG
主要的BUG在“五、训练模型”,修改如下:
from tqdm import tqdm
import tensorflow.keras.backend as K
import numpy as npepochs = 10
lr = 1e-4# 记录训练数据,方便后面的分析
history_train_loss = []
history_train_accuracy = []
history_val_loss = []
history_val_accuracy = []for epoch in range(epochs):train_total = len(train_ds)val_total = len(val_ds)"""total:预期的迭代数目ncols:控制进度条宽度mininterval:进度更新最小间隔,以秒为单位(默认值:0.1)"""with tqdm(total=train_total, desc=f'Epoch {epoch + 1}/{epochs}',mininterval=1,ncols=100) as pbar:lr = lr*0.92K.set_value(model.optimizer.lr, lr)train_loss = []train_accuracy = []for image,label in train_ds: """训练模型,简单理解train_on_batch就是:它是比model.fit()更高级的一个用法想详细了解 train_on_batch 的同学,可以看看我的这篇文章:https://www.yuque.com/mingtian-fkmxf/hv4lcq/ztt4gy"""# 这里生成的是每一个batch的acc与losshistory = model.train_on_batch(image,label)train_loss.append(history[0])train_accuracy.append(history[1])pbar.set_postfix({"train_loss": "%.4f"%history[0],"train_acc":"%.4f"%history[1],"lr": K.get_value(model.optimizer.lr)})pbar.update(1)history_train_loss.append(np.mean(train_loss))history_train_accuracy.append(np.mean(train_accuracy))print('开始验证!')with tqdm(total=val_total, desc=f'Epoch {epoch + 1}/{epochs}',mininterval=0.3,ncols=100) as pbar:val_loss = []val_accuracy = []for image,label in val_ds: # 这里生成的是每一个batch的acc与losshistory = model.test_on_batch(image,label)val_loss.append(history[0])val_accuracy.append(history[1])pbar.set_postfix({"val_loss": "%.4f"%history[0],"val_acc":"%.4f"%history[1]})pbar.update(1)history_val_loss.append(np.mean(val_loss))history_val_accuracy.append(np.mean(val_accuracy))print('结束验证!')print("验证loss为:%.4f"%np.mean(val_loss))print("验证准确率为:%.4f"%np.mean(val_accuracy))
上面的这段代码与之前的代码相比,区别是在如何计算并记录训练和验证的损失与准确率上。
主要区别:
- 每个 epoch 中的训练和验证损失、准确率的计算方式:
修改BUG前的代码:
每次处理一个 batch 后,直接将该 batch 的损失和准确率记录下来,并且每个 epoch 的训练和验证损失、准确率都是以最后一个 batch 的值为准。 这意味着最终记录到 history_train_loss 和 history_train_accuracy 的值是该 epoch 最后一个 batch 的损失和准确率,而不是整个 epoch 的平均值。
修改BUG后的代码:
每次处理一个 batch 后,将该 batch 的损失和准确率保存在一个列表中。 在 epoch 完成后,计算该 epoch 的所有batch 的损失和准确率的平均值,并将这些均值记录到 history_train_loss 和
history_train_accuracy。 因此,第二段代码记录的是整个 epoch 的平均训练和验证损失与准确率,能够更准确地反映整个训练集和验证集上的表现。
- 批处理后的统计处理:
修改BUG前的代码:
没有计算 epoch 内所有 batch 的损失与准确率的平均值,直接使用最后一个 batch 的结果作为 epoch 的整体表现。
修改BUG后的代码:
每个 epoch 内,所有 batch 的损失和准确率被存储到 train_loss 和 train_accuracy 列表中,最后通过np.mean() 计算平均值并记录。这种做法更精确,因为它考虑了所有 batch 的表现。
修改BUG前的代码更适合快速验证或不需要精确记录整体 epoch 表现的场景,因为它只记录每个 epoch 最后一个 batch 的表现。
修改BUG后的代码更适合需要精确分析每个 epoch 整体表现的情况,因为它计算了整个 epoch 的平均损失和准确率,能够更全面地反映模型的训练和验证过程。
修改BUG后运行代码,训练模型的数据如下:
Epoch 1/10: 0%| | 0/340 [00:00<?, ?it/s]2024-09-14 21:40:38.282945: I tensorflow/stream_executor/cuda/cuda_dnn.cc:384] Loaded cuDNN version 81012024-09-14 21:40:39.881639: I tensorflow/stream_executor/cuda/cuda_blas.cc:1786] TensorFloat-32 will be used for the matrix multiplication. This will only be logged once.Epoch 1/10: 100%|█| 340/340 [00:22<00:00, 15.17it/s, train_loss=0.7300, train_acc=0.2500, lr=9.2e-5]开始验证!Epoch 1/10: 100%|██████████████████| 85/85 [00:02<00:00, 32.92it/s, val_loss=0.6971, val_acc=0.3750]结束验证!验证loss为:0.6796验证准确率为:0.5426Epoch 2/10: 100%|█| 340/340 [00:18<00:00, 17.91it/s, train_loss=0.0571, train_acc=1.0000, lr=8.46e-5开始验证!Epoch 2/10: 100%|██████████████████| 85/85 [00:02<00:00, 36.76it/s, val_loss=0.1744, val_acc=0.8750]结束验证!验证loss为:0.2459验证准确率为:0.9162Epoch 3/10: 100%|█| 340/340 [00:19<00:00, 17.79it/s, train_loss=0.1029, train_acc=1.0000, lr=7.79e-5开始验证!Epoch 3/10: 100%|██████████████████| 85/85 [00:02<00:00, 36.90it/s, val_loss=1.1163, val_acc=0.8750]结束验证!验证loss为:0.2143验证准确率为:0.9324Epoch 4/10: 100%|█| 340/340 [00:19<00:00, 17.78it/s, train_loss=0.0312, train_acc=1.0000, lr=7.16e-5开始验证!Epoch 4/10: 100%|██████████████████| 85/85 [00:02<00:00, 36.53it/s, val_loss=0.0139, val_acc=1.0000]结束验证!验证loss为:0.0251验证准确率为:0.9912Epoch 5/10: 100%|█| 340/340 [00:19<00:00, 17.77it/s, train_loss=0.0061, train_acc=1.0000, lr=6.59e-5开始验证!Epoch 5/10: 100%|██████████████████| 85/85 [00:02<00:00, 36.21it/s, val_loss=0.0040, val_acc=1.0000]结束验证!验证loss为:0.0427验证准确率为:0.9868Epoch 6/10: 100%|█| 340/340 [00:19<00:00, 17.72it/s, train_loss=0.0273, train_acc=1.0000, lr=6.06e-5开始验证!Epoch 6/10: 100%|██████████████████| 85/85 [00:02<00:00, 36.39it/s, val_loss=0.0084, val_acc=1.0000]结束验证!验证loss为:0.0208验证准确率为:0.9941Epoch 7/10: 100%|█| 340/340 [00:19<00:00, 17.86it/s, train_loss=0.0007, train_acc=1.0000, lr=5.58e-5开始验证!Epoch 7/10: 100%|██████████████████| 85/85 [00:02<00:00, 36.45it/s, val_loss=0.0005, val_acc=1.0000]结束验证!验证loss为:0.0148验证准确率为:0.9926Epoch 8/10: 100%|█| 340/340 [00:19<00:00, 17.84it/s, train_loss=0.0313, train_acc=1.0000, lr=5.13e-5开始验证!Epoch 8/10: 100%|██████████████████| 85/85 [00:02<00:00, 36.78it/s, val_loss=0.2206, val_acc=0.8750]结束验证!验证loss为:0.0240验证准确率为:0.9912Epoch 9/10: 100%|█| 340/340 [00:19<00:00, 17.72it/s, train_loss=0.0009, train_acc=1.0000, lr=4.72e-5开始验证!Epoch 9/10: 100%|██████████████████| 85/85 [00:02<00:00, 36.01it/s, val_loss=0.0000, val_acc=1.0000]结束验证!验证loss为:0.0276验证准确率为:0.9926Epoch 10/10: 100%|█| 340/340 [00:19<00:00, 17.75it/s, train_loss=0.0000, train_acc=1.0000, lr=4.34e-开始验证!Epoch 10/10: 100%|█████████████████| 85/85 [00:02<00:00, 36.80it/s, val_loss=0.0009, val_acc=1.0000]结束验证!验证loss为:0.0081验证准确率为:0.9971
模型评估的图形如下:
预测的结果和图形如下:
1/1 [==============================] - 0s 321ms/step1/1 [==============================] - 0s 20ms/step1/1 [==============================] - 0s 19ms/step1/1 [==============================] - 0s 18ms/step1/1 [==============================] - 0s 19ms/step1/1 [==============================] - 0s 18ms/step1/1 [==============================] - 0s 19ms/step1/1 [==============================] - 0s 19ms/step