# 自动求导 动手学深度学习 pytorch

``````import torch

x = torch.arange(4.0)
x
``````
``````tensor([0., 1., 2., 3.])
``````
``````x.requires_grad_(True) # x = torch.arange(4.0, requires_grad=True)
``````
``````y = 2 * torch.dot(x, x)
y
``````
``````tensor(28., grad_fn=<MulBackward0>)
``````
``````y.backward()
``````
``````tensor([ 0.,  4.,  8., 12.])
``````
``````x.grad == 4 * x
``````
``````tensor([True, True, True, True])
``````
``````x.grad.zero_()
y = x.sum()
y.backward()
``````
``````tensor([1., 1., 1., 1.])
``````
``````x.grad.zero_()
y = x * x
y.sum().backward()
``````
``````tensor([0., 2., 4., 6.])
``````
``````x.grad.zero_()
y = x * x
u = y.detach()
z = u * x

z.sum().backward()
``````
``````tensor([True, True, True, True])
``````
``````x.grad.zero_()
y.sum().backward()
``````
``````tensor([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

d = f(a)
d.backward()

``````
``````tensor(True)
``````
``````bb = torch.arange(4.0)
print(bb)
bbn = bb.norm()
print(bbn)
``````
``````tensor([0., 1., 2., 3.])
tensor(3.7417)
``````

`norm()` 函数表示每个数字的平方之和 开根号 `(0 ** 2 + 1 ** 2 + 2 ** 2 + 3 ** 2) ^(1/2)`

# 参考

https://www.bilibili.com/video/BV1KA411N7Px

THE END

)">