tf.get_collection() 主要作用:从一个集合中取出变量
官方文档:https://tensorflow.google.cn/api_docs/python/tf/get_collection
tf.get_collection(
key,
scope=None
)
该函数有两个参数
-
key: The key for the collection. For example, the GraphKeys class contains many standard names for collections.
-
scope: (可选参数) 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.
该函数可以用来获取key集合中的所有元素,返回一个列表。列表的顺序依变量放入集合中的先后而定。scope为可选参数,表示的是名称空间(名称域),如果指定,就返回名称域中所有放入‘key’的变量的列表,不指定则返回所有变量。
例子
variables = tf.get_collection(tf.GraphKeys.VARIABLES)
for i in variables:
print(i)
out:
<tf.Variable 'conv1/weights:0' shape=(3, 3, 3, 96) dtype=float32_ref>
<tf.Variable 'conv1/biases:0' shape=(96,) dtype=float32_ref>
<tf.Variable 'conv2/weights:0' shape=(3, 3, 96, 64) dtype=float32_ref>
<tf.Variable 'conv2/biases:0' shape=(64,) dtype=float32_ref>
<tf.Variable 'local3/weights:0' shape=(16384, 384) dtype=float32_ref>
<tf.Variable 'local3/biases:0' shape=(384,) dtype=float32_ref>
<tf.Variable 'local4/weights:0' shape=(384, 192) dtype=float32_ref>
<tf.Variable 'local4/biases:0' shape=(192,) dtype=float32_ref>
<tf.Variable 'softmax_linear/softmax_linear:0' shape=(192, 10) dtype=float32_ref>
<tf.Variable 'softmax_linear/biases:0' shape=(10,) dtype=float32_ref>
又如
tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES,
scope="hidden[123]")
表示获取第1,2,3隐藏层的权重