tensorflow随笔-collection收集器

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u010255642/article/details/82144303

collection收集器的作用在于,可以在计算图运行过程中保存需要的值。

get_collection得到collection中关于key的内容,返回值是一个列表。

add_to_collection将值增加到collection中,并与name关联

add_to_collections将一个值放入多个collection中

tf.get_collection(
    key,
    scope=None
)
tf.add_to_collection(
    name,
    value
)
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Mon Aug 27 11:16:32 2018

@author: myhaspl
"""

import tensorflow as tf
a = tf.constant([[1., 2.], [3., 4.]])
b = a+1
c= b+2


tf.add_to_collection("my_constant",a)
tf.add_to_collection("my_constant",b)  
tf.add_to_collection("my_constant",c)

const_vals=tf.get_collection("my_constant")
res=tf.add_n([a,b,c])                                                         
sess=tf.Session()
with sess:
    print sess.run(res)
    print sess.run(const_vals)
[[ 7. 10.]
 [13. 16.]]
[array([[1., 2.],
       [3., 4.]], dtype=float32), array([[2., 3.],
       [4., 5.]], dtype=float32), array([[4., 5.],
       [6., 7.]], dtype=float32)]

记住,上次跑程序已经保存的值不会被自动删除,值会累计保存,直到python进程退出。否则,再跑一次上面的程序,则

[[ 7. 10.]
 [13. 16.]]
[array([[1., 2.],
       [3., 4.]], dtype=float32), array([[2., 3.],
       [4., 5.]], dtype=float32), array([[4., 5.],
       [6., 7.]], dtype=float32), array([[1., 2.],
       [3., 4.]], dtype=float32), array([[2., 3.],
       [4., 5.]], dtype=float32), array([[4., 5.],
       [6., 7.]], dtype=float32)]
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Mon Aug 27 11:16:32 2018

@author: myhaspl
"""

import tensorflow as tf
a = tf.constant([[1., 2.], [3., 4.]])



tf.add_to_collections(["my_con1","my_con2"],a)


const_1=tf.get_collection("my_con1")
const_2=tf.get_collection("my_con2")
                                                         
sess=tf.Session()
with sess:

    print sess.run(const_1)
    print sess.run(const_2)
[array([[1., 2.],
       [3., 4.]], dtype=float32)]
[array([[1., 2.],
       [3., 4.]], dtype=float32)]

猜你喜欢

转载自blog.csdn.net/u010255642/article/details/82144303