保存训练参数,并再下一次训练时直接使用
1、保存模型:
下面展示一些 内联代码片
。
cp_callback = tf.keras.callbacks.ModelCheckpoint(filepath=checkpoint_save_path,
save_weights_only=True,
save_best_only=True) # 加入回调函数,返回给callback
history = model.fit(x_train,y_train,batch_size=32,epochs=5,validation_data=(x_test,y_test),validation_freq=1,
callbacks=[cp_callback]) # 训练时加入callbacks参数,将callback赋值给history
2、读取模型(load.weight(路径文件名))
checkpoint_save_path = './checkpoint/mnist.ckpt' # 确定文件存储路径
if os.path.exists(checkpoint_save_path + '.index'): # 若查询到和参数文件同步生成的index文件则直接读取
print('_______________load the model________________')
model.load_weights(checkpoint_save_path)
提取可训练参数
两种方式,第一种,通过修改print的打印方式直接打印。第二种,通过将参数存入txt文本文档
1、直接打印
np.set_printoptions(threshold=np.inf)
print(model.trainable_variables)
2、存入文本
file = open('./weights.txt','w') # 存入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,查看训练效果
其实,在model.fit过程种已经同步记录了,训练集/测试集loss,训练集/测试集准确率。
# 若存在history = model.fit()
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) # 将图像分为1行2列,第一列
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) # 将图像分为1行2列,第二列
plt.plot(loss,label = 'Training Loss')
plt.plot(val_loss,label = 'Validation Loss')
plt.title('Training and Validation Loss')
plt.legend() # 画出图例
plt.show()
给图实物(练习)
前向传播执行应用
predict(输入特征,batch_size = 整数)
1、复现模型(前向传播)
model = tf,keras.model.Sequential([
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(128,activation='relu'),
tf.keras.layers.Dense(10,activation='softmax')
])
2、加载参数
model.load_weights(model_save_path)
3、预测结果
result = model.perdict(x_predict)