tensorflow2学习笔记

第四章神经网络拓展 4.1总览 对第三章对6步进行拓展
1 自制数据集,解决本领域应用
2 数据增强,扩充数据集
3 断点续训,存取模型
4 参数提取,把参数存入文本
5 acc/loss可视化,查看训练效果
6 应用程序,给图识物
4.2自制数据集 在代码中进行解释
代码实现:

import tensorflow as tf from PIL import Image import numpy as np import ostrain_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 = https://www.it610.com/article/content.split()# 以空格分开,存入数组 img_path = path + value[0] img = Image.open(img_path) img = np.array(img.convert('L'))# 图片变为np格式 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)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=https://www.it610.com/article/(x_test, y_test), validation_freq=1) model.summary()

4.3数据增强 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)
import tensorflow as tf from tensorflow.keras.preprocessing.image import ImageDataGeneratorfashion = 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.0x_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=https://www.it610.com/article/(x_test, y_test), validation_freq=1) model.summary()

4.4断点续训 读取保存模型
读取模型:
load_weights(路径文件名)
checkpoint_save_path = "./checkpoint/fashion.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] )
import tensorflow as tf import osfashion = 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.0model = 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/fashion.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=https://www.it610.com/article/(x_test, y_test), validation_freq=1, callbacks=[cp_callback]) model.summary()

4.5参数提取 查看上一节中所保存的参数
提取可训练参数
model.trainable_variables
返回模型中可训练的参数
设置print输出格式 np.set_printoptions(threshold=超过多少省略显示)
np.set_printoptions(threshold=np.inf)# 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')

4.6可视化 【tensorflow2学习笔记】acc曲线与loss曲线
history=model.fit(训练集数据, 训练集标签, batch_size=, epochs=, validation_split=用作测试数据的比例,validation_data=https://www.it610.com/article/测试集, validation_freq=测试频率)
history:
训练集loss: loss
测试集loss: val_loss
训练集准确率: sparse_categorical_accuracy
测试集准确率: val_sparse_categorical_accuracy
# 显示训练集和验证集的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()

如果使用mac出现OMP: Error #15: Initializing libiomp5.dylib, but found libiomp5.dylib already initialized.加入
import os os.environ['KMP_DUPLICATE_LIB_OK']='True'

就可以解决无法作图的问题了。
4.7给图识物 前向传播执行应用
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 tftype = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat', 'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']model_save_path = './checkpoint/fashion.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 - 各自点当前灰度值 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') print(type[int(pred)])

    推荐阅读