Python TensorFlow函数tf.get_collection使用方法详解

Ryan
Ryan
发布时间:2026-10-15| 5人浏览过
原创

本文详细介绍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的资料请持续关注本站其他相关文章!

免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。

Python 相关产品和应用

全部下载
Selenium

Selenium

4.51.0 · Windows

用于浏览器自动化和 Web 测试的 Python 工具。

scikit-learn

scikit-learn

1.9.1 · Windows

常用 Python 机器学习算法与模型评估工具库。

Black

Black

26.10.1 · Windows

强调一致性的 Python 自动代码格式化工具。

Ruff

Ruff

0.17.1 · macOS

由 Rust 编写的高速 Python 代码检查和格式化工具。

pytest

pytest

9.1.1 · Windows

简洁而强大的 Python 自动化测试框架。

FastAPI

FastAPI

0.146.0 · Windows

高性能 Python API 框架,支持类型提示和自动接口文档。

Flask

Flask

3.1.3 · Windows

轻量灵活的 Python Web 应用框架。

Django

Django

6.1.2 · Windows

成熟的 Python Web 框架,适合构建内容站点和业务系统。

Spyder

Spyder

6.1.7 · Windows

面向科学计算与数据分析的 Python 集成开发环境。

SciPy

SciPy

1.18.1 · Windows

面向科学、工程和技术计算的 Python 算法库。