未验证 提交 c037d625 编写于 作者: Z Zhen Wang 提交者: GitHub

Update the demo of paddle.grad (#26498)

* update the demo codes of paddle.grad.
上级 c11c83fb
......@@ -375,16 +375,16 @@ def grad(outputs,
Examples 1:
.. code-block:: python
import paddle.fluid as fluid
import paddle
paddle.disable_static()
def test_dygraph_grad(create_graph):
with fluid.dygraph.guard():
x = fluid.layers.ones(shape=[1], dtype='float32')
x = paddle.ones(shape=[1], dtype='float32')
x.stop_gradient = False
y = x * x
# Since y = x * x, dx = 2 * x
dx = fluid.dygraph.grad(
dx = paddle.grad(
outputs=[y],
inputs=[x],
create_graph=create_graph,
......@@ -410,12 +410,11 @@ def grad(outputs,
Examples 2:
.. code-block:: python
import paddle.fluid as fluid
fluid.enable_dygraph()
import paddle
paddle.disable_static()
def test_dygraph_grad(grad_outputs=None):
x = fluid.layers.fill_constant(shape=[1], value=2.0, dtype='float32')
x = paddle.fill_constant(shape=[1], value=2.0, dtype='float32')
x.stop_gradient = False
y1 = x * x
......@@ -431,27 +430,27 @@ def grad(outputs,
# Therefore, the final result would be:
# dx = 2 * x * dy1 + 3 * dy2 = 4 * dy1 + 3 * dy2.
dx = fluid.dygraph.grad(
dx = paddle.grad(
outputs=[y1, y2],
inputs=[x],
grad_outputs=grad_outputs)[0]
return dx.numpy()
THREE = fluid.layers.fill_constant(shape=[1], value=3.0, dtype='float32')
FOUR = fluid.layers.fill_constant(shape=[1], value=4.0, dtype='float32')
grad_value = paddle.fill_constant(shape=[1], value=4.0, dtype='float32')
# dy1 = [1], dy2 = [1]
print(test_dygraph_grad(None)) # [7.]
# dy1 = [1], dy2 = [4]
print(test_dygraph_grad([None, FOUR])) # [16.]
print(test_dygraph_grad([None, grad_value])) # [16.]
# dy1 = [4], dy2 = [1]
print(test_dygraph_grad([FOUR, None])) # [19.]
print(test_dygraph_grad([grad_value, None])) # [19.]
# dy1 = [3], dy2 = [4]
print(test_dygraph_grad([THREE, FOUR])) # [24.]
grad_y1 = paddle.fill_constant(shape=[1], value=3.0, dtype='float32')
print(test_dygraph_grad([grad_y1, grad_value])) # [24.]
'''
def check_in_out(in_out_list, name):
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册