Tensorflow评估,[关闭]

问题描述 投票:-1回答:1

给定层的张量名称,是否可以仅针对特定层评估输入,并且通常可以在前向传递期间保存所有结果?

将不胜感激任何帮助

tensorflow neural-network tensorflow-estimator
1个回答
1
投票

问题有点不清楚,但我认为这就是你所追求的:

您创建的每个张量或操作都有一个可能的参数name。通过为每个张量提供一个名称,您可以使用tf.Graph().get_tensor_by_name并在调用时在feed_dict中传递所需的输入。

至于保存结果,您可以使用tf.train.Saver()类保存模型的当前状态。

下面是一个模型的简单示例,其中在一个脚本中创建并保存模型,然后加载第二个脚本,同时加载该模型,并使用tf.Graph().get_tensor_by_name访问其Tensors。

save_model.朋友

#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.朋友

# 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]]

注意::0中操作名称后面的“get_tensor_by_name()”指定它是您想要的那个操作的第0个张量输出。

可以看到这段代码在一组jupyter笔记本here中工作,还有另一个更简单的实现,如果你已经构建了图形。

© www.soinside.com 2019 - 2024. All rights reserved.