最近在学习《PyTorch官方教程》,跟着教程实现了一个简单的神经网络。
神经网络可以通过 torch.nn 包来构建,一个典型的神经网络训练过程包括以下几点:
- 定义一个包含可训练参数的神经网络。
- 迭代整个输入。
- 通过神经网络处理输入。
- 计算损失(loss)。
- 反向传播梯度到神经网络的参数。
- 更新网络的参数,典型的用一个简单的更新方法:weight = weight - learning_rate *gradient
例如,对于实现下面这个神经网络:
将教程中的代码精简如下:
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
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)
# The learnable parameters of a model are returned by ``net.parameters()``
params = list(net.parameters())
print(len(params))
print(params[0].size()) # conv1's .weight
# Let try a random 32x32 input
# 返回一个1行1列的张量,其中每个元素又是一个32行32列的张量
input = torch.randn(1, 1, 32, 32)
out = net(input)
print(out)
#计算损失函数
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)
# 为了实现反向传播损失,我们所有需要做的事情仅仅是使用 loss.backward()
# 需要清空现存的梯度,要不然它都将会和现存的梯度累计到一起
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)
# 更新神经网络参数
learning_rate = 0.01
for f in net.parameters():
f.data.sub_(f.grad.data * learning_rate)
########################################################################
# 简洁版代码
# 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