发布于2019-12-07 09:28 阅读(803) 评论(0) 点赞(18) 收藏(0)
import tensorflow as tf
import os
"""
模型持久化:
含义:将当前训练好的模型图 和 权重保存到本地磁盘中,方便后续的使用。
1、服务器训练好了一个模型,迁移到 移动端使用;
2、深度学习训练都很耗时,耗钱。 可以迁移学习。
"""
def train():
with tf.Graph().as_default():
v1 = tf.get_variable(
'v1', dtype=tf.float32, shape=[1], initializer=tf.random_normal_initializer()
)
v2 = tf.get_variable(
'v2', dtype=tf.float32, shape=[1], initializer=tf.random_normal_initializer()
)
rezult = v1 + v2
# 构建持久化的对象
saver = tf.train.Saver()
# 创建持久化的文件路径
save_file = './models/ai20/model.ckpt'
dirpath = os.path.dirname(save_file)
if not os.path.exists(dirpath):
os.makedirs(dirpath)
print('成功创建文件夹:{}'.format(dirpath))
# 二、构建会话
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
print(sess.run([v1, v2, rezult]))
"""
[array([0.25989017], dtype=float32),
array([-0.12384889], dtype=float32),
array([0.13604128], dtype=float32)]
"""
# 执行持久化
saver.save(sess=sess, save_path=save_file)
print('变量成功保存至:{}'.format(save_file))
def restore_var():
with tf.Graph().as_default():
v1 = tf.get_variable(
'v1', dtype=tf.float32, shape=[1], initializer=tf.random_normal_initializer()
)
v2 = tf.get_variable(
'v2', dtype=tf.float32, shape=[1], initializer=tf.random_normal_initializer()
)
rezult = v1 + v2
# 构建持久化的对象
saver = tf.train.Saver()
# 创建持久化的文件路径
save_file = './models/ai20/model.ckpt'
dirpath = os.path.dirname(save_file)
if not os.path.exists(dirpath):
os.makedirs(dirpath)
print('成功创建文件夹:{}'.format(dirpath))
# 二、构建会话
with tf.Session() as sess:
# 直接恢复变量,所以无需变量初始化
saver.restore(sess, save_path=save_file)
print(sess.run([v1, v2, rezult]))
"""
[array([0.25989017], dtype=float32),
array([-0.12384889], dtype=float32),
array([0.13604128], dtype=float32)]
"""
if __name__ == '__main__':
# train()
restore_var()
作者:短发越来越短
链接:https://www.pythonheidong.com/blog/article/169676/1e9003deba955a5dcf6b/
来源:python黑洞网
任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任
昵称:
评论内容:(最多支持255个字符)
---无人问津也好,技不如人也罢,你都要试着安静下来,去做自己该做的事,而不是让内心的烦躁、焦虑,坏掉你本来就不多的热情和定力
Copyright © 2018-2021 python黑洞网 All Rights Reserved 版权所有,并保留所有权利。 京ICP备18063182号-1
投诉与举报,广告合作请联系vgs_info@163.com或QQ3083709327
免责声明:网站文章均由用户上传,仅供读者学习交流使用,禁止用做商业用途。若文章涉及色情,反动,侵权等违法信息,请向我们举报,一经核实我们会立即删除!