TensorFLow collection的用法

tf.add_to_collection: 把变量放入一个集合当中
tf.get_collection: 把集合中的全部变量取出,是一个列表
tf.add_n: 把列表中的变量加起来

例子:
import tensorflow as tf
tf.reset_default_graph()

w1 = tf.get_variable('w1', shape=[4], dtype=tf.float32, initializer=tf.truncated_normal_initializer(stddev=0.1))
w2 = tf.get_variable('w2', shape=[4], dtype=tf.float32, initializer=tf.constant_initializer(0.1))
tf.add_to_collection('w', w1)
tf.add_to_collection('w', w2)
get_w = tf.get_collection('w')
add_w = tf.add_n(get_w)
init_op = tf.global_variables_initializer()
with tf.Session() as sess:
    sess.run(init_op)
    print("生成数据的样结果:")
    print(sess.run(w1))
    print(sess.run(w2))
    print("放入集合w数据的结果:")
    print(sess.run(get_w))
    print("集合w中的数据相加的记过")
    print(sess.run(add_w))

运行结果如下:
生成数据的样结果:
[ 0.00524002  0.0679507  -0.0160088  -0.04484038]
[0.1 0.1 0.1 0.1]
放入集合w数据的结果:
[array([ 0.00524002,  0.0679507 , -0.0160088 , -0.04484038], dtype=float32), array([0.1, 0.1, 0.1, 0.1], dtype=float32)]
集合w中的数据相加的结果:
[0.10524002 0.16795069 0.0839912  0.05515962]
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值