[专题2]tensorflow model save and restore 模型的保存和恢复(1)

Tensorflow: how to save/restore a model?


PS  马上要锁门了,先把代码 贴出来,.

一、入门

Question:

After you train a model in Tensorflow:

1. How do you save the trained model?

2. How do you later restore this saved model?

程序设计目标:

使用saver.save() 保存简单的模型

并使用

saver = tf.train.import_meta_graph('保存的模型文件')

saver.restore(sess,tf.train.latest_checkpoint('指定CKPT文件'))

Save Model


import tensorflow as tf

# 定义要占位的变量 , i.e. feed_dict and placeholders

w1 = tf.placeholder("float", name="w1")

w2 = tf.placeholder("float", name="w2")

b1= tf.Variable(2.0,name="bias")

feed_dict ={w1:4,w2:8}

# 定义要保存的操作

w3 = tf.add(w1,w2)

w4 = tf.multiply(w3,b1,name="op_to_restore")

sess = tf.Session()

sess.run(tf.global_variables_initializer())

# 创建saver 对象保存

saver = tf.train.Saver()

# 运行

print(sess.run(w4,feed_dict))

#Prints 24 which is sum of (w1+w2)*b1

#保存图 my_test_model是指定保存模型的路径

saver.save(sess, './my_test_model',global_step=1000)

Restore the model:

import tensorflow as tf

sess=tf.Session()

# 首先加载模型 ,注意这里要说明加载的文件

saver = tf.train.import_meta_graph('./my_test_model-1000.meta')

saver.restore(sess,tf.train.latest_checkpoint('./'))

# 访问模型的中的变量

print(sess.run('bias:0'))

# 会打印出 2, 这个是在上一段程序中保存过的变量

# Now, let's access and create placeholders variables and

# create feed-dict to feed new data

graph = tf.get_default_graph()

w1 = graph.get_tensor_by_name("w1:0")

w2 = graph.get_tensor_by_name("w2:0")

feed_dict ={w1:13.0,w2:17.0}

#Now, access the op that you want to run.

op_to_restore = graph.get_tensor_by_name("op_to_restore:0")

print sess.run(op_to_restore,feed_dict)

#This will print 60 which is calculated

相关参考文献:

save-restore-tensorflow-models-quick-complete-tutoria

tensorflow-how-to-save-restore-a-model

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 简单线性回归 import tensorflow as tf import numpy # 创造数据 x_dat...
    CAICAI0阅读 8,947评论 0 49
  • 一下子现在的网红就火了个热朝天,Papi酱这种之前听都没听过的声音一下子就传开了。网红的活动遍布各个角落。 很神奇...
    Jim88阅读 5,254评论 0 1
  • Moodibars 心情巧克力,从超市买来的看上去很有爱的巧克力。一共有四种心情,happy与blash对应的是甜...
    伊蒂雅阅读 4,044评论 0 1
  • 我在静静的等待,她就在那慢腾腾的磨蹭…… 闺女的性格就是慢,说话慢,走路慢,穿衣慢,洗漱慢,吃饭也慢! 学习上更慢...
    徍音_阅读 1,715评论 2 3
  • 做翻译一年半了,在做这份工作之前没有想到会做这样的工作,天天要说话,经常还要站在很多人面前说话。之前我曾写过一篇《...
    七宝粥阅读 4,913评论 34 20

友情链接更多精彩内容