给定层的张量名称,是否可以仅针对特定层评估输入,并且通常可以在前向传递期间保存所有结果?
将不胜感激……
问题有点不清楚,但我认为这就是你所追求的:
您创建的每个张量或操作都有一个可能的参数 name 。通过为每个张量提供一个名称,您可以使用 tf.Graph().get_tensor_by_name 并传递你想要的输入 feed_dict 在打电话的时候。
name
tf.Graph().get_tensor_by_name
feed_dict
至于保存结果,您可以使用保存模型的当前状态 tf.train.Saver() 类。
下面是一个模型的简单示例,其中在一个脚本中创建并保存模型,然后加载第二个脚本,同样的模型被加载,并使用它的Tensors访问 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]]
注意:“ :0 “跟随操作名称 get_tensor_by_name() 指定它是 第0 您想要的那个操作的张量输出。
:0
get_tensor_by_name()
可以看到这段代码在一组jupyter笔记本中工作 这里 ,还有另一个更简单的实现,因为如果您已经构建了图形。