6

I'm trying to get all the variables in a variable scope, as is explained here. However, the line tf.get_collection(tf.GraphKeys.VARIABLES, scope='my_scope') is returning an empty list even though there are variables in that scope.

Here's some example code:

import tensorflow as tf

with tf.variable_scope('my_scope'):
    a = tf.Variable(0)
print tf.get_collection(tf.GraphKeys.VARIABLES, scope='my_scope')

which prints [].

How can I get the variables declared in 'my_scope'?

Community
  • 1
  • 1
Matt Cooper
  • 2,042
  • 27
  • 43

1 Answers1

11

The tf.GraphKeys.VARIABLES collection name has been deprecated since TensorFlow 0.12. Using tf.GraphKeys.GLOBAL_VARIABLES will give the expected result:

with tf.variable_scope('my_scope'):
    a = tf.Variable(0)
print tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope='my_scope')
# ==> '[<tensorflow.python.ops.variables.Variable object at 0x7f33f67ebbd0>]'
mrry
  • 125,488
  • 26
  • 399
  • 400
  • 1
    Some deprecation message during running would be nice : ) – Bily Dec 03 '16 at 06:02
  • for me that is still not working. Do I need to pass the graph somewhere or something like that? – Charlie Parker Mar 20 '17 at 18:39
  • I tried using the graph object itself directly and didn't work: `graph.get_collection(name='scope_name')`. Any idea whats wrong? – Charlie Parker Mar 20 '17 at 18:42
  • 2
    @CharlieParker The `tf.get_collection()` method assumes that everything is in a single default graph (i.e. the graph returned by `tf.get_default_graph()`). If you have multiple graph objects, and the graph of interest is called `g`, you can use [`g.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope='my_scope')`](https://www.tensorflow.org/api_docs/python/tf/Graph#get_collection) instead. However, if that doesn't work, you might have the wrong `tf.Graph` object. It would probably be easiest to address in a separate question with more of the code. – mrry Mar 20 '17 at 18:43
  • ok never mind. The error seems to be my confusion of `variable_scope` vs `name_scope`. I read the answer here:http://stackoverflow.com/questions/35919020/whats-the-difference-of-name-scope-and-a-variable-scope-in-tensorflow , but it still doesn't make sense to me why there are two types of name scoping (seems really annoying). – Charlie Parker Mar 20 '17 at 19:42