Python TensorFlow函数tf.get_collection使用方法详解
本文详细介绍TensorFlow中tf.get_collection函数的使用方法。该函数用于从指定collection中获取全部变量并返回列表,主要包含key和scope两个参数。文章通过具体代码示例,展示了其与tf.get_variable和tf.add_to_collection的配合使用方式,帮助开发者掌握变量集合的管理技巧。
参数数量及其作用
该函数包含两个参数:key和scope。
def get_collection(key, scope=None)
Wrapper for Graph.get_collection() using the default graph.
See tf.Graph.get_collection for more details.
Args:
key: The key for the collection. For example, the `GraphKeys` class
contains many standard names for collections.
scope: (Optional.) If supplied, the resulting list is filtered to include
only items whose `name` attribute matches using `re.match`. Items
without a `name` attribute are never returned if a scope is supplied and
the choice or `re.match` means that a `scope` without special tokens
filters by prefix.
Returns:
The list of values in the collection with the given `name`, or
an empty list if no value has been added to that collection. The
list contains the values in the order under which they were
collected.
此函数的主要功能是从指定的collection中提取所有变量,并将它们整理为一个列表。其中,key参数用于指定要查询的collection名称。
在实际应用中,tf.get_collection通常与tf.get_variable和tf.add_to_collection函数配合使用。
代码示例
以下示例分别演示了tf.get_collection与tf.get_variable及tf.add_to_collection的协同使用方法。
import tensorflow as tf;
import numpy as np;
c1 = ['c1', tf.GraphKeys.GLOBAL_VARIABLES]
v1 = tf.get_variable('v1', [1], initializer=tf.constant_initializer(1),collections=c1)
v2 = tf.get_variable('v2', [1], initializer=tf.constant_initializer(2))
tf.add_to_collection('c2', v2)
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
print(tf.get_collection('c1'))
print(tf.get_collection('c2'))
运行结果如下:
[<tf.Variable 'v1:0' shape=(1,) dtype=float32_ref>]
[<tf.Variable 'v2:0' shape=(1,) dtype=float32_ref>]
关于tf.get_variable的具体用法,可参考我的另一篇文章:
Python TensorFlow函数tf.get_variable使用方法
以上就是Python TensorFlow函数tf.get_collection使用方法的详细介绍,更多关于TensorFlow函数tf.get_collection的资料请持续关注本站其他相关文章!
本站声明
本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。













