# Build The Neural Network
神经网络由对数据执行操作的层/模块组成。torch.nn提供了构建神经网络所需的所有模块。Pytorch中的每个模块都是nn.Module的子类。一个神经网络是一个包含了其他模块(层)的模块。这种嵌套的结构使得更容易建立和管理这种复杂的结构。
示例:建立一个神经网络去识别FashionMNIST数据集中的图像
import os
import torch
from torch import nn
from torch.utils.data import DataLoader
from torchvision import datasets, transforms
1 Get Device for Training
使用GPU可以加速模型训练。接下来我们验证GPU是否可用(torch.cuda.is_available)
device = 'cuda' if torch.cuda.is_available() else 'cpu'
print('Using {} device'.format(device))
2 Define the Class
通过子类化nn.Module定义我们自己的神经网络。
(1) 在__init__方法中初始化神经网络层
(2) 每一个nn.Module子类在forward方法中实现对输入数据的操作
class NeuralNetwork(nn.Module):
def __init__(self): # 定义网络结构
super(NeuralNetwork, self).__init__()
self.flatten = nn.Flatten()
self.linear_relu_stack = nn.Sequential(
nn.Linear(28 * 28, 512),
nn.ReLU(),
nn.Linear(512, 512),
nn.ReLU(),
nn.Linear(512, 10),
nn.ReLU()
)
def forward(self, x): # 前向传播
x = self.flatten(x)
logits = self.linear_relu_stack(x)
return logits
在使用模型前需要先实例化模型,并将其移动到CPU上
model = NeuralNetwork().to(device)
print(model)
"""
Output:
NeuralNetwork(
(flatten): Flatten(start_dim=1, end_dim=-1)
(linear_relu_stack): Sequential(
(0): Linear(in_features=784, out_features=512, bias=True)
(1): ReLU()
(2): Linear(in_features=512, out_features=512, bias=True)
(3): ReLU()
(4): Linear(in_features=512, out_features=10, bias=True)
(5): ReLU()
)
)
"""
为了使用模型,我们将输入数据传递给他。这将执行模型的forward以及一些后台操作。
在输入数据上调用模型,会返回一个10维张量,其中包含每个类的原始预测值。我们将其传递给nn.Softmax模块的实例来获得预测概率。
X = torch.rand(1, 28, 28, device=device) # 生成(1, 28, 28)的数据
logits = model(X) # 向模型输入数据
pred_proab = nn.Softmax(dim=1)(logits) # 调用Softmax将预测映射为(0, 1)之间的概率
y_pred = pred_probab.argmax(1) # 求最大概率对应的类别
print(f"Predicted class: {y_pred}")
"""
Output:
Predicted class: tensor([0])
"""
3 Model Layers
让我们来分解网络,以讲解每一层的功能。为了说明这一点,我们将取一个由3张大小为28×28的图像组成的小批量样本输入网络。
input_image = torch.rand(3, 28, 28) # 生成(3, 28, 28)的数据
print(input_image.size())
3.1 nn.Flatten层
Flatten层用于将多维的输入一维化,常用在从卷积层到全连接层的过度。我们初始化nn.Flatten层以将每个2D图像转换为784(28*28)个像素值的连续数组(批量维度保持为3)
flatten = nn.Flatten()
flat_image = flatten(input_image) # (3, 28, 28)转换为(3, 784)
print(flat_image.size())
3.2 nn.Linear层
Linear层用该层的权重和偏置对输入数据做线性变换。
layer1 = nn.Linear(in_feature=28 * 28, out_features=20) # 输入(3, 28*28),输出(3, 20)
hidden1 = layer1(flat_image)
print(hidden1.size())
3.3 nn.ReLU层
为了在模型输入和输出之间建立一个复杂的非线性映射,需要使用非线性的激活函数。该函数在线性变换后引入非线性,帮助神经网络学习各种各样的复杂映射。
在这个模型中,我们在线性层之间使用nn.ReLU,也可以使用其他激活函数来引入非线性。
print(f"Before ReLU: {hidden1}\n\n")
hidden1 = nn.ReLU()(hidden1)
print(f"After ReLU: {hidden1}")
3.4 nn.Sequential层
nn.Sequential是一个有序的模型容器。输入数据将以Sequential中定义的顺序流经各层。可以使用nn.Sequential来组合一个快速网络,例如下面的seq_modules.
seq_modules = nn.Sequential(
flatten,
layer1,
nn.ReLU(),
nn.Linear(20, 10)
)
input_image = torch.rand(3, 28, 28)
logits = seq_modules(input_image)
3.5 nn.Softmax层
神经网络的最后一个线性层返回logits,即值域区间在[-infty, infty]中的原始值。这些值之后传递给nn.Softmax模块后,logits被缩放到[0, 1]区间,表示模型对每个类的预测概率(dim参数指示数值总和必须为1的维度)
softmax = nn.Softmax(dim=1)
pred_probab = softmax(logits)
print(pred_probab)
4 Model Parameters
神经网络内的许多层都是参数化的,即具有相关联的权重和偏置,这些参数在训练中被迭代优化。子类nn.Module自动跟踪模型对象内部定义的所有字段,并使用模型的Parameters()或named_parameters()方法访问所有参数。我们可以通过模型迭代每个参数,并输出其尺寸和值。
print("Model structure: ", model, "\n\n")
for name, param in model.named_parameters():
print(f"Layer: {name} | Size: {param.size()} | Value: {param[:2]} \n")