Deep Learning with Pytorch- neural network

今天药忘吃喽~ 2024-05-24 03:51 216阅读 0赞

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

定义神经网络

  1. import torch
  2. from torch.autograd import Variable
  3. import torch.nn as nn
  4. import torch.nn.functional as F
  5. class Net(nn.Module):
  6. def __init__(self):
  7. super(Net, self).__init__()
  8. # 1 input image channel, 6 output channels, 5*5 square convolution
  9. # kernel
  10. self.conv1 = nn.Conv2d(1, 6, 5)
  11. self.conv2 = nn.Conv2d(6, 16, 5)
  12. # an affine operation y = W*x + b
  13. self.fc1 = nn.Linear(16 * 5 * 5, 120)
  14. self.fc2 = nn.Linear(120, 84)
  15. self.fc3 = nn.Linear(84, 10)
  16. def forward(self, x):
  17. # Max pooling over a (2, 2) window
  18. x = F.max_pool2d(F.relu(self.conv1(x)), (2, 2))
  19. # if the size is a square you can only specify a single number
  20. x = F.max_pool2d(F.relu(self.conv2(x)), 2)
  21. x = x.view(-1, self.num_flat_features(x))
  22. x = F.relu(self.fc1(x))
  23. x = F.relu(self.fc2(x))
  24. x = self.fc3(x)
  25. return x
  26. def num_flat_features(self, x):
  27. size = x.size()[1:]
  28. # all dimensions except the batch dimension
  29. num_features = 1
  30. for s in size:
  31. num_features *= s
  32. return num_features
  33. net = Net()
  34. print(net)

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

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

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

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

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

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

  1. net.zero_grad()
  2. 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的梯度

  2. nn.Module: 神经网络模型. 一种封装参数的方便方法

  3. nn.Parameter: 一种Variable, 当作为一个特性赋值给一个Module时,被自动作为一个parameter注册

  4. autograd.Function: 实现一个 autograd 操作 forward 和 backward 定义. 每一个Variable操作, 创建至少一个 Function 结点, 该结点连结创造这个Variable的所有函数并且编码他的历史.

Loss Function

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

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

  1. output = net(input)
  2. target = Variable(torch.arange(1, 11))
  3. target = target.view(1, -1)
  4. criterion = nn.MSELoss()
  5. loss = critetion(output, input)
  6. print(loss)

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

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

  1. print(loss.grad_fn) # MSELoss
  2. print(loss.grad_fn.next_functions[0][0])
  3. # Linear
  4. print(loss.grad_fn.next_functions[0][0].next_function[0][0])
  5. # Relu

Backprop

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

  1. net.zero_grad()
  2. print('conv1.bias.grad before backward')
  3. print(net.conv1.bias.grad)
  4. loss.backward()
  5. print('conv2.bias.grad after backward')
  6. print(net.conv1.bias.grad)

Update the weights

更新权重

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

  1. import torch.optim as optim
  2. # create your optimizer
  3. optimizer = optim.SGD(net.parameters(), lr=0.01)
  4. # in your training loop
  5. optimizer.zero_grad()
  6. output = net(input)
  7. loss = criterion(output, target)
  8. loss.backward()
  9. optimizer.step() # Does the update

发表评论

表情:
评论列表 (有 0 条评论,216人围观)

还没有评论,来说两句吧...

相关阅读