- 🍨 本文为🔗365天深度学习训练营 中的学习记录博客
- 🍖 原作者:K同学啊
文章目录
- 一、前期工作
- 1.设置GPU(如果使用的是CPU可以忽略这步)
- 2. 导入数据
- 二、数据预处理
- 1、加载数据
- 2、再次检查数据
- 3. 配置数据集
- 4. 可视化数据
- 三、构建CNN网络
- 四、编译
- 五、训练模型
- 六、模型评估
- 七、预测
- 八、知识点
- 1、训练方式
- 2、tqdm
- 2.1、基本用法:
- 2.2、手动进度更新:
电脑环境:
语言环境:Python 3.8.0
编译器:Jupyter Notebook
深度学习环境:tensorflow 2.15.0
一、前期工作
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)
2. 导入数据
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 = "./365-7-data"
data_dir = pathlib.Path(data_dir)image_count = len(list(data_dir.glob('*/*')))print("图片总数为:",image_count)
二、数据预处理
1、加载数据
使用image_dataset_from_directory方法将磁盘中的数据加载到tf.data.Dataset中。
batch_size = 8
img_height = 224
img_width = 224"""
关于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)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)
我们可以通过class_names输出数据集的标签。标签将按字母顺序对应于目录名称。
class_names = train_ds.class_names
print(class_names)
输出:
[‘cat’, ‘dog’]
2、再次检查数据
for image_batch, labels_batch in train_ds:print(image_batch.shape)print(labels_batch.shape)break
输出:
(8, 224, 224, 3)
(8,)
3. 配置数据集
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)
4. 可视化数据
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")
三、构建CNN网络
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.compile(optimizer="adam",loss ='sparse_categorical_crossentropy',metrics =['accuracy'])
五、训练模型
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: 100%|████████| 340/340 [01:53<00:00, 2.99it/s, loss=0.8901, accuracy=0.1250, lr=9.2e-5]
开始验证!
Epoch 1/10: 100%|█████████████████████| 85/85 [00:03<00:00, 23.67it/s, loss=0.6123, accuracy=0.6250]
结束验证!
验证loss为:0.6123
验证准确率为:0.6250
Epoch 2/10: 100%|███████| 340/340 [00:22<00:00, 15.12it/s, loss=0.1449, accuracy=1.0000, lr=8.46e-5]
开始验证!
Epoch 2/10: 100%|█████████████████████| 85/85 [00:03<00:00, 25.99it/s, loss=0.2008, accuracy=0.8750]
结束验证!
验证loss为:0.2008
验证准确率为:0.8750
Epoch 3/10: 100%|███████| 340/340 [00:22<00:00, 15.23it/s, loss=0.0083, accuracy=1.0000, lr=7.79e-5]
开始验证!
Epoch 3/10: 100%|█████████████████████| 85/85 [00:03<00:00, 25.47it/s, loss=0.0298, accuracy=1.0000]
结束验证!
验证loss为:0.0298
验证准确率为:1.0000
Epoch 4/10: 100%|███████| 340/340 [00:22<00:00, 14.86it/s, loss=0.0321, accuracy=1.0000, lr=7.16e-5]
开始验证!
Epoch 4/10: 100%|█████████████████████| 85/85 [00:03<00:00, 25.84it/s, loss=0.0092, accuracy=1.0000]
结束验证!
验证loss为:0.0092
验证准确率为:1.0000
Epoch 5/10: 100%|███████| 340/340 [00:22<00:00, 15.03it/s, loss=0.3167, accuracy=0.8750, lr=6.59e-5]
开始验证!
Epoch 5/10: 100%|█████████████████████| 85/85 [00:03<00:00, 26.73it/s, loss=0.0381, accuracy=1.0000]
结束验证!
验证loss为:0.0381
验证准确率为:1.0000
Epoch 6/10: 100%|███████| 340/340 [00:22<00:00, 15.38it/s, loss=0.0323, accuracy=1.0000, lr=6.06e-5]
开始验证!
Epoch 6/10: 100%|█████████████████████| 85/85 [00:03<00:00, 25.85it/s, loss=0.0002, accuracy=1.0000]
结束验证!
验证loss为:0.0002
验证准确率为:1.0000
Epoch 7/10: 100%|███████| 340/340 [00:22<00:00, 15.04it/s, loss=0.0005, accuracy=1.0000, lr=5.58e-5]
开始验证!
Epoch 7/10: 100%|█████████████████████| 85/85 [00:03<00:00, 26.34it/s, loss=0.0040, accuracy=1.0000]
结束验证!
验证loss为:0.0040
验证准确率为:1.0000
Epoch 8/10: 100%|███████| 340/340 [00:21<00:00, 15.47it/s, loss=0.0018, accuracy=1.0000, lr=5.13e-5]
开始验证!
Epoch 8/10: 100%|█████████████████████| 85/85 [00:03<00:00, 26.12it/s, loss=0.0171, accuracy=1.0000]
结束验证!
验证loss为:0.0171
验证准确率为:1.0000
Epoch 9/10: 100%|███████| 340/340 [00:22<00:00, 15.38it/s, loss=0.0000, accuracy=1.0000, lr=4.72e-5]
开始验证!
Epoch 9/10: 100%|█████████████████████| 85/85 [00:03<00:00, 26.08it/s, loss=0.0009, accuracy=1.0000]
结束验证!
验证loss为:0.0009
验证准确率为:1.0000
Epoch 10/10: 100%|██████| 340/340 [00:21<00:00, 15.49it/s, loss=0.0050, accuracy=1.0000, lr=4.34e-5]
开始验证!
Epoch 10/10: 100%|████████████████████| 85/85 [00:03<00:00, 26.46it/s, loss=0.0001, accuracy=1.0000]
结束验证!
验证loss为:0.0001
验证准确率为:1.0000
六、模型评估
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# 采用加载的模型(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 247ms/step
1/1 [==============================] - 0s 19ms/step
1/1 [==============================] - 0s 21ms/step
1/1 [==============================] - 0s 23ms/step
1/1 [==============================] - 0s 20ms/step
1/1 [==============================] - 0s 21ms/step
1/1 [==============================] - 0s 22ms/step
1/1 [==============================] - 0s 19ms/step
八、知识点
1、训练方式
这是我们之前的训练方法。
history = model.fit(train_ds,validation_data=val_ds,epochs=epochs
)
本次使用的训练函数是model.train_on_batch
。
函数原型:
Model.train_on_batch(x, y=None, sample_weight=None, class_weight=None, return_dict=False)
- sample_weight:与x长度相同的可选数组,包含适用于每个样本的模型损失的权重。在时态数据的情况下,您可以传递一个具有形状(samples, sequence_length)的2D数组,以便对每个样本的每个时间步应用不同的权重。
- class_weight:可选的字典。将类索引(整数)映射到权值(浮点数),以应用于训练期间该类样本的模型损失。这对于告诉模型“更多地关注”来自代表性不足的类的样本是有用的。
- return_dict:如果为True,则损失和度量结果将作为字典返回,其中每个键是度量的名称。如果为False,它们将作为列表返回。
2、tqdm
tqdm是一个用于在终端中显示进度条的Python库。它提供了一种简单的方式来跟踪迭代过程的进度,无论是在循环中处理大量数据还是在长时间运行的任务中。
2.1、基本用法:
- 在for循环中使用:
from tqdm import tqdm
import timefor i in tqdm(range(10)):time.sleep(1)# 模拟任务执行时间
100%|██████████| 10/10 [00:10<00:00, 1.00s/it]
- 自定义进度条样式
desc:设置进度条的前缀文本;ncols:设置进度条的长度
from tqdm import tqdm
import time
for i in tqdm(range(10), desc="Processing", ncols=80):time.sleep(0.5)
Processing: 100%|███████████████████████████████| 10/10 [00:05<00:00, 1.99it/s]
2.2、手动进度更新:
tqdm可以手动更新,将其对象赋给一个变量,然后调用.update(N)方法来更新进度,tqdm()有个可选的参数设置迭代总数,然后通过update方法进行累加,每次执行update都会打印一次当前进度。
示例:新建一个tqdm实例,total=100表示迭代总数为100
percent = tqdm(total=100)
输出:
0%| | 0/100 [00:03<?, ?it/s]
调用update(N)方法,表示完成N次迭代,进度条则会显示对应的百分比
percent.update(1)
输出:
1%| | 1/100 [00:47<1:18:17, 47.45s/it]
再次调用会进行累加:
percent.update(90)
输出:
91%|█████████ | 91/100 [01:35<00:08, 1.12it/s]