PyTorch 搭建一个简单的神经网络【详细附代码】
神经网络(Neural Network --nn)可以使用torch.nn包来构建神经网络。之前已经介绍了autograd包,nn包则依赖于autograd包来定义模型并对它们求导。nn.Module包含层,以及返回output的方法forward(input)。例如:一个数图像识别这是一个简单的前馈神经网络(feed-forward network)。它接受一个输入,然后将它送入下一层,一层接一
神经网络(Neural Network --nn)
可以使用torch.nn
包来构建神经网络。之前已经介绍了autograd
包,nn
包则依赖于autograd
包来定义模型并对它们求导。nn.Module
包含层,以及返回output
的方法forward(input)
。
例如:一个数图像识别
这是一个简单的前馈神经网络(feed-forward network)。它接受一个输入,然后将它送入下一层,一层接一层的传递,最后给出输出.
1. 一个神经网络的训练过程如下:
- 定义包含一些可学习参数(或权重)的神经网络
- 遍历输入数据集
- 通过网络处理输入
- 计算loss(输出和正确答案的距离)
- 将梯度反向传播给网络的参数
- 更新网络的权重,一般使用一个简单的规则:
weight = weight - learning_rate * gradient
2. 定义网络:
import torch
import torch.nn as nn
import torch.nn.functional as F
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
# 输入图像channel:1;输出channel:6;5x5卷积核 6个
self.conv1 = nn.Conv2d(1, 6, 5)
self.conv2 = nn.Conv2d(6, 16, 5)
# an affine operation: 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):
# 2x2 Max pooling,先卷积+relu,再2 x 2下采样
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
net = Net()
print(net)
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
函数,就可以使用autograd
为您自动定义backward
函数(计算梯度)。 您可以在forward
函数中使用任何张量操作。
模型的可学习参数通过net.parameters()
返回:
params = list(net.parameters())
print(len(params))
print(params[0].size()) # conv1's .weight
10
torch.Size([6, 1, 5, 5])
2.1 随机输入,查看输出
让我们尝试一个32x32随机输入。 注意:该网络的预期输入大小(LeNet)为32x32。 要在 MNIST 数据集上使用此网络,请将图像从数据集中调整为32x32.
input = torch.randn(1, 1, 32, 32)
out = net(input)
print(out)
tensor([[-0.1221, -0.0510, -0.1360, -0.0879, 0.0333, 0.0496, 0.0247, -0.0319,
0.0865, -0.0089]], grad_fn=<AddmmBackward>)
注意:这里的张量有4维
- dim0:样本个数n
- dim1:通道数D
- dim2:图片高度H
- dim3:图片宽度W
2.2 梯度清零并随机化梯度
使用随机梯度将所有参数和反向传播的梯度缓冲区归零:
net.zero_grad()
out.backward(torch.randn(1, 10)) # out的大小是1x10的
注意:
torch.nn
仅支持小批量。 整个torch.nn
包仅支持作为微型样本而不是单个样本的输入。
例如,nn.Conv2d
将采用nSamples x nChannels x Height x Width
的 4D 张量。
如果您只有一个样本,只需使用input.unsqueeze(0)
添加一个假批量尺寸。
3. 损失函数
损失函数采用一对(输出,目标)输入,并计算一个值,该值估计输出与目标之间的距离。
nn
包下有几种不同的损失函数。 一个简单的损失是:nn.MSELoss
,它计算输入和目标之间的均方误差。
output = net(input) # 网络计算出来的值
target = torch.randn(10) # a dummy target, for example 真值
target = target.view(1, -1) # make it the same shape as output #变成行向量
criterion = nn.MSELoss()
loss = criterion(output, target)
print(loss)
tensor(0.8648, grad_fn=<MseLossBackward>)
现在,如果使用.grad_fn
属性向后跟随loss
,您将看到一个计算图,如下所示:
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 0x00000144AAB8C5C8>
<AddmmBackward object at 0x00000144AAB9CE88>
<AccumulateGrad object at 0x00000144AAB9CF88>
4. 反向传播
我们只需要调用loss.backward()
来反向传播误差。我们需要清零现有的梯度,否则梯度将会与已有的梯度累加。
现在,我们将调用loss.backward()
,并查看conv1层的偏置(bias)在反向传播前后的梯度。
net.zero_grad() # 清零所有参数(parameter)的梯度缓存
print('反向传播前的梯度')
print(net.conv1.bias.grad)
loss.backward()
print('反向传播后的梯度')
print(net.conv1.bias.grad)
反向传播前的梯度
tensor([0., 0., 0., 0., 0., 0.])
反向传播后的梯度
tensor([-0.0132, 0.0018, 0.0105, -0.0136, -0.0132, 0.0027])
5.更新权重
为了简单,有现成的优化包:torch.optim
import torch.optim as optim
# create your optimizer
optimizer = optim.SGD(net.parameters(), lr=0.01)
# 清除梯度
optimizer.zero_grad()
output = net(input)
loss = criterion(output, target) # loss用的是交叉熵
loss.backward()
# 更新权重
optimizer.step()
到此,我们的网络已经搭建成功,下一步是训练网络。
参考:PyTorch中文文档
更多推荐
所有评论(0)