Autograd: 自动求导机制
PyTorch 中所有神经网络的核心是 autograd 包。 我们先简单介绍一下这个包,然后训练第一个简单的神经网络。
autograd包为张量上的所有操作提供了自动求导。 它是一个在运行时定义的框架,这意味着反向传播是根据你的代码来确定如何运行,并且每次迭代可以是不同的。
示例
张量(Tensor)
torch.Tensor是这个包的核心类。如果设置 .requires_grad 为 True,那么将会追踪所有对于该张量的操作。 当完成计算后通过调用 .backward(),自动计算所有的梯度, 这个张量的所有梯度将会自动积累到 .grad 属性。
要阻止张量跟踪历史记录,可以调用.detach()方法将其与计算历史记录分离,并禁止跟踪它将来的计算记录。
为了防止跟踪历史记录(和使用内存),可以将代码块包装在with torch.no_grad():中。 在评估模型时特别有用,因为模型可能具有requires_grad = True的可训练参数,但是我们不需要梯度计算。
在自动梯度计算中还有另外一个重要的类Function.
Tensor and Function are interconnected(互相连接) and build up an acyclic(非循环的) graph, that encodes a complete history of computation. Each tensor has a .grad_fn attribute that references a Function that has created the Tensor (except for Tensors created by the user - their grad_fn is None).
Tensor 和 Function互相连接并生成一个非循环图,它表示和存储了完整的计算历史。 每个张量都有一个.grad_fn属性,这个属性引用了一个创建了Tensor的Function(除非这个张量是用户手动创建的,即,这个张量的 grad_fn 是 None)。
如果需要计算导数,你可以在Tensor上调用.backward()。 如果Tensor是一个标量(即它包含一个元素数据)则不需要为backward()指定任何参数, 但是如果它有更多的元素,你需要指定一个gradient 参数来匹配张量的形状。
import torch
x = torch.ones(2, 2, requires_grad=True)
print(x)
y = x + 2
print(y)
print(y.grad_fn)
z = y * y * 3
out = z.mean()
print(z)
print(out)
a = torch.randn(2, 2)
a = ((a * 3) / (a - 1))
print(a.requires_grad) # .requires_grad_( ... ) 可以改变现有张量的 requires_grad属性。 如果没有指定的话,默认输入的flag是 False。
a.requires_grad_(True)
print(a.requires_grad)
b = (a * a).sum()
print(b.grad_fn)
print(out.backward()) # 常量没有梯度 None
print(x.grad)
x = torch.randn(3, requires_grad=True)
print(x)
y = x * 2
print(y)
print(y.data)
'''
input:输入tensor
p (int, float, inf, -inf, 'fro', 'nuc', optional):范数计算中的幂指数值。默认为'fro'
dim (int,2-tuple,2-list, optional): 指定计算的维度。如果是一个整数值,向量范数将被计算;如果是一个大小为2的元组,矩阵范数将被计算;如果为None,当输入tensor只有两维时矩阵计算矩阵范数;当输入只有一维时则计算向量范数。如果输入tensor超过2维,向量范数将被应用在最后一维
keepdim(bool,optional):指明输出tensor的维度dim是否保留。如果dim=None或out=None,则忽略该参数。默认值为False,不保留
out(Tensor, optional):tensor的输出。如果dim=None或out=None,则忽略该参数。
dtype(torch.dtype,optional):指定返回tensor的期望数据类型。如果指定了该参数,在执行该操作时输入tensor将被转换成 :attr:’dtype’
1)如果不指明p,则是计算Frobenius范数:
2)p = 'inf',则是求出矩阵或向量中各项元素绝对值中的最大值
'''
while y.data.norm() < 1000: # Frobenius范数小于1000一直乘3
print(y.data.norm())
y = y * 3
print(y)
gradients = torch.tensor([0.1, 1.0, 0.0001], dtype=torch.float)
y.backward(gradients)
print(x.grad)
print(x.requires_grad)
print((x ** 2).requires_grad)
# 如果.requires_grad=True但是你又不希望进行autograd的计算, 那么可以将变量包裹在 with torch.no_grad()中:
with torch.no_grad():
print((x ** 2).requires_grad)
D:\Python\python.exe D:/PyCharm/Workspace/学习pytorch/自动求导.py
tensor([[1., 1.],
[1., 1.]], requires_grad=True)
tensor([[3., 3.],
[3., 3.]], grad_fn=<AddBackward0>)
<AddBackward0 object at 0x0000029AE5619860>
tensor([[27., 27.],
[27., 27.]], grad_fn=<MulBackward0>)
tensor(27., grad_fn=<MeanBackward0>)
False
True
<SumBackward0 object at 0x0000029AE5619898>
None
tensor([[4.5000, 4.5000],
[4.5000, 4.5000]])
tensor([-1.1421, 0.1596, -0.6421], requires_grad=True)
tensor([-2.2843, 0.3193, -1.2843], grad_fn=<MulBackward0>)
tensor([-2.2843, 0.3193, -1.2843])
tensor(2.6399)
tensor(7.9197)
tensor(23.7591)
tensor(71.2774)
tensor(213.8323)
tensor(641.4968)
tensor([-1665.2258, 232.7656, -936.2195], grad_fn=<MulBackward0>)
tensor([1.4580e+02, 1.4580e+03, 1.4580e-01])
True
True
False
Process finished with exit code 0