集合collection

tf.get_collection:从一个结合中取出全部变量,是一个列表

tensorflow用集合 colletion 组织不同类别的对象。 tf.GraphKeys 中包含了所有默认集合的名称。collection提供了一种“零存整取”的思路:在任意位置,任意层次都可以创造对象,存入相应collection中;创造完成后,统一从一个collection中取出一类变量,施加相应操作。例如,tf.Optimizer只优化tf.GraphKeys.TRAINABLE_VARIABLES中的变量。

Variable

Variable被收集在名为tf.GraphKeys.VARIABLEScolletion

定义

Tensorflow使用Variable类表达、更新、存储模型参数。

k = tf.Variable(tf.random_normal([]), name='k')
创建的 Variable 被添加到默认的 collection 中.
获取
Tensor , Operation 一样, Variable 也是全局的。 可以通过tf.all_variables()查看所有 tf.GraphKeys.VARIABLES 中的对象:
也可以用通用方法直接访问collection
with tf.variable_scope('scope'): v1 = tf.get_variable('var', [1]) with tf.variable_scope('scope2'): v2 = tf.get_variable('var', [1])v = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES)
v = tf.all_variables()#这两种方式都可以
print(v)#[<tf.Variable 'scope/var:0' shape=(1,) dtype=float32_ref>, <tf.Variable 'scope/scope2/var:0' shape=(1,) dtype=float32_ref>]

各类Variable

tensorflow维护多个collection

函数集合名意义
tf.all_variables()VARIABLES存储和读取checkpoints时,使用其中所有变量
tf.trainable_variables()TRAINABLE_VARIABLES训练时,更新其中所有变量
tf.moving_average_variables()MOVING_AVERAGE_VARIABLESExponentialMovingAverage对象会生成此类变量
tf.local_variables()LOCAL_VARIABLESall_variables()之外,需要用tf.init_local_variables()初始化
tf.model_variables()MODEL_VARIABLES
操作
tf.add_to_collection:把变量放入一个集合,把很多变量变成一个列表

tf.get_collection:从一个集合中取出全部变量,是一个列表

tf.add_n:把一个列表的东西都依次加起来
import tensorflow as tf;    
import numpy as np;    
import matplotlib.pyplot as plt;    
v1 = tf.get_variable(name='v1', shape=[1], initializer=tf.constant_initializer(0))  
tf.add_to_collection('loss', v1)  
v2 = tf.get_variable(name='v2', shape=[1], initializer=tf.constant_initializer(2))  
tf.add_to_collection('loss', v2)    
with tf.Session() as sess:  
    sess.run(tf.initialize_all_variables())  
    print (tf.get_collection('loss') ) #[<tf.Variable 'v1:0' shape=(1,) dtype=float32_ref>, <tf.Variable 'v2:0' shape=(1,) dtype=float32_ref>]
    print (sess.run(tf.add_n(tf.get_collection('loss')))  )#[ 2.]
    v = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES)
    print(v)#[<tf.Variable 'v1:0' shape=(1,) dtype=float32_ref>, <tf.Variable 'v2:0' shape=(1,) dtype=float32_ref>]
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值