机器学习与计算机视觉

Pytorch入门学习(三):Neural Networks

2018-01-06  本文已影响5002人  与阳光共进早餐

未经允许,不得转载,谢谢~~

我们现在已经对autograd包有了一个基本的认识,现在来学习一下实现神经网络的包torch.nn.

Neural Networks

以下是一个对数字图像进行分类的网络结构图:


网络的结构在图中可以明显的看出来了,接受输入图片,依次经过不同的网络层,最后得到输出.

对于神经网络的典型处理如下所示:

  1. 定义待可学习参数的网络结构;
  2. 数据集输入;
  3. 对输入进行处理,主要体现在网络的前向传播;
  4. 计算loss function;
  5. 反向传播求梯度;
  6. 根据梯度改变参数值,最简单的实现方式为:
    weight = weight - learning_rate * gradient

Define the network

用pytorch来实现上述网络结构的定义.

import torch
from torch.autograd import Variable
import torch.nn as nn
import torch.nn.functional as F


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_features


net = Net()
print(net)

最后的输出结果为:


learn more about the network

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

以上代码段实现将该神经网络的可学习参数都放到params中,并且输出了第一层conv的参数大小.

结果如下:



可以看到conv1的参数大小为(6,1,5,5)与网络结构相符合.

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

note

loss function

如下所示:

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

loss = criterion(output, target)
print(loss)

输出结果如下所示:


沿着loss的反向传播方向,依次用.grad_fn属性,就可以得到如下所示的计算图.

input -> conv2d -> relu -> maxpool2d -> conv2d -> relu -> maxpool2d
      -> view -> linear -> relu -> linear -> relu -> linear
      -> MSELoss
      -> loss

所以当我们调用loss.backward()函数的时候,整张图都被一次计算误差,所有Variable的.grad属性会被累加.

以下几条语句对反向求梯度做了解释:

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

结果如下所示:


Backprop

net.zero_grad()     # zeroes the gradient buffers of all parameters

print('conv1.bias.grad before backward')
print(net.conv1.bias.grad)

loss.backward()

print('conv1.bias.grad after backward')
print(net.conv1.bias.grad)

输出结果如下所示:


Update the weights

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

# create your optimizer
optimizer = optim.SGD(net.parameters(), lr=0.01)

# in your training loop:
optimizer.zero_grad()   # zero the gradient buffers
output = net(input)
loss = criterion(output, target)
loss.backward()
optimizer.step()    # Does the update

more

更多关于torch.nn模块及损失函数的信息戳这里哦~

回顾梳理

之前博客内容

本次博客内容

上一篇 下一篇

猜你喜欢

热点阅读