TF的colllection提供一个全局的存储机制,不会受到变量名生存空间的影响。简言之,一处保存,到处可取。
collction的相关函数:
- tf.add_to_collection(‘list_name’, element)
将元素element添加到列表list_name中 - tf.get_collection(‘list_name’)
返回名称为list_name的列表 - tf.add_n(list)
将列表元素相加并返回
示例1:
import tensorflow as tf
tf.add_to_collection('losses', tf.constant(2.2))
tf.get_colleciton('losses', tf.constant(3.))
with tf.Session() as sess:
print(sess.run(tf.get_collection('losses')))
print(sess.run(tf.add_n(tf.get_collection('losses'))))
# 注意:使用tf.add_n对列表元素进行相加时,列表内元素类型必须一致,否则会报错。
输出
[2.2, 3.0]
5.2
示例2:
import tensorflow as tf;
import numpy as np;
import matplotlib.pyplot as plt;
v1 = tf.get_variable(name='v1', shape=[1], initializer=tf.constant_initializer(0))
tf.add_to_collection('loss', v1)
v2 = tf.get_variable(name='v2', shape=[1], initializer=tf.constant_initializer(2))
tf.add_to_collection('loss', v2)
with tf.Session() as sess:
sess.run(tf.initialize_all_variables())
print tf.get_collection('loss')
print sess.run(tf.add_n(tf.get_collection('loss')))
输出:
[<tensorflow.python.ops.variables.Variable object at 0x7f6b5d700c50>, <tensorflow.python.ops.variables.Variable object at 0x7f6b5d700c90>]
TF自己也会维护一些colleciton,就像我们定义所有的summary op
都会保存在name=tf.GraphKeys.SUMMARIES
。这样,tf.get_colleciton(tf.GraphKeys.SUMMARIES)
就会返回所有定义的summary op
示例:
variables = tf.get_collection(tf.GraphKeys.VARIABLES)
for i in variables:
print(i)
>>> <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>
Reference:
https://www.jianshu.com/p/6612f368e8f4