Pytorch入门——神经网络

来源:互联网 发布:中科院人工智能 编辑:程序博客网 时间:2024/05/18 02:29

上一篇博客对Pytorch包中的变量和梯度有了初步了解,接下来进入正题——用Pytorch中的torch.nn包实现神经网络。

1.Pytorch实现神经网络的典型训练过程

在这里以Lenet模型为例,由两个卷积层,两个池化层,以及两个全连接层组成。 卷积核大小为5*5,stride为1,采用MAX池化。以该网络分类数字图像为例:
这里写图片描述
Pytorch实现神经网络的典型训练过程如下:

  • 定义具有一些可学习参数(权重)的神经网络
  • 迭代输入数据
  • 通过网络处理输入
  • 计算损失
  • 将梯度传播回到网络参数中
  • 使用梯度下降更新网络权重, weight = weight - learning_rate * gradient

2.定义网络

Lenet模型的Pytorch代码如下:

class Net(nn.Module):    def __init__(self):        super(Net, self).__init__()        # 1 input image channel, 6 output channels, 5x5 square convolution kernel        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):        # Max pooling over a (2, 2) window        x = F.max_pool2d(F.relu(self.conv1(x)), (2, 2))        # If the size is a square you can only specify a single number        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:]  # all dimensions except the batch dimension        num_features = 1        for s in size:            num_features *= s        return num_featuresnet = 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 (400 -> 120)  (fc2): Linear (120 -> 84)  (fc3): Linear (84 -> 10))

只需定义forward函数,并backward自动使用函数autograd,可以在forward功能中使用任何Tensor操作。
用net.parameters()返回模型学习的参数

params = list(net.parameters())print(len(params))print(params[0].size())  # conv1's .weight

输出

10(6L, 1L, 5L, 5L)

前向传播的输入输出都是autograd.Variable

input = Variable(torch.randn(1, 1, 32, 32))out = net(input)print(out)

输出

Variable containing: 0.0809  0.0700  0.0478 -0.0280 -0.0281  0.1334 -0.0481  0.0195 -0.0522  0.1430[torch.FloatTensor of size 1x10]

将随机梯度的所有参数和backprops的梯度缓冲区置零:

net.zero_grad()out.backward(torch.randn(1, 10))

注意:torch.nn仅支持mini-batch,整个torch.nn软件包仅支持输入,这些输入是小批量样品,而不是单个样品。例如,nn.Conv2d将采用nSamples x nChannels x Height x Width4D Tensor。如果有一个样本,只需使用input.unsqueeze(0)来添加假批量维。

3.损失函数

损失函数采用(输出,目标)输入对,并计算估计输出距离目标距离的值。nn包下有几种不同的损失函数,具体参考官网提供的损失函数说明。一个简单的损失是:nn.MSELoss,用于计算输入和目标之间的平均平方误差。
例如

output = net(input)target = Variable(torch.arange(1, 11))  # a dummy target, for examplecriterion = nn.MSELoss()loss = criterion(output, target)print(loss)

输出

Variable containing: 38.1674[torch.FloatTensor of size 1]

4.反向传播

要反向传播误差,只需要用loss.backward(),需要清除现有的梯度,否则渐变将累积到现有的梯度。
如下调用loss.backward(),并且看看在conv1之前和之后的conv1的偏差梯度。

net.zero_grad()     # zeroes the gradient buffers of all parametersprint('conv1.bias.grad before backward')print(net.conv1.bias.grad)loss.backward()print('conv1.bias.grad after backward')print(net.conv1.bias.grad)

输出

conv1.bias.grad before backwardVariable containing: 0 0 0 0 0 0[torch.FloatTensor of size 6]conv1.bias.grad after backwardVariable containing:-0.1000 0.0343-0.1194-0.0136-0.0767 0.0224[torch.FloatTensor of size 6]

神经网络包包含形成深层神经网络、构建模块的各种模块和损失函数,官网提供一个完整的文档列表。

5.权重更新

实现中使用的最简单的更新规则是随机梯度下降(SGD)
weight = weight - learning_rate * gradient
python具体实现如下:

learning_rate = 0.01for f in net.parameters():    f.data.sub_(f.grad.data * learning_rate)

torch.optim提供了很多种更新方法,如SGD、nesterov - SGD、Adam、RMSProp等,使用起来很简单,如下:

import torch.optim as optim# create your optimizeroptimizer = optim.SGD(net.parameters(), lr=0.01)# in your training loop:optimizer.zero_grad()   # zero the gradient buffersoutput = net(input)loss = criterion(output, target)loss.backward()optimizer.step()    # Does the update
原创粉丝点击