tf.add_to_collection:就是张量放到命名为name的集合中
在tensorflow2.0中的语法如下:
tf.Graph.add_to_collection(
name, value
)
name: 集合的名字
value: 加到集合中的张量
tf.get_collection: 返回给定名字集合的一个列表的张量
在tensorflow2.0中的语法如下:
tf.Graph.get_collection(
name,
scope = None
)
name: 集合的名字
scope: (可选项)一个字符串。如果提供的话,将在之前返回的list中利用re.match找到匹配的的项。
栗子
import tensorflow as tf
v1 = tf.get_variable('v1', shape=[3], initializer=tf.ones_initializer())
v2 = tf.get_variable('v2', shape=[5], initializer=tf.random_uniform_initializer(maxval=-1., minval=1., seed=0))
# 向当前计算图中添加张量集合
tf.add_to_collection('v', v1)
tf.add_to_collection('v', v2)
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
# 返回当前计算图中手动添加的张量集合
v = tf.get_collection('v')
print v
print v[0].eval()
print v[1].eval()
[<tf.Variable 'v1:0' shape=(3,) dtype=float32_ref>, <tf.Variable 'v2:0' shape=(5,) dtype=float32_ref>]
[ 1. 1. 1.]
[ 0.79827476 -0.9403336 -0.69752836 0.90343738 0.90295386]