Pytorch学习笔记(二)

神经网络

可以使用torch.nn包构造神经网络
在这里插入图片描述
它是一个简单的前馈网络。它接受输入,一个接一个地通过几个层输入,然后最终给出输出。

神经网络的典型训练程序如下:

定义具有一些可学习参数(或权重)的神经网络
迭代输入数据集
通过网络处理输入
计算损失(输出距离正确多远)
将渐变传播回网络参数
通常使用简单的更新规则更新网络权重: 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 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)

在这里插入图片描述
我们只需要定义forward,然后backward函数将会自动定义为我们完成autograd,模型的可学习参数由net.parameters()返回。

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

10
torch.Size([6, 1, 5, 5])

让我们尝试一个随机的32x32输入。注意:此网络(LeNet)的预期输入大小为32x32。要在MNIST数据集上使用此网络,请将数据集中的图像调整为32x32。

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

在这里插入图片描述
使用随机梯度将所有参数和反向的梯度缓冲区归零:

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

Loss Function

损失函数采用(输出,目标)输入对,并计算估计输出距目标的距离的值。

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)

在这里插入图片描述

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)

conv1.bias.grad before backward
tensor([0., 0., 0., 0., 0., 0.])
conv1.bias.grad after backward
tensor([-0.0122, -0.0004, -0.0031, -0.0044, -0.0003, -0.0003])

Update the weights

实践中使用的最简单的更新规则是随机梯度下降(SGD):在这里插入图片描述

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

但是,当使用神经网络时,我们希望使用各种不同的更新规则,例如SGD,Nesterov-SGD,Adam,RMSProp等。为了实现这一点,构建了一个小包:torch.optim它实现了所有这些方法。使用它非常简单:

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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值