tf.add_to_collection(name, value) 用來把一個value放入名稱是‘name’的集合,組成一個列表;
tf.get_collection(key, scope=None) 用來獲取一個名稱是‘key’的集合中的所有元素,返回的是一個列表,列表的順序是按照變量放入集合中的先后; scope參數可選,表示的是名稱空間(名稱域),如果指定,就返回名稱域中所有放入‘key’的變量的列表,不指定則返回所有變量。
tf.add_n(inputs, name=None), 把所有 ‘inputs’列表中的所有變量值相加,name可選,是操作的名稱。
## coding: utf-8 ##
import tensorflow as tf
v1 = tf.get_variable(name='v1', shape=[1], initializer=tf.constant_initializer(1))
tf.add_to_collection('output', v1) # 把變量v1放入‘output’集合中
v2 = tf.get_variable(name='v2', shape=[1], initializer=tf.constant_initializer(2))
tf.add_to_collection('output', v2)
v3 = tf.get_variable(name='v3', shape=[1], initializer=tf.constant_initializer(3))
tf.add_to_collection('output',v3)
with tf.Session() as sess:
sess.run(tf.initialize_all_variables())
print tf.get_collection('output') # 獲取'output'列表內容
print sess.run(tf.add_n(tf.get_collection('output'))) # tf.add_n把列表中所有內容一次性相加
# print:
# [<tf.Variable 'v1:0' shape=(1,) dtype=float32_ref>, <tf.Variable 'v2:0' shape=(1,) dtype=float32_ref>, <tf.Variable 'v3:0' shape=(1,) dtype=float32_ref>]
# [ 6.]