目标:
- 自制数据集,解决本领域应用
- 数据增强,扩充数据集
- 断点续训,存取模型
- 参数提取,把参数存入文本
- acc/loss可视化,查看训练效果
- 应用程序,给图识物
1、自制数据集
# 我们的目标是把图片路径和标签文件输入generateds函数
# 由该函数返回输入特征和标签
def generateds(图片路径, 标签文件)
在自制本地数据集之前,先观察数据集的结构。

由上图,第一列value[0]用于索引到每张图片,value[1]这一列就是每张图片对应的标签。
代码实现:
def generateds(path, txt):
# 以只读形式打开txt文件
f = open(txt, 'r')
# 读取文件中所有行
contents = f.readlines()
f.close()
x, y_ = [], []
# 逐行读出
for content in contents:
# 以空格分开,图片名为value[0],图片标签为value[1]
value = content.split()
# 图片路径+图片名拼接出图片的索引路径
img_path = path + value[0]
# 读入图片
img = Image.open(img_path)
# 图片变为8位宽度的灰度值的np.array格式
img = np.array(img.convert('L'))
# 数据归一化
img = img / 255.
# 归一化后的数据贴到列表x
x.append(img)
# 标签贴到列表y
y_.append(value[1])
# 打印状态提示
print('loading:' + content)
# 变为np.array格式
x = np.array(x)
# 变为np.array格式
y_ = np.array(y_)
y_ = y_.astype(np.int64)
return x, y_
import tensorflow as tf
from PIL import Image
import numpy as np
import os
train_path = './mnist_image_label/mnist_train_jpg_60000/'
train_txt = './mnist_image_label/mnist_train_jpg_60000.txt'
# 训练集输入特征存储文件,训练集标签存储文件
x_train_savepath = './mnist_image_label/mnist_x_train.npy'
y_train_savepath = './mnist_image_label/mnist_y_train.npy'
test_path = './mnist_image_label/mnist_test_jpg_10000/'
test_txt = './mnist_image_label/mnist_test_jpg_10000.txt'
x_test_savepath = './mnist_image_label/mnist_x_test.npy'
y_test_savepath = './mnist_image_label/mnist_y_test.npy'
def generateds(path, txt):
f = open(txt, 'r') # 以只读形式打开txt文件
contents = f.readlines() # 读取文件中所有行
f.close() # 关闭txt文件
x, y_ = [], [] # 建立空列表
for content in contents: # 逐行取出
value = 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))
# 不存在则调用generateds函数创建,并分别给x_train, y_train x_test, y_test赋值
else:
print('-------------Generate Datasets-----------------')
x_train, y_train = generateds(train_path, train_txt)
x_test, y_test = generateds(test_path, test_txt)
print('-------------Save Datasets-----------------')
x_train_save = np.reshape(x_train, (len(x_train), -1))
x_test_save = np.reshape(x_test, (len(x_test), -1))
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)
model = tf.keras.models.Sequential([
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(128, activation='relu'),
tf.keras.layers.Dense(10, activation='softmax')
])
model.compile(optimizer='adam',
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=False),
metrics=['sparse_categorical_accuracy'])
model.fit(x_train, y_train, batch_size=32, epochs=5, validation_data=(x_test, y_test), validation_freq=1)
model.summary()

第一次运行路径中没有npy数据集,创建数据集

2、数据增强
数据增强可以帮助拓展数据集,对图像的增强就是对图像的简单形变,用来因对拍照角度不同引起的图片变形。
TensorFlow2给出了数据增强函数:
image_gen_train = tf.keras.preprocessing.image.ImageDataGenerator(
rescale = 所有数据集将乘以该数值,
rotation_range = 随机旋转角度数范围,
width_shift_range = 随机宽度偏移量,
height_shift_range = 随机高度偏移量,
水平翻转:horizontal_flip = 是否随机水平翻转,
随机缩放:zoom_range = 随机缩放的范围[1-n, 1+n]
)
# 这个fit里面只接受四维数据
image_gen_train.fit(x_train)
# model.fit里同步升级为.flow,将x_train, y_train以batch打包
model.fit(image_gen_train.flow(x_train, y_train, batch_size=32), ...)
例:
# 给数据增加一个维度,从(60000, 28, 28)reshape为(60000, 28, 28, 1)
x_train = x_train.reshape(x_train.shape[0], 28, 28, 1)
image_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%
)
image_gen_train.fit(x_train)
model.fit(image_gen_train.flow(x_train, y_train, batch_size=32),
epochs=5,
validation_data=(x_test, y_test),
validation_freq=1)
3、断点续训
断点续训可以存取模型。
读取模型:
load_weights(路径文件名)
# 定义出文件存放的路径和文件名.ckpt
checkpoint_save_path = "./checkpoint/mnist.ckpt"
# 在生成ckpt文件时会同步生成索引表,所以可以通过判断是否有索引,就知道是不是已经保存过模型参数
if os.path.exists(checkpoint_save_path + '.index'):
print('-------------load the model-----------------')
# 若有索引表,则调用load_weights读取模型参数
model.load_weights(checkpoint_save_path)
保存模型:
tf.keras.callbacks.ModelCheckpoint(
filepath=路径文件名,
# 是否只保留模型参数
save_weights_only=True/False,
# 是否只保留最右结果
save_best_only=True/False)
# 在fit中加入回调选项,返回给history
history = model.fit(callbacks=[cp_callback])
例:
cp_callback = tf.keras.callbacks.ModelCheckpoint(filepath=checkpoint_save_path,
save_weights_only=True,
save_best_only=True)
history = model.fit(x_train, y_train, batch_size=32, epochs=5, validation_data=(x_test, y_test),
validation_freq=1,
callbacks=[cp_callback])
完整代码:
import tensorflow as tf
import os
mnist = tf.keras.datasets.mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0
model = tf.keras.models.Sequential([
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(128, activation='relu'),
tf.keras.layers.Dense(10, activation='softmax')
])
model.compile(optimizer='adam',
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=False),
metrics=['sparse_categorical_accuracy'])
checkpoint_save_path = "./checkpoint/mnist.ckpt"
if os.path.exists(checkpoint_save_path + '.index'):
print('-------------load the model-----------------')
model.load_weights(checkpoint_save_path)
cp_callback = tf.keras.callbacks.ModelCheckpoint(filepath=checkpoint_save_path,
save_weights_only=True,
save_best_only=True)
history = model.fit(x_train, y_train, batch_size=32, epochs=5, validation_data=(x_test, y_test), validation_freq=1,
callbacks=[cp_callback])
model.summary()
保存模型之后再次运行会提升准确率。
4、参数提取
把参数存入文本
提取可训练参数:
# 返回模型中可训练的参数
model.trainable_variables
设置print输出格式:
np.set_printoptions(threshold=超过多少省略显示) # np.inf表示无限大
np.set_printoptions(threshold=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()
5、acc和loss可视化
在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']
画图代码
# 将图像分为一行两列,这一段画出第一列
plt.subplot(1, 2, 1)
# 画出acc和val_acc数据,设置出标题,画出图例
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()
在断点续训的基础上加上画图
import tensorflow as tf
import os
import numpy as np
from matplotlib import pyplot as plt
np.set_printoptions(threshold=np.inf)
mnist = tf.keras.datasets.mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0
model = tf.keras.models.Sequential([
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(128, activation='relu'),
tf.keras.layers.Dense(10, activation='softmax')
])
model.compile(optimizer='adam',
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=False),
metrics=['sparse_categorical_accuracy'])
checkpoint_save_path = "./checkpoint/mnist.ckpt"
if os.path.exists(checkpoint_save_path + '.index'):
print('-------------load the model-----------------')
model.load_weights(checkpoint_save_path)
cp_callback = tf.keras.callbacks.ModelCheckpoint(filepath=checkpoint_save_path,
save_weights_only=True,
save_best_only=True)
history = model.fit(x_train, y_train, batch_size=32, epochs=5, validation_data=(x_test, y_test), validation_freq=1,
callbacks=[cp_callback])
model.summary()
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()
############################################### show ###############################################
# 显示训练集和验证集的acc和loss曲线
acc = history.history['sparse_categorical_accuracy']
val_acc = history.history['val_sparse_categorical_accuracy']
loss = history.history['loss']
val_loss = history.history['val_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()
6、应用程序,给图识物
这里希望输入一张手写照片,神经网络能输别出数字结果
TensorFlow给出了predict函数,它可以根据输入特征给出预测结果。
predict(输入特征, batch_size = 整数) # 返回前向传播计算结果
第一步:复现模型
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)
图片识别:
from PIL import Image
import numpy as np
import tensorflow as tf
model_save_path = './checkpoint/mnist.ckpt'
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)
preNum = int(input("input the number of test pictures:"))
for i in range(preNum):
image_path = input("the path of test picture:")
img = Image.open(image_path)
img = img.resize((28, 28), Image.ANTIALIAS)
img_arr = np.array(img.convert('L'))
# 把图片变为只有黑色和白色的高对比度图片
for i in range(28):
for j in range(28):
if img_arr[i][j] < 200:
img_arr[i][j] = 255
else:
img_arr[i][j] = 0
img_arr = img_arr / 255.0
# 增加一个维度
x_predict = img_arr[tf.newaxis, ...]
result = model.predict(x_predict)
pred = tf.argmax(result, axis=1)
print('\n')
tf.print(pred)
本文介绍了深度学习中关键的预处理步骤,包括自制数据集、数据增强、断点续训和参数提取。通过实例展示了如何使用TensorFlow进行数据增强以扩充数据集,利用断点续训保存和加载模型,以及如何将模型参数保存到文本文件。此外,还讨论了训练过程中的acc和loss可视化,并提供了应用程序示例,演示如何对手写数字图像进行识别。
4300

被折叠的 条评论
为什么被折叠?



