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

Tensorflow 如何获取tf.name_scope()中定义的变量的值?,tensorflow,Tensorflow,我想使用tf.get_变量来获取变量hidden4/weights,定义如上,但失败如下: 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) + bias

我想使用tf.get_变量来获取变量hidden4/weights,定义如上,但失败如下:

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.name\u范围(名称)

  • 使用默认图形的Graph.name_scope()的包装器
我想你要找的是:

TensorFlow中的可变范围机制包括两个主要功能:

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

  • tf.variable_scope():管理传递给tf.get_variable()的名称的名称空间

带有tf.variable_scope('hidden4')的
:
#此范围中不存在名为的变量,因此它将创建该变量
权重=tf.get_变量(“权重”,tf.convert_to_张量(权重4))#必须完全定义新变量的形状(隐藏4/权重)
偏差=tf.get_变量(“偏差”,tf.convert_to_张量(偏差4))#必须完全定义新变量的形状(隐藏/偏差)
hidden4=tf.sigmoid(tf.matmul(hidden3,权重)+偏差)
使用tf.variable_scope('hidden4',reuse=True):
hidden4weights=tf.get_变量(“权重”)
断言权重==hidden4weights

应该可以了。

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

classifyerlayer_W=[v代表tf.all_variables(),如果v.name==“softmax_-linear/weights:0”][0]#按名称“softmax_-linear/weights:0”查找变量
init=numpy.random.randn(20484382)#创建一个用于重新初始化变量的数组
assign_op=classifyerlayer_W.assign(init)#创建一个assign操作
sess.run(assign_op)#运行op完成分配

非常感谢您的帮助和详细说明!!我遇到了一个新问题,如下所示
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)
(Pdb) hidden4/weights.eval(sess)
*** NameError: name 'hidden4' is not defined
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