tensorflow 保存和调用模型

2017-12-27  本文已影响0人  周云锋
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 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.}))
上一篇 下一篇

猜你喜欢

热点阅读