Neuarl Networks
使用torch.nn.Module来构建神经网络
一个nn.Module包含了各个层和一个forward方法,返回ouput
- 前馈神经网络:接受一个输入,然后一层一层地传递,最后输出计算结果
训练过程:
- 定义包含科学系参数(权重)神经网络
- 在数据集上迭代
- 通过神经网络处理输入
- 计算损失(输出结果和正确值差值大小)
- 将梯度反方向传播会网络的参数
- 更新网络的参数: weight = weight - learning_rate * gradient
# 定义网络
import torch
import torch.nn as nn
import torch.nn.functional as F
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
# 1 输入通道, 6 输出通道, 5x5卷积核
self.conv1 = nn.Conv2d(1, 6, 5)
self.conv2 = nn.Conv2d(6, 16, 5)
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)
x = x.view(-1, self.num_flat_features(x))
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = self.fc3(x)
return x
def num_flat_features(self, x):
size = x.size()[1:]
num_features = 1
for s in size:
num_features *= s
return num_features
if __name__ == '__main__':
model = Net()
print(model)
Net(
(conv1): Conv2d(1, 6, kernel_size=(5, 5), stride=(1, 1))
(conv2): Conv2d(6, 16, kernel_size=(5, 5), stride=(1, 1))
(fc1): Linear(in_features=400, out_features=120, bias=True)
(fc2): Linear(in_features=120, out_features=84, bias=True)
(fc3): Linear(in_features=84, out_features=10, bias=True)
)
模型中必须定义forward函数,backward函数(用来计算梯度)会被autograd自动创建,可以在forward函数中使用任何对Tensor的操作
# net.parameters() 返回可被学习的参数(权重)列表和值
params = list(model.parameters())
print(len(params))
print(params[0].size())
10
torch.Size([6, 1, 5, 5])
input = torch.randn(1, 1, 32, 32)
out = model(input)
print(out)
tensor([[-0.0278, -0.0444, -0.0038, 0.0215, 0.0452, 0.0473, 0.0622, -0.1564,
0.0825, 0.0806]], grad_fn=<AddmmBackward>)
# 将所有的参数的梯度缓存清零,然后进行随机梯度的反向传播
model.zero_grad()
out.backward(torch.randn(1, 10))
损失函数
一个损失函数接受一对(output, target)作为收入,计算一个值估计网络的输出和目标值相差多少
nn包中有很多不同的损失函数,nn.MSELoss是一个比较简单的损失函数,它计算输出值和目标间的均方误差
详情:address
output = model(input)
target = torch.randn(10)
target = target.view(1, -1)
criterion = nn.MSELoss()
loss = criterion(output, target)
print(loss)
tensor(0.5557, grad_fn=<MseLossBackward>)
print(loss.grad_fn) # MSELoss
print(loss.grad_fn.next_functions[0][0]) # Linear
print(loss.grad_fn.next_functions[0][0].next_functions[0][0]) # ReLU
<MseLossBackward object at 0x000001B89A3AE0C8>
<AddmmBackward object at 0x000001B8988909C8>
<AccumulateGrad object at 0x000001B89A308DC8>
反向传播
调用loss.backward获得反向传播的误差
在调用前需要清楚已存在的梯度,否则梯度将被累加到已存在的梯度
model.zero_grad() # 清除梯度
print('conv1.bias.grad before backward', model.conv1.bias.grad)
loss.backward()
print('conv1.bias.grad after backward', model.conv1.bias.grad)
conv1.bias.grad before backward tensor([0., 0., 0., 0., 0., 0.])
conv1.bias.grad after backward tensor([-0.0019, 0.0015, -0.0030, -0.0074, 0.0009, -0.0004])
更新权重
权重更新最简单的规则是随机梯度下降(SGD)
learning_rate = 0.01
for f in model.parameters():
f.data.sub_(f.grad.data * learning_rate)
import torch.optim as optim
optimizer = optim.SGD(model.parameters(), lr=0.01)
optimizer.zero_grad()
output = model(input)
loss = criterion(output, target)
loss.backward()
optimizer.step()