神经网络的典型训练过程如下:
- 定义具有一些可学习参数(或权重)的神经网络
- 遍历输入数据集
- 通过网络处理输入
- 计算损失(输出正确的距离有多远)
- 将梯度传播回网络参数
- 通常使用简单的更新规则来更新网络的权重:
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, 3x3 square convolution
# kernel
self.conv1 = nn.Conv2d(1, 6, 3)
self.conv2 = nn.Conv2d(6, 16, 3)
# an affine operation: y = Wx + b
self.fc1 = nn.Linear(16 * 6 * 6, 120) # 6*6 from image dimension
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)
通常,当您必须处理图像,文本,音频或视频数据时,可以使用将数据加载到numpy数组中的标准python包。然后,您可以将此数组转换为torch.*Tensor
。
- 对于图像,Pillow,OpenCV等软件包很有用
- 对于音频,请使用scipy和librosa等软件包
- 对于文本,基于Python或Cython的原始加载,或者NLTK和SpaCy很有用
具体地,对于视觉,我们已经创建了一个叫做 torchvision
,其中有对普通数据集如Imagenet,CIFAR10,MNIST等和用于图像数据的变压器,即,数据装载机 torchvision.datasets
和torch.utils.data.DataLoader
。
这提供了极大的便利,并且避免了编写样板代码。
训练图像分类器
我们将按顺序执行以下步骤:
- 使用以下命令加载和标准化CIFAR10训练和测试数据集
torchvision
- 定义卷积神经网络
- 定义损失函数
- 根据训练数据训练网络
- 在测试数据上测试网络
使用numpy实现网络实例
# -*- coding: utf-8 -*-
import numpy as np
# N is batch size; D_in is input dimension;
# H is hidden dimension; D_out is output dimension.
N, D_in, H, D_out = 64, 1000, 100, 10
# Create random input and output data
x = np.r