TensorFlow 2.0 搭建神经网络(扩展)
以下内容主要用于完善上节六步法搭建神经网络的功能,
- import
- train, test <数据增强>
- model = tf.keras.models.Sequential
- model.compile
- model.fit <断点续训>
- model.summary <参数提取,acc/loss 可视化>
- <前向推理实现应用>
1 数据增强 (增大数据量)
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)
mnist 数据集示例:
import tensorflow as tf 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) # 给数据增加一个维度,使数据和网络结构匹配 x_test = x_test.reshape(x_test.shape[0], 28, 28, 1) image_gen_train = tf.keras.preprocessing.image.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(input_shape=(28, 28, 1)), tf.keras.layers.Dense(128, activation=tf.keras.activations.relu), tf.keras.layers.Dense(10, activation=tf.keras.activations.softmax) ]) model.compile(optimizer=tf.keras.optimizers.Adam(), loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=False), metrics=[tf.keras.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()
2 断点续训,存取模型
保存模型:借助 tensorflow 给出的回调函数,直接保存参数和网络。
tf.keras.callbacks.ModelCheckpoint( filepath=路径文件名, save_weights_only=True, monitor='val_loss', # val_loss or loss 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])
注:monitor 配合 save_best_only 可以保存最优模型,包括训练损失最小模型、测试损失最小模型、训练准确率最高模型、测试准确率最高模型等。
读取模型:
checkpoint_save_path = './checkpoint/mnist.ckpt' if os.path.exists(checkpoint_save_path + '.index'): print('----------load the model----------') model.load_weights(checkpoint_save_path)
示例:
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(input_shape=(28, 28)), tf.keras.layers.Dense(128, activation=tf.keras.activations.relu), tf.keras.layers.Dense(10, activation=tf.keras.activations.softmax) ]) model.compile(optimizer=tf.keras.optimizers.Adam(), loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=False), metrics=[tf.keras.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, monitor='val_loss', 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()
3 参数提取,写入文本
np.set_printoptions(threshold=np.inf) # 超过多少省略显示,np.inf表示无限大 print(model.trainable_variables) # 模型中可训练的参数 file = open('./weigths.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 acc/loss 可视化
history = model.fit()
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'] # show plt.figure(figsize=(8, 8)) 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()
5 实现给图识物的应用程序
输入一张手写数字图片,输出识别值:
import tensorflow as tf import os import numpy as np from PIL import Image from matplotlib import pyplot as plt model = tf.keras.models.Sequential([ tf.keras.layers.Flatten(), tf.keras.layers.Dense(128, activation=tf.keras.activations.relu), tf.keras.layers.Dense(10, activation=tf.keras.activations.softmax) ]) checkpoint_save_path = './checkpoint/mnist.ckpt.index' model.load_weights(checkpoint_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)