如何获取tf.name_scope()中定义的变量的值?

How to get the value of a variable defined in tf.name_scope()?

with tf.name_scope('hidden4'):
    weights = tf.Variable(tf.convert_to_tensor(weights4))
    biases = tf.Variable(tf.convert_to_tensor(biases4))
    hidden4 = tf.sigmoid(tf.matmul(hidden3, weights) + biases)

我想用tf.get_variable获取上面定义的变量hidden4/weights,但是失败如下:

hidden4weights = tf.get_variable("hidden4/weights:0")
*** ValueError: Variable hidden4/weights:0 already exists, disallowed.       Did you mean to set reuse=True in VarScope? Originally defined at:

File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.7/pdb.py", line 234, in default
exec code in globals, locals
File "/usr/local/lib/python2.7/cmd.py", line 220, in onecmd
return self.default(line)

然后我尝试hidden4/weights.eval(sess),但也失败了。

(Pdb) hidden4/weights.eval(sess)
*** NameError: name 'hidden4' is not defined

tf.name_scope()用于可视化变量。

tf.name_scope(name)

  • Wrapper for Graph.name_scope() using the default graph.

我想你要找的是 tf.variable_scope():

Variable Scope mechanism in TensorFlow consists of 2 main functions:

  • tf.get_variable(, , ): Creates or returns a variable with a given name.

  • tf.variable_scope(): Manages namespaces for names passed to tf.get_variable().

with tf.variable_scope('hidden4'):
    # No variable in this scope with name exists, so it creates the variable
    weights = tf.get_variable("weights", <shape>, tf.convert_to_tensor(weights4)) # Shape of a new variable (hidden4/weights) must be fully defined
    biases = tf.get_variable("biases", <shape>, tf.convert_to_tensor(biases4)) # Shape of a new variable (hidden4/biases) must be fully defined
    hidden4 = tf.sigmoid(tf.matmul(hidden3, weights) + biases)

with tf.variable_scope('hidden4', reuse=True):
    hidden4weights = tf.get_variable("weights")

assert weights == hidden4weights

应该可以了。

我已经解决了上面的问题:

classifyerlayer_W=[v for v in tf.all_variables() if v.name == "softmax_linear/weights:0"][0]  #find the variable by name "softmax_linear/weights:0"
init= numpy.random.randn(2048, 4382) # create a array you use to re-initial the variable
assign_op = classifyerlayer_W.assign(init) # create a assign operation 
sess.run(assign_op) # run op to finish the assign