py_func
API属性:声明式编程(静态图)专用API
( func, x, out, backward_func=None, skip_vars_in_backward_input=None ) [源代码]
该自定义的Python OP的前向函数是 func
, 反向函数是 backward_func
。 Paddle将在前向部分调用 func
,并在反向部分调用 backward_func
(如果 backward_func
不是None)。 x
为 func
的输入,必须为LoDTensor类型; out
为 func
的输出, 既可以是LoDTensor类型, 也可以是numpy数组。
反向函数 backward_func
的输入依次为:前向输入 x
、前向输出 out
、 out
的梯度。 如果 out
的某些变量没有梯度,则 backward_func
的相关输入变量为None。如果 x
的某些变量没有梯度,则用户应在 backward_func
中主动返回None。
此功能还可用于调试正在运行的网络,可以通过添加没有输出的 py_func
运算,并在 func
中打印输入 x
。
# 该示例展示了如何将LoDTensor转化为numpy数组,并利用numpy API来自定义一个OP
import paddle.fluid as fluid
import numpy as np
def element_wise_add(x, y):
# 必须先手动将LodTensor转换为numpy数组,否则无法支持numpy的shape操作
x = np.array(x)
y = np.array(y)
if x.shape != y.shape:
result = np.zeros(x.shape, dtype='int32')
for i in range(len(x)):
for j in range(len(x[0])):
result[i][j] = x[i][j] + y[i][j]
return result
def create_tmp_var(name, dtype, shape):
return fluid.default_main_program().current_block().create_var(
def py_func_demo():
start_program = fluid.default_startup_program()
main_program = fluid.default_main_program()
# 创建前向函数的输入变量
x = fluid.data(name='x', shape=[2,3], dtype='int32')
y = fluid.data(name='y', shape=[2,3], dtype='int32')
output = create_tmp_var('output','int32', [3,1])
# 输入多个LodTensor以list[Variable]或tuple(Variable)形式
fluid.layers.py_func(func=element_wise_add, x=[x,y], out=output)
exe=fluid.Executor(fluid.CPUPlace())
exe.run(start_program)
# 给program喂入numpy数组
input1 = np.random.randint(1, 10, size=[2,3], dtype='int32')
input2 = np.random.randint(1, 10, size=[2,3], dtype='int32')
out = exe.run(main_program,
feed={'x':input1, 'y':input2},
fetch_list=[output.name])
print("{0} + {1} = {2}".format(input1, input2, out))
py_func_demo()
# 参考输出:
# [[5, 9, 9] + [[7, 8, 4] = [array([[12, 17, 13]