深圳市南山区网站建设,国际商务网站,高端定制手机网站,网络营销指导如何做文章目录 一、前言二、前期工作1. 设置GPU#xff08;如果使用的是CPU可以忽略这步#xff09;2. 导入数据3. 查看数据 二、数据预处理1.加载数据2. 可视化数据4. 配置数据集 三、调用官方网络模型四、设置动态学习率五、编译六、训练模型七、模型评估1. Accuracy与Loss图2. … 文章目录 一、前言二、前期工作1. 设置GPU如果使用的是CPU可以忽略这步2. 导入数据3. 查看数据 二、数据预处理1.加载数据2. 可视化数据4. 配置数据集 三、调用官方网络模型四、设置动态学习率五、编译六、训练模型七、模型评估1. Accuracy与Loss图2. 混淆矩阵 八、保存and加载模型九、预测 一、前言
我的环境
语言环境Python3.6.5编译器jupyter notebook深度学习环境TensorFlow2.4.1
往期精彩内容
卷积神经网络CNN实现mnist手写数字识别 卷积神经网络CNN多种图片分类的实现卷积神经网络CNN衣服图像分类的实现卷积神经网络CNN鲜花识别卷积神经网络CNN天气识别 卷积神经网络VGG-16识别海贼王草帽一伙卷积神经网络ResNet-50鸟类识别 卷积神经网络AlexNet鸟类识别卷积神经网络(CNN)识别验证码卷积神经网络CNN车牌识别
来自专栏机器学习与深度学习算法推荐
二、前期工作
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# 设置随机种子尽可能使结果可以重现
import numpy as np
np.random.seed(1)# 设置随机种子尽可能使结果可以重现
import tensorflow as tf
tf.random.set_seed(1)import pathlibdata_dir Eye_datasetdata_dir pathlib.Path(data_dir)3. 查看数据
image_count len(list(data_dir.glob(*/*)))print(图片总数为,image_count)图片总数为 4307二、数据预处理
1.加载数据
batch_size 64
img_height 224
img_width 224使用image_dataset_from_directory方法将磁盘中的数据加载到tf.data.Dataset中
train_ds tf.keras.preprocessing.image_dataset_from_directory(data_dir,validation_split0.2,subsettraining,seed12,image_size(img_height, img_width),batch_sizebatch_size)Found 4307 files belonging to 4 classes.
Using 3446 files for training.val_ds tf.keras.preprocessing.image_dataset_from_directory(data_dir,validation_split0.2,subsetvalidation,seed12,image_size(img_height, img_width),batch_sizebatch_size)Found 4307 files belonging to 4 classes.
Using 861 files for validation.我们可以通过class_names输出数据集的标签。标签将按字母顺序对应于目录名称。
class_names train_ds.class_names
print(class_names)[close_look, forward_look, left_look, right_look]2. 可视化数据
plt.figure(figsize(10, 5)) # 图形的宽为10高为5
plt.suptitle(数据展示)for images, labels in train_ds.take(1):for i in range(8):ax plt.subplot(2, 4, i 1) ax.patch.set_facecolor(yellow)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(64, 224, 224, 3)
(64,)Image_batch是形状的张量8, 224, 224, 3)。这是一批形状240x240x3的8张图片最后一维指的是彩色通道RGB。Label_batch是形状8的张量这些标签对应8张图片
4. 配置数据集
AUTOTUNE tf.data.AUTOTUNEtrain_ds train_ds.cache().shuffle(1000).prefetch(buffer_sizeAUTOTUNE)
val_ds val_ds.cache().prefetch(buffer_sizeAUTOTUNE)三、调用官方网络模型
model tf.keras.applications.VGG16()
# 打印模型信息
model.summary()四、设置动态学习率
这里先罗列一下学习率大与学习率小的优缺点。
学习率大 优点 1、加快学习速率。 2、有助于跳出局部最优值。缺点 1、导致模型训练不收敛。 2、单单使用大学习率容易导致模型不精确。 学习率小 优点 1、有助于模型收敛、模型细化。 2、提高模型精度。缺点 1、很难跳出局部最优值。 2、收敛缓慢。
注意这里设置的动态学习率为指数衰减型ExponentialDecay。在每一个epoch开始前学习率learning_rate都将会重置为初始学习率initial_learning_rate然后再重新开始衰减。计算公式如下 learning_rate initial_learning_rate * decay_rate ^ (step / decay_steps) # 设置初始学习率
initial_learning_rate 1e-4lr_schedule tf.keras.optimizers.schedules.ExponentialDecay(initial_learning_rate, decay_steps5, # 敲黑板这里是指 steps不是指epochsdecay_rate0.96, # lr经过一次衰减就会变成 decay_rate*lrstaircaseTrue)# 将指数衰减学习率送入优化器
optimizer tf.keras.optimizers.Adam(learning_ratelr_schedule)五、编译
在准备对模型进行训练之前还需要再对其进行一些设置。以下内容是在模型的编译步骤中添加的
损失函数loss用于衡量模型在训练期间的准确率。优化器optimizer决定模型如何根据其看到的数据和自身的损失函数进行更新。指标metrics用于监控训练和测试步骤。以下示例使用了准确率即被正确分类的图像的比率。
model.compile(optimizeroptimizer,loss sparse_categorical_crossentropy,metrics [accuracy])六、训练模型
epochs 20history model.fit(train_ds,validation_dataval_ds,epochsepochs
)七、模型评估
1. Accuracy与Loss图
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, labelTraining Accuracy)
plt.plot(epochs_range, val_acc, labelValidation Accuracy)
plt.legend(loclower right)
plt.title(Training and Validation Accuracy)plt.subplot(1, 2, 2)
plt.plot(epochs_range, loss, labelTraining Loss)
plt.plot(epochs_range, val_loss, labelValidation Loss)
plt.legend(locupper right)
plt.title(Training and Validation Loss)
plt.show()2. 混淆矩阵
Seaborn 是一个画图库它基于 Matplotlib 核心库进行了更高阶的 API 封装可以让你轻松地画出更漂亮的图形。Seaborn 的漂亮主要体现在配色更加舒服、以及图形元素的样式更加细腻。
from sklearn.metrics import confusion_matrix
import seaborn as sns
import pandas as pd# 定义一个绘制混淆矩阵图的函数
def plot_cm(labels, predictions):# 生成混淆矩阵conf_numpy confusion_matrix(labels, predictions)# 将矩阵转化为 DataFrameconf_df pd.DataFrame(conf_numpy, indexclass_names ,columnsclass_names) plt.figure(figsize(8,7))sns.heatmap(conf_df, annotTrue, fmtd, cmapBuPu)plt.title(混淆矩阵,fontsize15)plt.ylabel(真实值,fontsize14)plt.xlabel(预测值,fontsize14)val_pre []
val_label []for images, labels in val_ds:#这里可以取部分验证数据.take(1)生成混淆矩阵for image, label in zip(images, labels):# 需要给图片增加一个维度img_array tf.expand_dims(image, 0) # 使用模型预测图片中的人物prediction model.predict(img_array)val_pre.append(class_names[np.argmax(prediction)])val_label.append(class_names[label])plot_cm(val_label, val_pre)八、保存and加载模型
这是最简单的模型保存与加载方法哈
# 保存模型
model.save(model/16_model.h5)# 加载模型
new_model tf.keras.models.load_model(model/16_model.h5)九、预测
九、预测
# 采用加载的模型new_model来看预测结果plt.figure(figsize(10, 5)) # 图形的宽为10高为5
plt.suptitle(预测结果展示)for images, labels in val_ds.take(1):for i in range(8):ax plt.subplot(2, 4, i 1) # 显示图片plt.imshow(images[i].numpy().astype(uint8))# 需要给图片增加一个维度img_array tf.expand_dims(images[i], 0) # 使用模型预测图片中的人物predictions new_model.predict(img_array)plt.title(class_names[np.argmax(predictions)])plt.axis(off)