沐神深度学习paddle自动求导实现

import paddle

x = paddle.to_tensor([i for i in range(4)], dtype='float32', stop_gradient=False)
x

Tensor(shape=[4], dtype=float32, place=Place(gpu:0), stop_gradient=False, [0., 1., 2., 3.])

paddle.is_grad_enabled()

True

y = 2 * paddle.dot(x, x)
y

Tensor(shape=[1], dtype=float32, place=Place(gpu:0), stop_gradient=False, [28.])

paddle.autograd.backward(y, retain_graph=True)
x.grad

Tensor(shape=[4], dtype=float32, place=Place(gpu:0), stop_gradient=False, [0. , 4. , 8. , 12.])

x.grad == 4 * x

Tensor(shape=[4], dtype=bool, place=Place(gpu:0), stop_gradient=True, [True, True, True, True])

x.clear_grad()
y = x.sum()
paddle.autograd.backward(y, retain_graph=True)
x.grad

Tensor(shape=[4], dtype=float32, place=Place(gpu:0), stop_gradient=False, [1., 1., 1., 1.])

x.clear_grad()
y = x * x
paddle.autograd.backward(y.sum(), retain_graph=True)
x.grad

Tensor(shape=[4], dtype=float32, place=Place(gpu:0), stop_gradient=False, [0., 2., 4., 6.])

将计算移出记录的计算图
x.clear_grad()
y = x * x
u = y.detach()
z = u * x

paddle.autograd.backward(z.sum(), retain_graph=True)
x.grad == u

Tensor(shape=[4], dtype=bool, place=Place(gpu:0), stop_gradient=True, [True, True, True, True])

x.clear_grad()
paddle.autograd.backward(y.sum(), retain_graph=True)
x.grad == 2 * x

Tensor(shape=[4], dtype=bool, place=Place(gpu:0), stop_gradient=True, [True, True, True, True])

复杂工作流自动求导
def f(a):
    b = a * 2
    while b.norm() < 1000:
        b = b * 2
    if b.sum() > 0:
        c = b
    else:
        c = 100 * b
    return c  

a = paddle.randn(shape=((10,10)),dtype='float32')
a.stop_gradient = False
d = f(a)
paddle.autograd.backward(d, retain_graph=True)
  
a.grad == d / a

Tensor(shape=[10, 10], dtype=bool, place=Place(gpu:0), stop_gradient=True,
[[True, True, True, True, True, True, True, True, True, True],
[True, True, True, True, True, True, True, True, True, True],
[True, True, True, True, True, True, True, True, True, True],
[True, True, True, True, True, True, True, True, True, True],
[True, True, True, True, True, True, True, True, True, True],
[True, True, True, True, True, True, True, True, True, True],
[True, True, True, True, True, True, True, True, True, True],
[True, True, True, True, True, True, True, True, True, True],
[True, True, True, True, True, True, True, True, True, True],
[True, True, True, True, True, True, True, True, True, True]])

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值