新手教程
- 60分钟快速入门Pytorch
- Pytorch是什么?
- Autograd:自动分化
- 神经网络
- 训练分类器
60分钟快速入门Pytorch
- 张量
- Autograd求导
- nn 包
- 多GPU示例
PyTorch使用Torch模型
- 学习PyTorch与实例
学习PyTorch与实例
可以使用torch.nn
包构建神经网络。
现在你已经看到了autograd
,nn
取决于autograd
定义模型并区分它们。一个nn.Module
包含图层,一个forward(input)
返回的方法output
。
例如,看看这个网络分类数字图像:
这是一个简单的前馈网络。它需要输入,一个接一个地将它提供多个层,然后最后给出输出。
神经网络的典型训练过程如下:
- 定义具有一些可学习参数(或权重)的神经网络
- 迭代输入数据集
- 通过网络处理输入
- 计算损失(输出距离是正确的)
- 传播梯度回到网络的参数
- 更新网络的权重,通常使用简单的更新规则:
weight = weight - learning_rate * gradient
定义网络
我们来定义这个网络:
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)
输出:
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
torch.Size([6, 1, 5, 5])
输入输出都是autograd.Variable
input = Variable(torch.randn(1, 1, 32, 32))
out = net(input)
print(out)
输出:
Variable containing:
0.1257 -0.0564 -0.0549 -0.1289 0.1114 0.0916 0.0308 0.0477 -0.1268 -0.0780
[torch.FloatTensor of size 1x10]