说明:这篇文章来自 2020-2021 年的 WordPress 备份。原始图片附件未随 XML 一起保存,旧服务器图片地址也已失效,因此这里保留正文并移除了失效图片。
baseline
在baseline基础上扩展
import tensorflow as tfmnist = 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’])
model.fit(x_train, y_train, batch_size=32, epochs=5, validation_data=(x_test, y_test), validation_freq=1) model.summary()
一 自制数据集,解决本领域应用
MNIST数据集shape: x_train.shape:(60000, 28, 28) y_train.shape:(60000,) x_test.shape:(10000, 28, 28) y_test.shape:(10000,) 文件中数据格式:第一列是图片名,用来索引图片,第二列是标签值
通过本地数据自制数据库:
import tensorflow as tf from PIL import Image import numpy as np import ostrain_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)) 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()
二 数据增强,扩充数据集
数据增强(增大数据量)函数:
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] )
image_gen_train.fit(x_train)
这里fit函数需要输入一个四维数据,所以要对x_train做reshape,同时里面的参数变化如下:
model.fit(x_train, y_train,batch_size=32, ……)
变为
model.fit(image_gen_train.flow(x_train, y_train,batch_size=32), ……)
三 断点续训,存取模型
- 读取模型:
load_weights(路径文件名)
代码:
checkpoint_save_path = "./checkpoint/mnist.ckpt" #定义存放模型路径 if os.path.exists(checkpoint_save_path + '.index'): #生成ckpt文件时会同步生成索引表,所以通过索引表可以知道是否保存过模型参数 print('-------------load the model-----------------') model.load_weights(checkpoint_save_path) #读取模型参数 - 保存模型
保存模型可以使用tf的回调参数直接保存训练出来的模型参数:
tf.keras.callbacks.ModelCheckpoint( filepath=路径文件名, save_weights_only=True/False, #是否只保留模型参数 save_best_only=True/False) #是否只保留最优结果 history = model.fit( callbacks=[cp_callback] )#fit中需要加入回调选项
代码:
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])
第一次运行之后能发现路径中有保存下来的checkpoint文件夹模型参数,再次运行能发现模型准确率是基于保存的模型参数的基础上继续提升的。
四 参数提取,把参数存入文本
提取可训练参数
model.trainable_variables 返回模型中可训练的参数
要想看到这些参数,可用print打印,用set_printoptions设置print的打印效果
np.set_printoptions(threshold=超过多少省略显示)
np.set_printoptions(threshold=np.inf) # 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()
最后输出的参数:
五 acc/loss可视化,查看训练效果
在fit执行训练过程中,同步记录了训练集loss、测试集los是、训练集准确率、测试集准确率。可以用history.history提取出来
history=model.fit(训练集数据, 训练集标签, batch_size=
, epochs=,
validation_split=用作测试数据的比例,validation_data=测试集,
validation_freq=测试频率)
history: 训练集loss: loss 测试集loss: val_loss 训练集准确率: sparse_categorical_accuracy 测试集准确率: val_sparse_categorical_accuracy
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.plot画出以上四个数据的曲线:
六 应用程序,给图识物
前向传播执行应用 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) #resize成标准尺寸
img_arr = np.array(img.convert('L')) #转化为灰度图
#数据预处理
img_arr = 255 - img_arr #训练数据黑底白字,预测数据白底黑字,所以要处理像素点颜色取反,255纯白,0纯黑
# for i in range(28):
# for j in range(28):
# if img_arr[i][j] < 200: #另一种数据预处理,将灰度值小于200的像素点变白色
# img_arr[i][j] = 255 #能在保留图片的有效信息过滤图片噪声
# else:
# img_arr[i][j] = 0
#归一化
img_arr = img_arr / 255.0
print("img_arr:",img_arr.shape)
x_predict = img_arr[tf.newaxis, ...] #img_arr:(28,28)——>x_predicy:(1,28,28)
print("x_predict:",x_predict.shape)
result = model.predict(x_predict)
pred = tf.argmax(result, axis=1)
print('\n')
tf.print(pred)</code></pre>