Tensorflow学习笔记——collection 详解

TF的colllection提供一个全局的存储机制,不会受到变量名生存空间的影响。简言之,一处保存,到处可取。

collction的相关函数:

  • tf.add_to_collection(‘list_name’, element)
    将元素element添加到列表list_name中
  • tf.get_collection(‘list_name’)
    返回名称为list_name的列表
  • tf.add_n(list)
    将列表元素相加并返回

示例1:

import tensorflow as tf

tf.add_to_collection('losses', tf.constant(2.2))
tf.get_colleciton('losses', tf.constant(3.))

with tf.Session() as sess:
	print(sess.run(tf.get_collection('losses')))
	print(sess.run(tf.add_n(tf.get_collection('losses'))))

# 注意:使用tf.add_n对列表元素进行相加时,列表内元素类型必须一致,否则会报错。

输出

[2.2, 3.0]
5.2

示例2:

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')
	print sess.run(tf.add_n(tf.get_collection('loss')))

输出:

[<tensorflow.python.ops.variables.Variable object at 0x7f6b5d700c50>, <tensorflow.python.ops.variables.Variable object at 0x7f6b5d700c90>]

TF自己也会维护一些colleciton,就像我们定义所有的summary op都会保存在name=tf.GraphKeys.SUMMARIES。这样,tf.get_colleciton(tf.GraphKeys.SUMMARIES)就会返回所有定义的summary op

示例:

 variables = tf.get_collection(tf.GraphKeys.VARIABLES)
  for i in variables:
  print(i)

>>>   <tf.Variable 'conv1/weights:0' shape=(3, 3, 3, 96) dtype=float32_ref>
      <tf.Variable 'conv1/biases:0' shape=(96,) dtype=float32_ref>
      <tf.Variable 'conv2/weights:0' shape=(3, 3, 96, 64) dtype=float32_ref>
      <tf.Variable 'conv2/biases:0' shape=(64,) dtype=float32_ref>
      <tf.Variable 'local3/weights:0' shape=(16384, 384) dtype=float32_ref>
      <tf.Variable 'local3/biases:0' shape=(384,) dtype=float32_ref>
      <tf.Variable 'local4/weights:0' shape=(384, 192) dtype=float32_ref>
      <tf.Variable 'local4/biases:0' shape=(192,) dtype=float32_ref>
      <tf.Variable 'softmax_linear/softmax_linear:0' shape=(192, 10) dtype=float32_ref>
      <tf.Variable 'softmax_linear/biases:0' shape=(10,) dtype=float32_ref>

Reference:
https://www.jianshu.com/p/6612f368e8f4

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值