美文网首页
tensorflow 保存和调用模型

tensorflow 保存和调用模型

作者: 周云锋 | 来源:发表于2017-12-27 16:25 被阅读0次
  • save_graph.py 保存运算图以及训练参数
import tensorflow as tf

x1 = tf.placeholder(dtype=tf.float32, shape=[], name = 'x1')

x2 = tf.placeholder(dtype=tf.float32, shape=[], name = 'x2')

w = tf.Variable(tf.constant(2.), name = 'w')

ytmp = tf.multiply(w, x1, name = 'ytmp')

y = tf.add(ytmp, x2, name = 'y')

sess = tf.Session()

sess.run(tf.global_variables_initializer())

print (sess.run(y, feed_dict={x1: 1., x2: 2.}))

saver = tf.train.Saver()

saver.save(sess, 'model/test')
  • import_graph.py 导入运算图和相应参数
import tensorflow as tf

sess = tf.Session()

# 导入运算图
saver = tf.train.import_meta_graph('model/test.meta')

#加载相应参数
saver.restore(sess, tf.train.latest_checkpoint('model/'))

graph = tf.get_default_graph()

x1 = graph.get_tensor_by_name('x1:0')

x2 = graph.get_tensor_by_name('x2:0')

y = graph.get_tensor_by_name('y:0')

# restore之后不需要执行variable初始化
#sess.run(tf.global_variables_initializer())
print (sess.run(graph.get_tensor_by_name('w:0')))
print (sess.run(y, feed_dict={x1: 1., x2: 2.}))
  • 想要调用保存好的模型,只需要get输入palceholder和最后一步operation即可。

相关文章

网友评论

      本文标题:tensorflow 保存和调用模型

      本文链接:https://www.haomeiwen.com/subject/rpvugxtx.html