将下面代码改为用checkpoint保存saver=tf.train.Saver() # 训练或预测 train = False # 模型文件路径 model_path = "model" if train: print("训练模式") # 训练初始化参数 # 定义输入和Label以填充容器 训练时dropout为0.25 train_feed_dict = { xs: x_train, ys: y_train, drop: 0.25 } # 训练学习1000次 for step in range(1000): with tf.GradientTape() as tape: logits_val = logits(train_feed_dict) loss_val = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=tf.one_hot(y_train, num_classes), logits=logits_val)) grads = tape.gradient(loss_val, logits.trainable_variables) optimizer.apply_gradients(zip(grads, logits.trainable_variables)) if step % 50 == 0: #每隔50次输出一次结果 print("step = {}\t mean loss = {}".format(step, loss_val)) # 保存模型 saver.save(logits, model_path) print("训练结束,保存模型到{}".format(model_path)) else: print("测试模式") # 测试载入参数 logits=tf.keras.models.load_model(model_path) print("从{}载入模型".format(model_path))
时间: 2024-04-03 14:36:28 浏览: 77
TensorFlow入门使用 tf.train.Saver()保存模型
5星 · 资源好评率100%
# 首先需要在计算图中定义一个变量来保存模型的全局步数
global_step = tf.Variable(0, dtype=tf.int32, trainable=False, name='global_step')
# 在训练过程中需要增加global_step
train_op = optimizer.apply_gradients(zip(grads, logits.trainable_variables), global_step=global_step)
# 在定义saver时,指定要保存的变量和保存路径,注意不要在文件名中包含global_step变量
saver = tf.train.Saver(var_list=logits.trainable_variables, max_to_keep=3) # 最多保存3个模型
with tf.Session() as sess:
if train:
print("训练模式")
# 恢复之前训练好的模型
latest_checkpoint = tf.train.latest_checkpoint(model_path)
if latest_checkpoint:
print("从{}载入模型".format(latest_checkpoint))
saver.restore(sess, latest_checkpoint)
else:
sess.run(tf.global_variables_initializer())
# 训练学习1000次
for step in range(1000):
_, loss_val, global_step_val = sess.run([train_op, loss, global_step], feed_dict=train_feed_dict)
if step % 50 == 0:
print("step = {}\t mean loss = {}".format(global_step_val, loss_val))
# 每隔100步保存一次模型
if global_step_val % 100 == 0:
saver.save(sess, model_path + "/model", global_step=global_step_val)
print("保存模型到{}-{}".format(model_path, global_step_val))
else:
print("测试模式")
# 载入最新的模型
latest_checkpoint = tf.train.latest_checkpoint(model_path)
if latest_checkpoint:
print("从{}载入模型".format(latest_checkpoint))
saver.restore(sess, latest_checkpoint)
else:
print("没有找到模型文件")
exit()
# 进行预测
阅读全文