类tensorflow.python.framework.function.Defun的说明

本文详细介绍了TensorFlow中的Defun装饰器,用于定义可在TensorFlow环境中直接使用的Python函数。通过示例展示了如何使用Defun将接受特定类型参数的Python函数转换为TensorFlow函数,包括变量创建和图构建过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

tensorflow.python.framework.function.Defun

文档路径(我使用的是anaconda3):
$CONDAHOME/lib/python3.5/site-packages/tensorflow/python/framework/function.py

用于定义 TensorFlow 函数的装饰器。

使用此装饰器使Python函数可以直接用作TensorFlow函数。

修饰函数必须将操作添加到默认的图并返回零个或多个Tensor对象使用命名参数调用装饰器,每个参数用于要装饰的函数的每个参数,参数的预期类型为值

例如,如果要装饰的函数接受两个名为xytf.float32参数,请使用以下命令调用装饰器:

@Defun(tf.float32, tf.float32)
def foo(x, y):
  ...

当你调用修饰函数时,它会将call操作添加到默认的图中,并将函数的定义添加到默认的图中。因为将函数添加到图中被延迟了,所以装饰器可以在程序中的任何地方使用

在函数内部创建的任何变量都会被提升到外部图中。请注意,变量是在第一次调用函数期间处于活动状态的变量作用域中创建的。后续函数调用将引用同一组变量。

一旦使用图创建任务,函数的定义就会冻结在图中。因此,必须在创建相应任务之前在图中创建使用该函数的节点

举例:

# Defining the function.
@tf.Defun(tf.float32, tf.float32)
def MyFunc(x, y):
  return x + y, x - y
# Building the graph.
a = tf.Constant([1.0])
b = tf.Constant([2.0])
c, d = MyFunc(a, b, name='mycall')

英文文档全文:

Decorator used to define TensorFlow functions.

Use this decorator to make a Python function usable directly as a TensorFlow
function.

The decorated function must add ops to the default graph and return zero or
more Tensor objects. Call the decorator with named arguments, one for each
argument of the function to decorate, with the expected type of the argument
as value.

For example if the function to decorate accepts two tf.float32 arguments
named x and y, call the decorator with:

@Defun(tf.float32, tf.float32)
def foo(x, y):
  ...

When you call the decorated function it will add call ops to the
default graph and adds the definition of the function into the
default graph. Because the addition of the function into the graph
is deferred, the decorator can be used anywhere in the program.

Any variables created inside of the function are hoisted into the outer graph.
Note that the variables are created in the variable scope that was active
during the first call to the function. Subsequent function calls will refer to
the same set of variables.

Definitions of functions are frozen in a graph as soon as the graph is used to
create a session. Therefore, nodes using the function must be created in the
graph before the corresponding session is created.

Example, but also see the [How To on functions].

# Defining the function.
@tf.Defun(tf.float32, tf.float32)
def MyFunc(x, y):
  return x + y, x - y
# Building the graph.
a = tf.Constant([1.0])
b = tf.Constant([2.0])
c, d = MyFunc(a, b, name='mycall')
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值