①自制數(shù)據(jù)集,解決本領(lǐng)域應(yīng)用
②數(shù)據(jù)增強(qiáng),擴(kuò)充數(shù)據(jù)集
③斷點(diǎn)續(xù)訓(xùn),存取模型
④參數(shù)提取,把參數(shù)存入文本
⑤acc/loss可視化,查看訓(xùn)練效果
⑥應(yīng)用程序,給圖識物
數(shù)據(jù)增強(qiáng)
image_gen_train = tf.keras.preprocessing.image.ImageDataGenerator(
rescale = 所有數(shù)據(jù)將乘以該數(shù)值
rotation_range = 隨機(jī)旋轉(zhuǎn)角度數(shù)范圍
width_shift_range = 隨機(jī)寬度偏移量
height_shift_range = 隨機(jī)高度偏移量
水平翻轉(zhuǎn):horizontal_flip = 是否隨機(jī)水平翻轉(zhuǎn)
隨機(jī)縮放:zoom_range = 隨機(jī)縮放的范圍 [1-n,1+n] )
例:
數(shù)據(jù)增強(qiáng)(增大數(shù)據(jù)量)
11
image_gen_train = ImageDataGenerator(
rescale=1. / 1., # 如為圖像,分母為255時,可歸至0~1
rotation_range=45, # 隨機(jī)45度旋轉(zhuǎn)
width_shift_range=.15, # 寬度偏移
height_shift_range=.15, # 高度偏移
horizontal_flip=False, # 水平翻轉(zhuǎn)
zoom_range=0.5 # 將圖像隨機(jī)縮放閾量50%)
image_gen_train.fit(x_train)
image_gen_train.fit(x_t
實現(xiàn)對訓(xùn)練數(shù)據(jù)的增強(qiáng)
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) # 給數(shù)據(jù)增加一個維度,使數(shù)據(jù)和網(wǎng)絡(luò)結(jié)構(gòu)匹配
image_gen_train = ImageDataGenerator(
rescale=1. / 1., # 如為圖像,分母為255時,可歸至0~1
rotation_range=45, # 隨機(jī)45度旋轉(zhuǎn)
width_shift_range=.15, # 寬度偏移
height_shift_range=.15, # 高度偏移
horizontal_flip=True, # 水平翻轉(zhuǎn)
zoom_range=0.5 # 將圖像隨機(jī)縮放閾量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()
讀取保存模型
load_weights(路徑文件名)
tf.keras.callbacks.ModelCheckpoint(
filepath=路徑文件名,
save_weights_only=True/False,
save_best_only=True/False)
history = model.fit( callbacks=[cp_callback] )
保存模型:

保存模型 回調(diào)函數(shù)
import tensorflow as tf
import os
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
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/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=(x_test, y_test), validation_freq=1,
callbacks=[cp_callback])
model.summary()
提取可訓(xùn)練參數(shù)
model.trainable_variables 返回模型中可訓(xùn)練的參數(shù)
設(shè)置print輸出格式
np.set_printoptions(threshold=超過多少省略顯示)
np.set_printoptions(threshold=np.inf) # 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曲線
history=model.fit(訓(xùn)練集數(shù)據(jù), 訓(xùn)練集標(biāo)簽, batch_size=, epochs=,validation_split=用作測試數(shù)據(jù)的比例,validation_data=測試集,validation_freq=測試頻率)
history:
訓(xùn)練集loss: loss
測試集loss: val_loss
訓(xùn)練集準(zhǔn)確率: sparse_categorical_accuracy
測試集準(zhǔn)確率: val_sparse_categorical_accuracy
# 顯示訓(xùn)練集和驗證集的acc和loss曲線
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=(x_test, y_test), validation_freq=1,callbacks=[cp_callback])
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') #訓(xùn)練集準(zhǔn)確率
plt.plot(val_acc, label='Validation Accuracy') #測試集準(zhǔn)確率
plt.title('Training and Validation Accuracy')
plt.legend()
plt.subplot(1, 2, 2)
plt.plot(loss, label='Training Loss') # 訓(xùn)練集 損失函數(shù)
plt.plot(val_loss, label='Validation Loss') #測試集損失函數(shù)
plt.title('Training and Validation Loss')
plt.legend()
plt.show()
predict(輸入特征, batch_size=整數(shù))
返回前向傳播計算結(jié)果
復(fù)現(xiàn)模型
model = tf.keras.models.Sequential([
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(128, activation='relu'),
tf.keras.layers.Dense(10, activation='softmax’)])
加載參數(shù)
model.load_weights(model_save_path)
預(yù)測結(jié)果
result = model.predict(x_predict)
from PIL import Image
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
type = ['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)
image = plt.imread(image_path)
plt.set_cmap('gray')
plt.imshow(image)
img=img.resize((28,28),Image.ANTIALIAS)
img_arr = np.array(img.convert('L'))
img_arr = 255 - img_arr
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)])
plt.pause(1)
plt.close()