tensorflow.python.framework.function.Defun
文档路径(我使用的是anaconda3):
$CONDAHOME/lib/python3.5/site-packages/tensorflow/python/framework/function.py
用于定义 TensorFlow 函数的装饰器。
使用此装饰器使Python函数可以直接用作TensorFlow函数。
修饰函数必须将操作添加到默认的图并返回零个或多个Tensor
对象。使用命名参数调用装饰器,每个参数用于要装饰的函数的每个参数,参数的预期类型为值。
例如,如果要装饰的函数接受两个名为x
和y
的tf.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')