1. 自制数据集
目标:将自己的图片集和标签集转换为适合神经网络读取的多维数组
例如:
from PIL import Image
import numpy as np
import os
train_path = './fashion_image_label/fashion_train_jpg_60000/'
train_txt = './fashion_image_label/fashion_train_jpg_60000.txt'
x_train_savepath = './fashion_image_label/fashion_x_train.npy'
y_train_savepath = './fashion_image_label/fahion_y_train.npy'
test_path = './fashion_image_label/fashion_test_jpg_10000/'
test_txt = './fashion_image_label/fashion_test_jpg_10000.txt'
x_test_savepath = './fashion_image_label/fashion_x_test.npy'
y_test_savepath = './fashion_image_label/fashion_y_test.npy'
def generateds(path, txt):
f = open(txt, 'r')
contents = f.readlines()
f.close()
x, y_ = [], []
for content in contents:
value = content.split()
img_path = path + value[0]
img = Image.open(img_path)
img = np.array(img.convert('L'))
img = img / 255.
x.append(img)
y_.append(value[1])
print('loading : ' + content)
x = np.array(x)
y_ = np.array(y_)
y_ = y_.astype(np.int64)
return 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)
2. 数据增强
数据增强可以帮助扩展数据集。对图像增加,就是对图像进行简单形变,用来应对因拍照角度不同而引起的图像变形。如:
tf.keras.preprocessing.image.ImageDataGenerator(
rescale= 所以数据将乘以该数值,
rotation_range = 随机旋转角度数范围,
width_shift_range=随机宽度偏移量,
height_shift_range=随机高度偏移量,
horizontal_flip=是否随机水平旋转,
zoom_range=随机缩放的范围[1-n, 1+n]
)
例如,用之前的Minst数据集来展示数据增强的用法:
import tensorflow as tf
from tensorflow.keras.preprocessing.image import ImageDataGenerator
fashion = tf.keras.datasets.fashion_mnist
(x_train, y_train), (x_test, y_test) = fashion.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) # 给数据增加一个维度,使数据和网络结构匹配
image_gen_train = ImageDataGenerator(
rescale=1. / 1., # 如为图像,分母为255时,可归至0~1
rotation_range=45, # 随机45度旋转
width_shift_range=.15, # 宽度偏移
height_shift_range=.15, # 高度偏移
horizontal_flip=True, # 水平翻转
zoom_range=0.5 # 将图像随机缩放阈量50%
)
image_gen_train.fit(x_train)
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()
3. 断点续训,存取模型
读取模型:model.load_weights(路径文件名)
由于在生成保存模型数据的ckpt文件时会同步生成.index索引文件,所以可以根据有无相应的index文件来判断是否有已保存的模型文件
checkpoint_save_path = './checkpoint/minst.ckpt'
if os.path.exists(checkpoint_save_path + '.index'):
print("********load the model*********")
model.load_weights(checkpoint_save_path)
保存模型参数:
tf.keras.callbacks.ModelCheckpoint(
filepath=路径文件名,
save_weights_only=True/False, # 是否只保留模型参数
save_best_only=True/False # 是否只保留最优结果
)
history = model.fit(callbacks=[cp_callback]) # 训练时加入callback记录到history
完整代码:
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.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.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()
# 第一个运行会生成checkpoint文件夹;再次运行会打印“loat the model”
4. 参数提取,把参数存入文本
如何查看刚才保存的参数呢?
model.trainable_variables: 返回模型中可训练的参数
np.set_printoptions(threshold=超过多少省略显示)
print(model.trainalbel_variables)
with open('./weights.txt', "r") as f:
for v in model.trainalbel_variables:
f.write(str(v.name) + '\n')
f.write(str(v.shape) + '\n')
f.write(str(v.numpy()) + '\n')
运行结束后,会生成一个weights.txt的文件,里面内容如下(只截取了一部分):
sequential/dense/kernel:0
(784, 128)
[[-2.17313766e-02 9.63861495e-03 2.45406926e-02 -2.05611363e-02
-7.95493349e-02 7.36297593e-02 -1.00414529e-02 -2.20061354e-02
-2.01823190e-02 4.14270088e-02 1.25524700e-02 -3.86570469e-02
4.22033072e-02 2.80330330e-02 9.59490985e-03 3.71083617e-04
-2.30173916e-02 -4.57206331e-02 -5.82779385e-02 -2.92782038e-02
-6.12219647e-02 -2.66422592e-02 5.13606444e-02 -6.69592693e-02
6.71493262e-03 -1.25512704e-02 5.38410172e-02 5.32102808e-02
-2.83893384e-02 -4.53878976e-02 6.74401000e-02 -4.15585935e-03
7.46259093e-03 5.67617640e-02 9.12702084e-03 4.33859974e-02
8.93525779e-04 -2.85942480e-02 -2.26105154e-02 -1.89675465e-02
4.66749594e-02 4.78440300e-02 3.05311531e-02 -6.91696778e-02
5. acc/loss可视化
在hitsory=model.fit中,已经保留了很多信息:
- 训练集Loss: loss
- 测试集loss: val_loss
- 训练集准确率: sparse_categorical_accuracy
- 测试集准确率:val_sparse_categorical_accuracy
在之前的代码基础上加入matplotlib相关的代码即可:
import tensorflow as tf
import os
import numpy as np
import matplotlib.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.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.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)
with open("./weights.txt", "w") as f:
for v in model.trainable_variables:
f.write(str(v.name) + "\n")
f.write(str(v.shape) + "\n")
f.write(str(v.numpy()) + "\n")
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()
结果如下:
myplot.png
6. 应用程序,给图识物
那如何识别一张自己手写的图片上的数字呢?
使用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)
网友评论