Tensorflow:如何通过名称获得张量?

pro*_*tas 47 python scope tensorflow

我无法通过名字恢复张量,我甚至不知道它是否可能.

我有一个创建我的图形的函数:

def create_structure(tf, x, input_size,dropout):    
 with tf.variable_scope("scale_1") as scope:
  W_S1_conv1 = deep_dive.weight_variable_scaling([7,7,3,64], name='W_S1_conv1')
  b_S1_conv1 = deep_dive.bias_variable([64])
  S1_conv1 = tf.nn.relu(deep_dive.conv2d(x_image, W_S1_conv1,strides=[1, 2, 2, 1], padding='SAME') + b_S1_conv1, name="Scale1_first_relu")
.
.
.
return S3_conv1,regularizer
Run Code Online (Sandbox Code Playgroud)

我想访问此函数外的变量S1_conv1.我试过了:

with tf.variable_scope('scale_1') as scope_conv: 
 tf.get_variable_scope().reuse_variables()
 ft=tf.get_variable('Scale1_first_relu')
Run Code Online (Sandbox Code Playgroud)

但这给了我一个错误:

ValueError:欠共享:变量scale_1/Scale1_first_relu不存在,不允许.你是不是要在VarScope中设置reuse = None?

但这有效:

with tf.variable_scope('scale_1') as scope_conv: 
 tf.get_variable_scope().reuse_variables()
 ft=tf.get_variable('W_S1_conv1')
Run Code Online (Sandbox Code Playgroud)

我可以解决这个问题

return S3_conv1,regularizer, S1_conv1
Run Code Online (Sandbox Code Playgroud)

但我不想那样做.

我认为我的问题是S1_conv1实际上不是一个变量,它只是一个张量.有办法做我想要的吗?

apf*_*alz 55

有一个函数tf.Graph.get_tensor_by_name().例如:

import tensorflow as tf

c = tf.constant([[1.0, 2.0], [3.0, 4.0]])
d = tf.constant([[1.0, 1.0], [0.0, 1.0]])
e = tf.matmul(c, d, name='example')

with tf.Session() as sess:
    test =  sess.run(e)
    print e.name #example:0
    test = tf.get_default_graph().get_tensor_by_name("example:0")
    print test #Tensor("example:0", shape=(2, 2), dtype=float32)
Run Code Online (Sandbox Code Playgroud)

  • 作为参考,如果您需要获得OP而不是张量:http://stackoverflow.com/questions/42685994/how-to-get-a-tensorflow-op-by-name (3认同)

Yar*_*tov 32

所有张量都有字符串名称,您可以看到如下

[tensor.name for tensor in tf.get_default_graph().as_graph_def().node]
Run Code Online (Sandbox Code Playgroud)

一旦知道了名称,就可以使用Tensor获取<name>:0(0表示有点多余的端点)

例如,如果你这样做

tf.constant(1)+tf.constant(2)
Run Code Online (Sandbox Code Playgroud)

您有以下Tensor名称

[u'Const', u'Const_1', u'add']
Run Code Online (Sandbox Code Playgroud)

所以你可以获取添加的输出

sess.run('add:0')
Run Code Online (Sandbox Code Playgroud)

请注意,这不是公共API的一部分.自动生成的字符串张量名称是实现细节,可能会更改.