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)。 xfunc 的输入,必须为LoDTensor类型; outfunc 的输出, 既可以是LoDTensor类型, 也可以是numpy数组。

    反向函数 backward_func 的输入依次为:前向输入 x 、前向输出 outout 的梯度。 如果 out 的某些变量没有梯度,则 backward_func 的相关输入变量为None。如果 x 的某些变量没有梯度,则用户应在 backward_func 中主动返回None。

    此功能还可用于调试正在运行的网络,可以通过添加没有输出的 py_func 运算,并在 func 中打印输入 x

    1. # 该示例展示了如何将LoDTensor转化为numpy数组,并利用numpy API来自定义一个OP
    2. import paddle.fluid as fluid
    3. import numpy as np
    4. def element_wise_add(x, y):
    5. # 必须先手动将LodTensor转换为numpy数组,否则无法支持numpy的shape操作
    6. x = np.array(x)
    7. y = np.array(y)
    8. if x.shape != y.shape:
    9. result = np.zeros(x.shape, dtype='int32')
    10. for i in range(len(x)):
    11. for j in range(len(x[0])):
    12. result[i][j] = x[i][j] + y[i][j]
    13. return result
    14. def create_tmp_var(name, dtype, shape):
    15. return fluid.default_main_program().current_block().create_var(
    16. def py_func_demo():
    17. start_program = fluid.default_startup_program()
    18. main_program = fluid.default_main_program()
    19. # 创建前向函数的输入变量
    20. x = fluid.data(name='x', shape=[2,3], dtype='int32')
    21. y = fluid.data(name='y', shape=[2,3], dtype='int32')
    22. output = create_tmp_var('output','int32', [3,1])
    23. # 输入多个LodTensor以list[Variable]或tuple(Variable)形式
    24. fluid.layers.py_func(func=element_wise_add, x=[x,y], out=output)
    25. exe=fluid.Executor(fluid.CPUPlace())
    26. exe.run(start_program)
    27. # 给program喂入numpy数组
    28. input1 = np.random.randint(1, 10, size=[2,3], dtype='int32')
    29. input2 = np.random.randint(1, 10, size=[2,3], dtype='int32')
    30. out = exe.run(main_program,
    31. feed={'x':input1, 'y':input2},
    32. fetch_list=[output.name])
    33. print("{0} + {1} = {2}".format(input1, input2, out))
    34. py_func_demo()
    35. # 参考输出:
    36. # [[5, 9, 9] + [[7, 8, 4] = [array([[12, 17, 13]