Automatically guide hands-on deep learning pytorch

insert image description here
insert image description here
insert image description here
insert image description here
insert image description here
insert image description here
insert image description here
insert image description here
insert image description here
insert image description here
insert image description here
insert image description here

example:

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)
x.grad
y = 2 * torch.dot(x, x)
y
tensor(28., grad_fn=<MulBackward0>)
y.backward()
x.grad
tensor([ 0.,  4.,  8., 12.])
x.grad == 4 * x
tensor([True, True, True, True])
x.grad.zero_()
y = x.sum()
y.backward()
x.grad
tensor([1., 1., 1., 1.])
x.grad.zero_()
y = x * x
y.sum().backward()
x.grad
tensor([0., 2., 4., 6.])
x.grad.zero_()
y = x * x
u = y.detach()
z = u * x

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

a = torch.randn(size=(), requires_grad=True)
d = f(a)
d.backward()

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

norm()The function expresses the root of the sum of the squares of each number(0 ** 2 + 1 ** 2 + 2 ** 2 + 3 ** 2) ^(1/2)

refer to

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

Guess you like

Origin blog.csdn.net/zgpeace/article/details/123650973