Deep Learning with Pytorch- neural network

Deep Learning with Pytorch: A 60 Minute Blitz

Neural Networks

神经网络

神经网络是使用 torch.nn 包构建的

现在我们对 autograd 有了一个初步的了解, nn 依赖 autograd 定义模型并且微分这些模型, 一个 nn.Module 包含神经网络的层, 和一个返回 output 的方法 forward(input).

查看这副图片, 图片中描绘的是用于分类数字图像的神经网络.
这是一个简单的 feed-forward network. 它接收input, 通过一层一层的将input传递几层, 然后给出输出.

以下是一个训练神经网络的典型步骤
1.定义一个有要学习参数 ( 权重 ) 的神经网络
2.在输入的数据集上迭代
3.通过神经网络处理输入
4.计算 loss ( 输出距离正确结果还差多少 )
5.反向传播梯度进入神经网络的参数
6.更新网络的权重,特别是使用下面的简单更新规则 weight = weight - learning_rate * gradient

Define the network

定义神经网络

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, 5*5 square convolution
        # kernel
        self.conv1 = nn.Conv2d(1, 6, 5)
        self.conv2 = nn.Conv2d(6, 16, 5)
        # an affine operation y = W*x + 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)

我们刚刚定义了 forward 函数, backward()(在backward中计算gradients) 函数是在使用 autograd 自动定义的. 我们可以在forward函数中看到对Tensor的任何操作

一个模型的可学习参数由 net.parameters() 返回

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

forward函数的输入是一个 autograd.Variable, 输出也是这样.
为了在 MNIST 上使用这个网络需要将dataset中获取的图像裁剪为32*32

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

清零所有参数梯度缓冲并且使用随机梯度反向传播

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

Note: 整个torch.nn包只支持mini-batch样本输入, 不支持一个单一的样本, 如果你只有一个单一的样本,可以使用input.unsqueeze(0)增加假的batch维度

Recap 回顾:

1.torch.Tensor: 一个多维数组

1. autograd.Variable: 封装一个Tensor并且记录应以与Tensor上的操作历史.有和Tensor同样的API接口,还有backward()函数和对tensor的梯度
1. nn.Module: 神经网络模型. 一种封装参数的方便方法
1. nn.Parameter: 一种Variable, 当作为一个特性赋值给一个Module时,被自动作为一个parameter注册
1. autograd.Function: 实现一个 autograd 操作 forward 和 backward 定义. 每一个Variable操作, 创建至少一个 Function 结点, 该结点连结创造这个Variable的所有函数并且编码他的历史.

Loss Function

一个loss function记录输入的对, 并且计算输出和目标之间差距的估计值.

nn包中有很多loss function, 最简单的loss function是 nn.MSELoss 计算目标和输出之间mean-square error

output = net(input)
target = Variable(torch.arange(1, 11))
target = target.view(1, -1)
criterion = nn.MSELoss()

loss = critetion(output, input)
print(loss)

现在,如果你在反向方向跟踪 loss, 使用.grad_fn, 就会看到计算过程的图. 因此,当我们调用loss.backward(),整幅图是对loss的微分,图中所有的Variable将会有一个.grad Variable, 随着梯度自增.

为了说明,使用下面几步backward

print(loss.grad_fn)    # MSELoss
print(loss.grad_fn.next_functions[0][0])
# Linear
print(loss.grad_fn.next_functions[0][0].next_function[0][0]) 
# Relu

Backprop

为了反向传播error我们要做的仅仅是 loss.backward(). 我们需要清理所有存在梯度,其他的梯度会随着已存在的梯度增加.

net.zero_grad()

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

loss.backward()

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

Update the weights

更新权重

实际中使用最简单的更新规则是随机梯度下降(SGD)
weight = weight - learning_rate * gradient
在包 torch.optium 中实现了不同更新规则

import torch.optim as optim

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

# in your training loop
optimizer.zero_grad()
output = net(input)
loss = criterion(output, target)
loss.backward()
optimizer.step()  # Does the update
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值