本文参考书为《Dive Into Pytorch》
import torch # 引入包名
x = torch.ones(2, 2, requires_grad=True) # 创建一个2*2的矩阵并且程序记录该张量的所有操作
y = x + 2
z = y * y * 3
out = z.mean()
print(x,y,z,out)
tensor([[1., 1.],
[1., 1.]], requires_grad=True)
tensor([[3., 3.],
[3., 3.]], grad_fn=<AddBackward0>)
tensor([[27., 27.],
[27., 27.]], grad_fn=<MulBackward0>)
tensor(27., grad_fn=<MeanBackward0>)
out.backward() #此时out是一个数,是标量,因此可以直接调用backward函数
print(x.grad)
tensor([[4.5000, 4.5000],
[4.5000, 4.5000]])
若out
是个张量,则backward
函数需要传入一个与out
同型的张量。具体可以参考backward参数
out2=x.sum() #out2仍然是标量
print(out2)
tensor(4., grad_fn=<SumBackward0>)
out2.backward()
print(x.grad)
tensor([[5.5000, 5.5000],
[5.5000, 5.5000]])
x.grad
是累积的,第一次是4.5,第二次导数是1,加起来就是5.5
out3=x.sum()
x.grad.data.zero_()
out3.backward() # 清零x.grad
print(x.grad)
tensor([[1., 1.],
[1., 1.]])
x = torch.tensor([1.0, 2.0, 3.0, 4.0], requires_grad=True)
y = 2 * x
z = y.view(2, 2)
print(z)
tensor([[2., 4.],
[6., 8.]], grad_fn=<ViewBackward0>)
v = torch.tensor([[1.0, 0.1], [0.01, 0.001]], dtype=torch.float)
z.backward(v)# 传入一个同形矩阵v从而对z的各个变量进行加权求和,得到标量后,才能进行梯度计算
print(x.grad)
tensor([2.0000, 0.2000, 0.0200, 0.0020])
x = torch.tensor(1.0, requires_grad=True)
y1 = x ** 2
with torch.no_grad():
y2 = x ** 3
y3 = y1 + y2
y3.backward()
print(x.grad)
tensor(2.)
本来 y 3 y_3 y3= x 3 x^3 x3+ x 2 x^2 x2,但 x 3 x^3 x3被中断了梯度追踪,所以不会累积到x.grad中