Tensorflow获取范围内的所有变量

Vla*_*oiu 40 tensorflow

我在某个范围内创建了一些变量,如下所示:

with tf.variable_scope("my_scope"):
  createSomeVariables()
  ...
Run Code Online (Sandbox Code Playgroud)

然后我想获取"my_scope"中所有变量的列表,这样我就可以将它传递给优化器.这样做的正确方法是什么?

use*_*291 77

我想你想要tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES,scope ='my_scope').这将获取范围内的所有变量.

要传递给优化器,您不希望所有变量只需要可训练变量.这些也保存在默认集合中,即tf.GraphKeys.TRAINABLE_VARIABLES.

  • `tf.GraphKeys.VARIABLES`在v0.12中被弃用(我从这个答案中学到了:http://stackoverflow.com/a/40918792/1827383).请改用`tf.GraphKeys.GLOBAL_VARIABLES`. (18认同)

Sal*_*ali 14

用户正确指出您需要tf.get_collection().我将举一个简单的例子来说明如何做到这一点:

import tensorflow as tf

with tf.name_scope('some_scope1'):
    a = tf.Variable(1, 'a')
    b = tf.Variable(2, 'b')
    c = tf.Variable(3, 'c')

with tf.name_scope('some_scope2'):
    d = tf.Variable(4, 'd')
    e = tf.Variable(5, 'e')
    f = tf.Variable(6, 'f')

h = tf.Variable(8, 'h')

for i in tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope='some_scope'):
    print i   # i.name if you want just a name
Run Code Online (Sandbox Code Playgroud)

请注意,您可以提供任何graphKeys和scope是一个正则表达式:

scope :(可选.)如果提供,则生成的列表将被过滤,以仅包含name属性与re.match匹配的项目.如果提供了作用域,则不会返回没有name属性的项目,而choice或re.match表示没有特殊标记的作用域按前缀过滤.

因此,如果您将传递'som​​e_scope',您将获得6个变量.