tensorflow笔记【7】深度学习-断点续训,保存模型
文章目录- 一、断点续训,保存模型(compile后面)
- 二、参数提取,写至文本
- 1.详细代码
- 2.参数提却,写至文本的代码
- 三、准确率可视化
- 总结
`
一、断点续训,保存模型(compile后面)load_weights(l路径文件名)–告知文件存在哪里,直接读取已有模型的参数。
借助tensorflow给出的回调函数,直接保存参数和网络。
定义出存放模型的路径和文件名(.ckpt)
判断是不是已经有了索引表,知到是不是保存过模型参数
生成ckpt文件会同步生成索引表。
# -----------------------断点续训,保存模型--------------------
# 读取模型
checkpoint_save_path = 'checkpoint/checkpoint.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
)
ModelCheckpoint
keras.callbacks.ModelCheckpoint(filepath, monitor='val_loss', verbose=0, save_best_only=False, save_weights_only=False, mode='auto', period=1)
在每个训练期之后保存模型。
filepath 可以包括命名格式选项,可以由 epoch 的值和 logs 的键(由 on_epoch_end 参数传递)来填充。
例如:如果 filepath 是 weights.{epoch:02d}-{val_loss:.2f}.hdf5, 那么模型被保存的的文件名就会有训练轮数和验证损失。
**参数**
filepath: 字符串,保存模型的路径。
monitor: 被监测的数据。
verbose: 详细信息模式,0 或者 1 。
save_best_only: 如果 save_best_only=True, 被监测数据的最佳模型就不会被覆盖。
mode: {auto, min, max} 的其中之一。 如果 save_best_only=True,那么是否覆盖保存文件的决定就取决于被监测数据的最大或者最小值。 对于 val_acc,模式就会是 max,而对于 val_loss,模式就需要是 min,等等。 在 auto 模式中,方向会自动从被监测的数据的名字中判断出来。
save_weights_only: 如果 True,那么只有模型的权重会被保存 (model.save_weights(filepath)), 否则的话,整个模型会被保存 (model.save(filepath))。
period: 每个检查点之间的间隔(训练轮数)。
详细代码:
# 1.导入相关模块---import
import tensorflow as tf
from tensorflow.keras import Model
from tensorflow.keras.layers import Flatten, Dense
import os
# 2.指定数据集----(x_train,y_train),(x_test,y_test)
mnist = tf.keras.datasets.mnist
(x_train, y_train), (x_test, y_test)=mnist.load_data()
x_train, x_test = x_train/255, x_test/255
# 3.搭建网络模型---class
class MnistModel(Model):
def __init__(self):
super(MnistModel, self).__init__()
self.flatten = Flatten()
self.d1 = Dense(128, activation='relu')
self.d2 = Dense(10, activation='softmax')
def call(self, x):
x = self.flatten(x)
x = self.d1(x)
y = self.d2(x)
return y
model = MnistModel()
# 4.为网络模型配置训练方法---compile
model.compile(optimizer='adam',
loss=tf.keras.losses.sparse_categorical_crossentropy,
metrics=['sparse_categorical_accuracy']
)
# -----------------------断点续训,保存模型--------------------
# 读取模型
checkpoint_save_path = 'checkpoint/checkpoint.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
)
# 5.最优模型进行训练---fit
history = model.fit(x_train, y_train, batch_size=32, epochs=5,
validation_data=(x_test, y_test),
validation_freq=1,
callbacks=[cp_callback])
# 6.打印网络模型和参数---summary
model.summary()
二、参数提取,写至文本
在断点续训基础上,添加参数提取功能
np.set_printoptions(threshold=np.inf) # 设置打印选项,打印所有内容,threshold打印全部数组元素
print(model.trainable_variables) # 打印所有可训练参数
代码:
# 1.导入相关模块---import
import os
import tensorflow as tf
from tensorflow.keras.layers import Flatten, Dense
from tensorflow.keras import Model
import numpy as np
np.set_printoptions(threshold=np.inf) # 设置打印选项,打印所有内容
# 2.指定数据集----(train),(test)
mnist = tf.keras.datasets.mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train, x_test = x_train/255, x_test/255
# 3.搭建网络模型---class
class MnistModel(Model):
def __init__(self):
super(MnistModel, self).__init__()
self.flatten = Flatten()
self.d1 = Dense(128, activation='relu')
self.d2 = Dense(10, activation='softmax')
def call(self, x):
x = self.flatten(x)
x = self.d1(x)
y = self.d2(x)
return y
model = MnistModel()
# 4.为网络模型配置训练方法---compile
model.compile(optimizer='adam',
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=False),
metrics=['sparse_categorical_accuracy'])
# -------------------断点续训,保存模型------------------------
# 读取模型
checkpoint_save_path = './checkpoint/checkpoint.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)
# 5.网络模型传入数据集进行训练---fit
history = model.fit(x_train,y_train,batch_size=32,epochs=5,
validation_data=(x_test,y_test),
validation_freq=1,
callbacks=[cp_callback])
# 6.打印网络模型和参数---summary
model.summary()
print(model.trainable_variables) # 打印所有可训练参数
f = open('./weights.txt', 'w')
for v in model.trainable_variables:
f.write(str(v.name) + 'n')
f.write(str(v.shape) + 'n')
f.write(str(v.numpy()) + 'n')
f.close()
2.参数提却,写至文本的代码
代码如下:
print(model.trainable_variables) # 打印所有可训练参数
f = open('./weights.txt', 'w')
for v in model.trainable_variables:
f.write(str(v.name) + 'n')
f.write(str(v.shape) + 'n')
f.write(str(v.numpy()) + 'n')
f.close()
三、准确率可视化
# ----------------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.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 accuracy')
plt.legend()
plt.show()
总结
准确率提高很多。



