神经网络

一个典型的神经网络训练过程有以下几步:

  • 定义神经网络。
  • 以一个数据集作为输入进行跌代。
  • 通过网络处理输入。
  • 计算误差。
  • 误差梯度向参数进行传播。
  • 更新网络参数。

定义网络

前向传播

基于Pytorch官方给的tutorial,将讲解以注释的形式写在代码中,如下:

import torch
import torch.nn as nn
import torch.nn.functional as F

# 表示继承于nn.Module类
class Net(nn.Module):

    # 构造函数
    def __init__(self):
        
        # 首先调用父类构造函数
        super(Net, self).__init__()
        
       	# nn.Con2vd函数用来构建卷积核(filter),输入通道为1(假设图片是灰度图片),输出通道为6(有6个filter,需要提取出6个特征),卷积核大小为5(即该filter为5×5)
        self.conv1 = nn.Conv2d(1, 6, 5)
        
        # 同上
        self.conv2 = nn.Conv2d(6, 16, 5)
        
        # 构建一个线性层,该线性层输入为16 × 5 × 5,输出为120
        self.fc1 = nn.Linear(16 * 5 * 5, 120)
        
        # 同上
        self.fc2 = nn.Linear(120, 84)
        
        # 同上
        self.fc3 = nn.Linear(84, 10)

    # 前向传播函数的构建
    def forward(self, x):
        
        # 卷积 -> ReLU -> 池化
        x = F.max_pool2d(F.relu(self.conv1(x)), (2, 2))
        
        # 卷积 -> ReLU -> 池化
        x = F.max_pool2d(F.relu(self.conv2(x)), 2)
        
        # 矩阵翻转
        x = x.view(-1, self.num_flat_features(x))
        
        # 线性层后ReLU
        x = F.relu(self.fc1(x))
        
        # 线性层后ReLU
        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)

查看参数

运行以下代码以查看参数:

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

使用网络

伪造输入数据

input = torch.randn(1, 1, 32, 32)

前向传播

out = net(input)
print(out)

值得注意的是,我们并没有显式调用forward函数,为什么会有输出呢,因为底层自动调用了该函数,并且在任何继承nn.Module的子类中均需要重定义该函数。

梯度重置

net.zero_grad()

# 伪造loss并反向传播
out.backward(torch.randn(1, 10))

定义损失函数

output = net(input)

# 伪造真实的标签
target = torch.randn(10)

# 标签尺寸调整(-1表示视另一个参数而定)
target = target.view(1, -1) 

# 指定损失函数(均方误差Mean-squared Error)
criterion = nn.MSELoss()

# 计算误差
loss = criterion(output, target)
print(loss)

反向传播

loss.backward()

# 查看第一层的偏置参数的梯度
print(net.conv1.bias.grad)

更新权重

手动更新权重

learning_rate = 0.01
for f in net.parameters():
    f.data.sub_(f.grad.data * learning_rate)

自动更新权重

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

optimizer.step()    # Does the update