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

时间:2016-06-07 03:36:12

标签: tensorflow

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

2 个答案:

答案 0 :(得分:4)

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

  

tf.name_scope(名称)

     
      
  • Graph.name_scope()的包装器使用默认图形。
  •   

我认为您正在寻找的是tf.variable_scope()

  

TensorFlow中的变量范围机制由2个主要功能组成:

     
      
  • tf.get_variable(,,):创建或返回具有给定名称的变量。

  •   
  • tf.variable_scope():管理传递给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

应该这样做。

答案 1 :(得分:0)

我已经解决了上述问题:

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