Tensorflow 获取范围内的所有变量
Tensorflow get all variables in scope
我在特定范围内创建了一些变量,如下所示:
with tf.variable_scope("my_scope"):
createSomeVariables()
...
然后我想获取 "my_scope" 中所有变量的列表,以便将其传递给优化器。正确的做法是什么?
我想你想要 tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope='my_scope')。这将获取范围内的所有变量。
要传递给优化器,您不需要 所有 变量,您只需要可训练变量。这些也保存在默认集合中,即 tf.GraphKeys.TRAINABLE_VARIABLES
.
用户正确指出您需要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
请注意,您可以提供任何 graphKeys 并且范围是正则表达式:
scope: (Optional.) If supplied, the resulting list is filtered to
include only items whose name attribute matches using re.match. Items
without a name attribute are never returned if a scope is supplied and
the choice or re.match means that a scope without special tokens
filters by prefix.
因此,如果您通过 'some_scope',您将获得 6 个变量。
我在特定范围内创建了一些变量,如下所示:
with tf.variable_scope("my_scope"):
createSomeVariables()
...
然后我想获取 "my_scope" 中所有变量的列表,以便将其传递给优化器。正确的做法是什么?
我想你想要 tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope='my_scope')。这将获取范围内的所有变量。
要传递给优化器,您不需要 所有 变量,您只需要可训练变量。这些也保存在默认集合中,即 tf.GraphKeys.TRAINABLE_VARIABLES
.
用户正确指出您需要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
请注意,您可以提供任何 graphKeys 并且范围是正则表达式:
scope: (Optional.) If supplied, the resulting list is filtered to include only items whose name attribute matches using re.match. Items without a name attribute are never returned if a scope is supplied and the choice or re.match means that a scope without special tokens filters by prefix.
因此,如果您通过 'some_scope',您将获得 6 个变量。