2.4.1 计算梯度

import torch

x=torch.arange(4.0,requires_grad=True)
print(x)
# 输出:
# tensor([0., 1., 2., 3.], requires_grad=True)

y = 2 * torch.dot(x, x)
print(y)
# 输出:
# tensor(28., grad_fn=<MulBackward0>)

# y是关于x的导数,这里求y关于x的导数,并把得到的每个导数值存到x.grad中
y.backward()
print(x.grad)

# 将梯度清零,以免累加
x.grad.zero_()
print(x.grad)
# 输出:
# tensor([0., 0., 0., 0.])

y = x.sum()
# y是关于x的导数,这里求y关于x的导数,并把得到的每个导数值存到x.grad中
y.backward()
print(x.grad)
# 输出:
# tensor([1., 1., 1., 1.])

 

posted on 2022-11-01 15:14  yc-limitless  阅读(17)  评论(0编辑  收藏  举报