(听完北大曹健老师的课,特此复习)
一、本节课的知识点
- 自制数据集,解决本领域应用
- 数据增强,扩充数据集
- 断点续训,存取模型
- 参数提取,把参数存入文本
- acc/loss可视化,查看训练效果
- 应用程序,给图识物
二、自制数据集
先回顾一下MNIST数据集的特点以及一些使用方法:
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] # 拼出图片路径和文件名
#这里注意一定要把path加上,错了好久都没找到
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)) #np.reshape(需要处理的数据,新的格式)
x_test_save = np.reshape(x_test, (len(x_test), -1))
np.save(x_train_savepath, x_train_save) #np.save(file,arr),file是将数据保存到的文件或文件名,arr是要保存的数据
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()
三、数据增强,扩充数据集
这里要用到ImageDataGenerator类,简介:
该类以及一些图像预处理的介绍
以下为引用该博客的解释
简单来说就是:ImageDataGenerator()是keras.preprocessing.image模块中的图片生成器,可以每一次给模型“喂”一个batch_size大小的样本数据,同时也可以在每一个批次中对这batch_size个样本数据进行增强,扩充数据集大小,增强模型的泛化能力。比如进行旋转,变形,归一化等等。
import tensorflow as tf
from tensorflow.keras.preprocessing.image import ImageDataGenerator
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
x_train = x_train.reshape(x_train.shape[0], 28, 28, 1) # 给数据增加一个维度,从(60000, 28, 28)reshape为(60000, 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) #这里的fit要输入四维数据,所以要在上面将三通道的数据增加一个单通道1
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(image_gen_train.flow(x_train, y_train, batch_size=32), epochs=5, validation_data=(x_test, y_test),
validation_freq=1)
model.summary()
四、断点续训,存取模型
先定义出存放模型的路径和文件名命名为ckpt文件;
因为生成ckpt文件会自动生成索引表,所以我们判断索引表存在与否就可以判断该ckpt文件是否存在(或者说模型参数是否被保存)
ckpt文件是二进制文件,保存了所有的weights、biases、gradients等变量
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"
'''
先定义出存放模型的路径和文件名命名为ckpt文件;
因为生成ckpt文件会自动生成索引表,所以我们判断索引表存在与否就可以判断该ckpt文件是否存在(或者说魔心参数是否被保存)
'''
if os.path.exists(checkpoint_save_path + '.index'):
print('-------------load the model-----------------')
model.load_weights(checkpoint_save_path) #load_weights函数调用模型参数文件
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])
#记录训练数据到history对象中,自动开启,并通过model.fit()方法返回
model.summary()
五、参数提取,把参数存入文本
import tensorflow as tf
import os
import numpy as np
np.set_printoptions(threshold=np.inf) #设置print的输出格式,threshold代表阈值为无限大,表示用print打印时不会用省略号代替
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') #如果说这个weight.txt文件不存在的话,就会自动生成一个文件
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训练后的模型返回给history对象,对该对象进行操作。
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()
返回的结果:
七、应用程序,给图识物
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'))
img_arr = 255 - img_arr
#这里我们准备的图片是白底黑字,但是模型适应的是黑底白字
#我们用255减去灰度图中的每一个像素点的值,相当于将之变为黑底白字
#或者用下面的方法,将白色的像素点(大于200的像素点)全部变成黑色(0像素)
#将黑色的像素点(小于200的像素点)全部变成白色(255像素)
# 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
print("img_arr:",img_arr.shape)
x_predict = img_arr[tf.newaxis, ...]
print("x_predict:",x_predict.shape)
result = model.predict(x_predict)
pred = tf.argmax(result, axis=1)
print('\n')
tf.print(pred)
img.convert
image = image.convert() 是图像实例对象的一个方法,接受一个 mode 参数,用以指定一种色彩模式
PIL有九种不同模式:
1: 1位像素,黑白,每字节一个像素存储
L: 8位像素,黑白
P: 8位像素,使用调色板映射到任何其他模式
RGB: 3x8位像素,真彩色
RGBA: 4x8位像素,带透明度掩模的真彩色
CMYK: 4x8位像素,分色
YCbCr: 3x8位像素,彩色视频格式
I: 32位有符号整数像素
F: 32位浮点像素
(引用Exler_yz的博客)
[Python] - 图像处理 ------ img.convert()
tf.newaxis给张量增加维度。
这是为了解决当我们使用predict函数用模型预测结果时,把数据喂入模型时维度不匹配的问题。因为我们在建模的时候通常是按照batch_size的为一批穿入模型的,所以比我们用predict的数据本身的维度要多一维。所以要增加一个维度。
tensorflow加载数据类型tf.newaxis的使用以及例子