本文将介绍使用PyTorch搭建神经网络所需要的五个模块:
1. 定义神经网络;
使用PyTorch只需要定义神经网络的正向传输过程,Autograd机制会自动生成反向传播过程。torch.nn包提供了创建神经网络的卷积层、全连接层等的函数,使用这些函数可以方便的搭建想要的网络。
代码示例:
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))#改变张量维度,-1表示维度自动判断
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
2. 读取数据;
读取数据需要将原始数据转换为Tensor变量,才能输入神经网络进行处理。读取的方式由数据类型决定,读取图像常用的方式如下:
#下载并读取CIFAR10数据集
trainset = torchvision.datasets.CIFAR10(root='./data', train=True,
download=True, transform=transform)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=4,
shuffle=True, num_workers=2)
3. 正向传播计算损失;
正向传播过程由网络的forward函数定义,计算损失需要先定义损失函数。PyTorch内置了常用的损失函数如均方误差、交叉熵等,可以直接调用。
代码示例:
#正向传播计算网络的输出结果
output = net(input)
#target是训练集数据的标签,此处以随机数代替
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)
4. 反向传播计算梯度;
代码示例:
#清空之前网络中产生的梯度
net.zero_grad() # zeroes the gradient buffers of all parameters
#计算梯度
loss.backward()
5. 更新网络权重。
更新网络权重需要使用优化器,torch.optim中集成了常用的权重优化算法如梯度下降算法、Adam算法等。
代码示例:
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