tf.add_to_collection方法

import tensorflow as tf

v1 = tf.get_variable('v1', shape=[1], initializer=tf.ones_initializer())
v2 = tf.get_variable('v2', shape=[1], initializer=tf.zeros_initializer())

tf.add_to_collection('vc', v1)
tf.add_to_collection('vc', v2)

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    vc = tf.get_collection('vc')
    print(vc)
    for i in vc:
        print(i)
        print(sess.run(i))

输出内容:

[<tf.Variable 'v1:0' shape=(1,) dtype=float32_ref>, <tf.Variable 'v2:0' shape=(1,) dtype=float32_ref>]
<tf.Variable 'v1:0' shape=(1,) dtype=float32_ref>
[ 1.]
<tf.Variable 'v2:0' shape=(1,) dtype=float32_ref>
[ 0.]

tf.get_collection 返回 当前计算图 中手动添加的张量集合。

原文地址:https://www.cnblogs.com/guqiangjs/p/7805289.html