#|ML&DL - TensorFlow2.1快速入门学习笔记04——神经网络八股扩展
ML&DL - TensorFlow2.1快速入门学习笔记04——神经网络八股扩展
- 第四讲 神经网络八股扩展
-
- 4.1 自建数据集
- 4.2 数据增强
- 4.3 断点续训
-
- 保存模型
- 读取模型
- 4.4 参数提取
- 4.5 acc & loss 可视化
- 4.6 应用程序:给图识物
- Reference
第四讲 神经网络八股扩展 在上一讲中介绍了使用
tf.keras
搭建神经网络的 “六步法”:- import
- train, test
- model = tf.keras.models.Sequential / class
- model.compile
- model.fit
- model.summary
- 自建数据集
在之前的学习中,都是使用已经打包好的数据,使用.load_data
方法来导入训练和验证数据。
使用 自建数据集 ,如何给 (x_train, y_train), (x_test, y_test) 赋值呢?
fashion = tf.keras.datasets.fashion_mnist
(x_train, y_train), (x_test, y_test) = fashion.load_data()
- 数据增强
如果训练数据不足,模型见识不足,模型的泛化能力会较弱。针对这一问题,还需要进行 数据增强 ,来扩展数据,提高泛化力。
- 断点续训
如果每次训练都从头开始,是一件很不划算的事,所以需要引入 断点续训 ,来实时保存最优模型。
- 参数提取
神经网络训练的目的,就是获取各层网络最优的参数。只要拿到这些参数,就能够在任何平台实现前向推断,复现出模型,实现应用。所以需要进行 参数提取 ,将参数存入文本。
- acc & loss 可视化
由于tf.keras
的高度封装,是我们不能像使用TensorFlow那样进行 acc & loss 曲线绘制,所以本讲将对使用tf.keras
实现 acc & loss 可视化 进行讲解。
- 前向推理实现应用
模型训练好以后,输入神经网络一组新的/从未见过的特征,神经网络会输出预测的结果,实现学以致用。
- 本讲目标:
① 自制数据集,解决本领域应用
② 数据增强,扩充数据集
③ 断点续训,存取模型
④ 参数提取,把参数存入文本
⑤ acc/loss可视化,查看训练效果
⑥ 应用程序,给图识物
.load_data
方法来导入训练和验证数据后各数据的尺寸为:![#|ML&DL - TensorFlow2.1快速入门学习笔记04——神经网络八股扩展](https://img.it610.com/image/info8/5706ccc1389541ec8883223b28265c18.jpg)
文章图片
以自建数据集方式,编写函数,导入 (x_train, y_train), (x_test, y_test) :
def generate_datasets(path, txt):
f = open(txt, 'r')# 以只读形式打开txt文件
contents = f.readlines()# 读取文件中所有行
f.close()# 关闭txt文件
x, y_ = [], []# 建立空列表
for content in contents:# 逐行取出
value = https://www.it610.com/article/content.split()# 以空格分开,图片路径为value[0] , 标签为value[1] , 存入列表
img_path = path + value[0]# 拼出图片路径和文件名
img = Image.open(img_path)# 读入图片
img = np.array(img.convert('L'))# 图片变为8位宽灰度值的np.array格式
img = img / 255.# 数据归一化 (实现预处理)
x.append(img)# 归一化后的数据,贴到列表x
y_.append(value[1])# 标签贴到列表y_
print('loading : ' + content)# 打印状态提示x = np.array(x)# 变为np.array格式
y_ = np.array(y_)# 变为np.array格式
y_ = y_.astype(np.int64)# 变为64位整型
return x, y_# 返回输入特征x,返回标签y_
if os.path.exists(x_train_savepath) and os.path.exists(y_train_savepath) and os.path.exists(
x_test_savepath) and os.path.exists(y_test_savepath):
print('-------------Load Datasets-----------------')
x_train_save = np.load(x_train_savepath)
y_train = np.load(y_train_savepath)
x_test_save = np.load(x_test_savepath)
y_test = np.load(y_test_savepath)
x_train = np.reshape(x_train_save, (len(x_train_save), 28, 28))
x_test = np.reshape(x_test_save, (len(x_test_save), 28, 28))
else:
print('-------------Generate Datasets-----------------')
x_train, y_train = generate_datasets(train_path, train_txt)
x_test, y_test = generate_datasets(test_path, test_txt)print('-------------Save Datasets-----------------')
x_train_save = np.reshape(x_train, (len(x_train), -1))# 将x_train由60000*28*28 reshape为60000*784
x_test_save = np.reshape(x_test, (len(x_test), -1))# 将x_tset由60000*28*28 reshape为60000*784
np.save(x_train_savepath, x_train_save)
np.save(y_train_savepath, y_train)
np.save(x_test_savepath, x_test_save)
np.save(y_test_savepath, y_test)
4.2 数据增强 数据增强可以帮助扩展数据集,对图像进行数据增强就是对图像进行简单的形变。用来应对因拍照角度不同所引起的图像变形。
API:
from tensorflow.keras.preprocessing.image import ImageDataGeneratorimage_gen_train = tf.keras.preprocessing.image.ImageDataGenerator(
rescale = 所有数据(像素值)将乘以该数值
rotation_range = 随机旋转角度数范围
width_shift_range = 随机宽度偏移量
height_shift_range = 随机高度偏移量
horizontal_flip = 是否随机水平翻转
zoom_range = 随机缩放的范围 [1-n, 1+n])
image_gen_train.fit(x_train)
举个栗子:
from tensorflow.keras.preprocessing.image import ImageDataGeneratorimage_gen_train = ImageDataGenerator(
rescale=1. / 1., # 如为图像,分母为255时,可归至0~1
rotation_range=45, # 随机45度旋转
width_shift_range=.15, # 宽度偏移
height_shift_range=.15, # 高度偏移
horizontal_flip=False, # 水平翻转
zoom_range=0.5 # 将图像随机缩放阈量50%)x_train = x_train.reshape(x_train.shape[0], 28, 28, 1)# 将x_train由60000*28*28 reshape为60000*28*28*1,其中的 *1 指单通道
image_gen_train.fit(x_train)# 对x_train进行数据增强操作
因为在
image_gen_train.fit()
中需要输入四维数组,所以需要对 x_train 进行 reshape 维度变换: ( 60000 , 28 , 28 ) ? ( 60000 , 28 , 28 , 1 ) (60000, 28, 28)\Longrightarrow(60000, 28, 28, 1) (60000,28,28)?(60000,28,28,1)。model.fit()
也需要进行相应修改:注意: 此处
image_gen_train.fit()
与 model.fit()
中的 .fit()
方法不是同一个方法,分别属于 ImageDataGenerator()
与 tf.keras.models.Sequential()
。model.fit(x_train, y_train,batch_size=32, ……)
# 改为下面的形式执行训练过程: image_gen_train.flow(x_train, y_train,batch_size=32) 是以flow形式按照batch打包后执行训练过程
model.fit(image_gen_train.flow(x_train, y_train,batch_size=32), ……)
4.3 断点续训 断点续训可以存取模型(模型参数)。
保存模型
借助 tensorflow 给出的回调函数,在
fit()
中添加 callbacks=[]
参数,直接保存参数和网络。API:
# monitor 配合 save_best_only 可以保存最优模型,包括:训练损失最小模型、测试损失最小模型、训练准确率最高模型、测试准确率最高模型等。
tf.keras.callbacks.ModelCheckpoint(filepath=路径+文件名,
save_weights_only=True/False,# 是否只保留模型参数
monitor='val_loss',# val_loss or loss
save_best_only=True/False)# 是否只保留最优结果# 执行训练过程时,加入callbacks选项,记录到history中
# 之前使用 model.fit() 未记录到history中:
# model.fit(x_train, y_train, batch_size=32, epochs=5,
#validation_data=https://www.it610.com/article/(x_test, y_test),
#validation_freq=1,
#callbacks=[cp_callback])
history = model.fit(x_train, y_train, batch_size=32, epochs=5,
validation_data=(x_test, y_test),
validation_freq=1,
callbacks=[cp_callback])
读取模型
模型读取可由TensorFlow给出的
.load_weights()
函数。API:
load_weights(路径文件名)
# 保存为 .ckpt 文件,因为保存为 .ckpt 文件时会同步生成索引表,通过判断是否存在索引表 .index ,就知道是否已经保存过模型参数了。
checkpoint_save_path = "./checkpoint/mnist.ckpt"
# 如果已经有了索引表,就可以直接读取模型参数
if os.path.exists(checkpoint_save_path + '.index'):
print('-------------load the model-----------------')
model.load_weights(checkpoint_save_path)
4.4 参数提取 实现参数提取,将参数存入文本文件。
TensorFlow API:
model.trainable_variables
返回模型中可训练的参数。可以直接使用
print
输出这些参数,但是,直接print
,会有大量的数据输出用省略号替换掉。所以需要设置print()
函数的打印效果:np.set_printoptions(threshold=超过多少省略显示)
。np.set_printoptions(threshold=np.inf) # np.inf表示无限大
print(model.trainable_variables)
# 将参数写入文本文件
file = open('./weights.txt', 'w')
for v in model.trainable_variables:
file.write(str(v.name) + '\n')
file.write(str(v.shape) + '\n')
file.write(str(v.numpy()) + '\n')
file.close()
4.5 acc & loss 可视化 【#|ML&DL - TensorFlow2.1快速入门学习笔记04——神经网络八股扩展】将模型训练过程中,准确率上升,损失函数下降的过程可视化出来。
history=model.fit(训练集数据, 训练集标签, batch_size=, epochs=,
validation_split=用作测试数据的比例,
validation_data=https://www.it610.com/article/测试集,
validation_freq=测试频率)
在
model.fit()
执行训练过程时,同步记录了:- 训练集loss:loss
- 测试集loss:val_loss
- 训练集准确率:sparse_categorical_accuracy
- 测试集准确率:val_sparse_categorical_accuracy
history.history[]
提取出来。acc = history.history['sparse_categorical_accuracy']
val_acc = history.history['val_sparse_categorical_accuracy']
loss = history.history['loss']
val_loss = history.history['val_loss']
将 acc & loss 曲线绘制出来:
plt.subplot(1, 2, 1)
plt.plot(acc, label='Training Accuracy')
plt.plot(val_acc, label='Validation Accuracy')
plt.title('Training and Validation Accuracy')
plt.legend()plt.subplot(1, 2, 2)
plt.plot(loss, label='Training Loss')
plt.plot(val_loss, label='Validation Loss')
plt.title('Training and Validation Loss')
plt.legend()
plt.show()
![#|ML&DL - TensorFlow2.1快速入门学习笔记04——神经网络八股扩展](https://img.it610.com/image/info8/3213f06191064806bdfb2d56fe732c51.jpg)
文章图片
4.6 应用程序:给图识物 要让训练的神经网络模型可用,就需要编写一套应用程序,实现给图识物。
![#|ML&DL - TensorFlow2.1快速入门学习笔记04——神经网络八股扩展](https://img.it610.com/image/info8/1897069c04cb4d2aacd6ecb24324092b.jpg)
文章图片
TensorFlow给出了
predict()
函数,可以实现根据输入特征输出预测结果。在 predict()
基础上实现前向传播执行识图应用只需要三步:# 复现模型(前向传播)搭建网络框架
model = tf.keras.models.Sequential([tf.keras.layers.Flatten(),
tf.keras.layers.Dense(128, activation='relu'),
tf.keras.layers.Dense(10, activation='softmax’)])
# 加载参数
model.load_weights(model_save_path)
# 预测结果
result = model.predict(x_predict)
注意: 模型应用需要对输入待预测数据进行预处理。
- 在训练模型时使用的是28 ? 28 28*28 28?28 的灰度图。所以在应用时需要先将输入resize成28 ? 28 28*28 28?28 的标准尺寸,并转换为灰度图。
- 也可以将图片二值化输入,这样不仅保留了图片有用信息,而且滤去了背景噪声,选择合适的二值化阈值,识别效果会更好。
- 此外还需要注意,训练时使用的图片为黑底白字,所以应用时需要将白底黑字的图片转换成为黑底白字的图片,即
img_arr = 255 - img_arr
实现颜色取反。 - 神经网络训练时都是按照batch ( 32 ? 28 ? 28 32*28*28 32?28?28) 送入网络的,所以进入predict函数前要先把 img_arr 前添加一个维度。
x_predict = img_arr[tf.newaxis, ...]
Reference
推荐阅读
- JAVA(抽象类与接口的区别&重载与重写&内存泄漏)
- 宋仲基&宋慧乔(我们不公布恋情,我们直接结婚。)
- 21天|21天|M&M《见识》04
- 二叉树路径节点关键值和等于目标值(LeetCode--112&LeetCode--113)
- neo4j|neo4j cql语句 快速查询手册
- 2021—3—8日教练实践总结&呼吸练习&觉察日记
- 奇迹-妖妈|奇迹-妖妈 感恩日记46/365&非暴力沟通第3天
- 通过复盘快速成长(附模板)
- 前端|web前端dya07--ES6高级语法的转化&render&vue与webpack&export
- 数据技术|一文了解Gauss数据库(开发历程、OLTP&OLAP特点、行式&列式存储,及与Oracle和AWS对比)