1 . 在 Tensor 上的所有操作,autograd 都能为它们自动提供微分,避免了手动计算导数的复杂过程,只需要设置 tensor.requires_grad=True 即可。

Input:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import torch as t

x = t.ones(2, 2, requires_grad=True)

# 上一步等价于
# x = t.ones(2, 2)
# x.requires_grad = True

print(x)

y = x.sum()
print(y)

print(y.grad_fn)

y.backward() # 反向传播计算梯度
print(x.grad)

Output:

grad 在反向传播过程中是累加的,每一次运行反向传播,梯度都会累加之前的梯度,因此反向传播之前需要把梯度清零。

Input:

1
2
3
4
5
6
7
8
9
10
y.backward()
print(x.grad)
y.backward()
print(x.grad)

# 以下划线结束的函数是 inplace 操作,会修改自身的值
x.grad.data.zero_()

y.backward()
print(x.grad)

Output:



2 . torch.nn 是专门为神经网络设计的模块化接口,nn 构建于 Autograd 之上,可用来定义和运行网络,nn.Modulenn 中最重要的类,可以把它看成是一个网络的封装,包含网络定义以及 forward 方法,调用 forward(input) 方法,可返回前向传播的结果,下面是 LeNet 的实现。

Input:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import torch.nn as nn
import torch.nn.functional as F

class Net(nn.Module):
def __init__(self):
# nn.Module 子类的函数必须在构造函数中执行父类的构造函数
# 下式等价于 nn.Module.__init__(self)
super(Net, self).__init__()

# 卷积层 1 表示输入图片为单通道,6 表示输出通道数,5 表示卷积核为 5*5
self.conv1 = nn.Conv2d(1, 6, 5)
# 卷积层
self.conv2 = nn.Conv2d(6, 16, 5)
# 仿射层/全连接层, y=Wx+b
self.fc1 = nn.Linear(16*5*5, 120)
self.fc2 = nn.Linear(120, 84)
self.fc3 = nn.Linear(84, 10)

def forward(self, x):
# 卷积 --> 激活 --> 池化
x = F.max_pool2d(F.relu(self.conv1(x)), (2, 2))
x = F.max_pool2d(F.relu(self.conv2(x)), 2)
# reshape, -1 表示自适应
x = x.view(x.size()[0], -1)
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = self.fc3(x)
return x

net = Net()
print(net)

Output:

只要在 nn.Module 的子类中定义了 forward 函数,backward 函数就会自动被实现(利用 autograd),网络的可学习参数通过 net.parameters() 返回,net.named_parameters 可同时返回可学习的参数和名称。

Input:

1
2
3
4
5
params = list(net.parameters())
print(len(params))

for name, parameters in net.named_parameters():
print(name, ':', parameters.size())

Output:

forward 函数的输入和输出都是 Tensor。

Input:

1
2
3
input = t.randn(1, 1, 32, 32)
out = net(input)
print(out.size())

Output:

1
2
net.zero_grad()   # 所有参数的梯度清零
out.backward(t.ones(1, 10)) # 反向传播

torch.nn 只支持 mini-batches,不支持一次只输入一个样本,即一次必须是一个 batch,但如果只想输入一个样本,则用 input.unsqueeze(0) 将 batch_size 设为 1。

3 . nn 实现了神经网络中大多数的损失函数,例如 nn.MSELoss 用来计算均方误差,nn.CrossEntropyLoss 用来计算交叉熵损失。

Input:

1
2
3
4
5
output = net(input)
target = t.arange(0, 10).view(1, 10)
criterion = nn.MSELoss()
loss = criterion(output, target.float())
print(loss)

Output:

torch.LongTensor —-> torch.FloatTensor: tensor.float()

torch.FloatTensor —-> torch.LongTensor: tensor.long()

Input:

1
2
3
4
5
6
7
# 运行 backward,观察调用之前和调用之后的 grad
net.zero_grad() # 把 net 中所有可学习参数的梯度清零
print('反向传播之前 conv1.bias 的梯度: ')
print(net.conv1.bias.grad)
loss.backward()
print('反向传播之后 conv1.bias 的梯度: ')
print(net.conv1.bias.grad)

Output:

4 . 在反向传播计算完所有参数的梯度之后,还需要使用优化方法来更新网络的权重和参数,例如随机梯度下降(SGD)的更新策略手动实现如下:

1
2
3
learning_rate = 0.01
for f in net.parameters():
f.data.sub_(f.data * learning_rate)

torch.optim 中实现了深度学习中绝大多数的优化方法,例如 RMSProp、Adam、SGD 等。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import torch.optim as optim

# 新建一个优化器,指定要调整的参数和学习率
optimizer = optim.SGD(net.parameters(), lr=0.01)

# 在训练过程中
# 先梯度清零(与 net.zero_grad() 效果一样)
optimizer.zero_grad()

# 计算损失
output = net(input)
loss = criterion(output, target.float())

# 反向传播
loss.backward()

# 更新参数
optimizer.step()

笔记来源:《pytorch-book》