add_to_collection的用法

1.add_to_collection
add_to_collectio为Graph的一个方法,可以简单地认为Graph下维护了一个字典,key为name,value为list,而add_to_collection就是把变量添加到对应key下的list中

sess=tf.InteractiveSession()
#初始化2个Variable
v1=tf.Variable(tf.constant(1))
v2=tf.Variable(tf.constant(1))
#设置保存到collection的name为collection
name='collection'
#把v1和v2添加到默认graph的collection中
tf.add_to_collection(name,v1)
tf.add_to_collection(name,v2)
#获得名为name的集合
c1 = tf.get_collection(name)
tf.global_variables_initializer().run()
print("the first collection: %s"%sess.run(c1))
#修改v1和v2的值,必须使用eval()或run()进行执行
tf.assign(v1,tf.constant(3)).eval()
tf.assign(v2,tf.constant(4)).eval()
#再次查看collection中的值
c2 = tf.get_collection(name)
print("the second collection: %s"%sess.run(c2))
print("the sum of collection: %s"%sess.run(tf.add_n(c2))
#resut:
#the first collection: [1, 1]
#the second collection: [3, 4]
#the sum of collection: 7
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值