【发布时间】:2019-03-15 13:10:39
【问题描述】:
给定层的张量名称,是否可以仅评估特定层的输入,并且通常可以在前向传递期间保存所有结果?
将不胜感激任何帮助
【问题讨论】:
标签: tensorflow neural-network tensorflow-estimator
给定层的张量名称,是否可以仅评估特定层的输入,并且通常可以在前向传递期间保存所有结果?
将不胜感激任何帮助
【问题讨论】:
标签: tensorflow neural-network tensorflow-estimator
问题有点不清楚,但我认为这就是你所追求的:
您创建的每个张量或操作都有一个可能的参数name。通过为每个张量提供名称,您可以使用 tf.Graph().get_tensor_by_name 并在调用时将所需的输入传递给 feed_dict。
至于保存结果,您可以使用tf.train.Saver() 类保存模型的当前状态。
这是一个简单的模型示例,其中在一个脚本中创建并保存模型,然后在第二个脚本中加载相同的模型,并使用 tf.Graph().get_tensor_by_name 访问其张量。
save_model.py
#create model
x = tf.placeholder(tf.float32, shape=[3,3], name="x")
w = tf.Variable(tf.random_normal(dtype=tf.float32, shape=[3,3], mean=0, stddev=0.5), name="w")
xw = tf.multiply(x,w, name="xw")
# create saver
saver = tf.train.Saver()
# run and save model
x_input = np.ones((3,3))*2 # numpy array of 2s
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
xw_out = sess.run(xw, feed_dict={x: x_input})
# save model including variables to ./tmp
save_path = saver.save(sess, "./tmp/model.ckpt")
print("Model saved with w at: \n {}".format(w.eval()))
>>>Model saved with w at:
>>> [[ 0.07033788 -0.9353725 0.9999725 ]
>>> [-0.2922624 -1.143613 -1.0453095 ]
>>> [ 0.02661585 0.18821386 0.19582961]]
print(xw_out)
>>>[[ 0.14067577 -1.870745 1.999945 ]
>>>[-0.5845248 -2.287226 -2.090619 ]
>>>[ 0.05323171 0.3764277 0.39165923]]
load_model.py
# load saved model graph
saver = tf.train.import_meta_graph("./tmp/model.ckpt.meta")
x_input = np.ones((3,3))*2 # numpy array of 2s
with tf.Session() as sess:
# Restore sesssion from saver
saver.restore(sess, "./tmp/model.ckpt")
print("Model restored.")
# Check the values of the variables
w = sess.run(sess.graph.get_tensor_by_name("w:0"))
xw = sess.run(sess.graph.get_tensor_by_name("xw:0"), feed_dict={"x:0": x_input})
print("Output calculated with w loaded from ./tmp at: \n {}".format(w))
>>>INFO:tensorflow:Restoring parameters from ./tmp/model.ckpt
>>>Model restored.
>>>Output calculated with w loaded from ./tmp at:
>>> [[ 0.07033788 -0.9353725 0.9999725 ]
>>> [-0.2922624 -1.143613 -1.0453095 ]
>>> [ 0.02661585 0.18821386 0.19582961]]
print(xw)
>>>[[ 0.14067577 -1.870745 1.999945 ]
>>>[-0.5845248 -2.287226 -2.090619 ]
>>>[ 0.05323171 0.3764277 0.39165923]]
注意:get_tensor_by_name() 中操作名称后面的“:0”指定它是您想要的该操作输出的 0th 张量。
可以在一组 jupyter notebook here 中看到此代码,如果您已经构建了图表,还有另一个更简单的实现。
【讨论】: