注意
点击 这里 下载完整示例代码
学习基础知识 || 快速入门 || 张量 || 数据集和数据加载器 || 转换 || 构建模型 || 自动求导 || 优化 || 保存和加载模型
构建神经网络¶
创建日期: 2021年2月9日 | 最后更新日期: 2024年1月16日 | 最后验证: 未验证
神经网络由执行数据操作的层/模块组成。 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
获取训练设备¶
我们希望能够在可用的GPU或MPS硬件加速器上训练我们的模型。让我们检查一下是否有torch.cuda 或torch.backends.mps可用,否则我们将使用CPU。
device = (
"cuda"
if torch.cuda.is_available()
else "mps"
if torch.backends.mps.is_available()
else "cpu"
)
print(f"Using {device} device")
Using cuda device
定义类¶
我们通过继承 nn.Module 来定义我们的神经网络,并在 __init__ 中初始化神经网络层。nn.Module 每个子类都实现了 forward 方法上的输入数据操作。
class NeuralNetwork(nn.Module):
def __init__(self):
super().__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),
)
def forward(self, x):
x = self.flatten(x)
logits = self.linear_relu_stack(x)
return logits
我们创建一个 NeuralNetwork 的实例,并将其移动到 device,然后打印其结构。
model = NeuralNetwork().to(device)
print(model)
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)
)
)
要使用模型,我们向其传递输入数据。这会执行模型的forward,
以及一些后台操作。
不要直接调用model.forward()!
对输入调用模型会返回一个二维张量,其中dim=0对应于每个类别的10个原始预测值的输出,而dim=1对应于每个输出的各个值。
我们通过传递给nn.Softmax模块的实例来获得预测概率。
X = torch.rand(1, 28, 28, device=device)
logits = model(X)
pred_probab = nn.Softmax(dim=1)(logits)
y_pred = pred_probab.argmax(1)
print(f"Predicted class: {y_pred}")
Predicted class: tensor([7], device='cuda:0')
模型层¶
让我们分解一下 FashionMNIST 模型中的层。为了说明这一点,我们将使用一个包含 3 张 28x28 大小图像的样本 minibatch,并观察当我们将其通过网络传递时会发生什么。
input_image = torch.rand(3,28,28)
print(input_image.size())
torch.Size([3, 28, 28])
nn.Flatten¶
我们初始化 nn.Flatten 层以将每个 28x28 的 2D 图像转换为连续的 784 个像素值数组(批量维度 (dim=0) 保持不变)。
flatten = nn.Flatten()
flat_image = flatten(input_image)
print(flat_image.size())
torch.Size([3, 784])
nn.ReLU¶
非线性激活函数是创建模型输入与输出之间复杂映射的关键。 它们在进行线性变换后应用,以引入非线性,帮助神经网络学习各种现象。
在该模型中,我们使用 nn.ReLU 连接我们的线性层,但还有其他激活函数可以在您的模型中引入非线性。
Before ReLU: tensor([[ 0.4158, -0.0130, -0.1144, 0.3960, 0.1476, -0.0690, -0.0269, 0.2690,
0.1353, 0.1975, 0.4484, 0.0753, 0.4455, 0.5321, -0.1692, 0.4504,
0.2476, -0.1787, -0.2754, 0.2462],
[ 0.2326, 0.0623, -0.2984, 0.2878, 0.2767, -0.5434, -0.5051, 0.4339,
0.0302, 0.1634, 0.5649, -0.0055, 0.2025, 0.4473, -0.2333, 0.6611,
0.1883, -0.1250, 0.0820, 0.2778],
[ 0.3325, 0.2654, 0.1091, 0.0651, 0.3425, -0.3880, -0.0152, 0.2298,
0.3872, 0.0342, 0.8503, 0.0937, 0.1796, 0.5007, -0.1897, 0.4030,
0.1189, -0.3237, 0.2048, 0.4343]], grad_fn=<AddmmBackward0>)
After ReLU: tensor([[0.4158, 0.0000, 0.0000, 0.3960, 0.1476, 0.0000, 0.0000, 0.2690, 0.1353,
0.1975, 0.4484, 0.0753, 0.4455, 0.5321, 0.0000, 0.4504, 0.2476, 0.0000,
0.0000, 0.2462],
[0.2326, 0.0623, 0.0000, 0.2878, 0.2767, 0.0000, 0.0000, 0.4339, 0.0302,
0.1634, 0.5649, 0.0000, 0.2025, 0.4473, 0.0000, 0.6611, 0.1883, 0.0000,
0.0820, 0.2778],
[0.3325, 0.2654, 0.1091, 0.0651, 0.3425, 0.0000, 0.0000, 0.2298, 0.3872,
0.0342, 0.8503, 0.0937, 0.1796, 0.5007, 0.0000, 0.4030, 0.1189, 0.0000,
0.2048, 0.4343]], grad_fn=<ReluBackward0>)
nn.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)
nn.Softmax¶
神经网络的最后一层返回 logits - 原始值在 [-∞, ∞] 范围内 - 这些值随后传递给
nn.Softmax 模块。对数概率被缩放到 [0, 1] 范围内的值,代表模型预测的每个类别的概率。dim 参数表示沿该维度值必须相加为 1。
softmax = nn.Softmax(dim=1)
pred_probab = softmax(logits)
模型参数¶
许多神经网络内部的层是参数化的,即具有在训练过程中优化的相关权重和偏差。
通过子类化nn.Module,系统会自动跟踪您模型对象内定义的所有字段,并通过您的模型的parameters()或named_parameters()方法使所有参数可访问。
在本例中,我们遍历每个参数,并打印其大小及其值的预览。
print(f"Model structure: {model}\n\n")
for name, param in model.named_parameters():
print(f"Layer: {name} | Size: {param.size()} | Values : {param[:2]} \n")
Model structure: 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)
)
)
Layer: linear_relu_stack.0.weight | Size: torch.Size([512, 784]) | Values : tensor([[ 0.0273, 0.0296, -0.0084, ..., -0.0142, 0.0093, 0.0135],
[-0.0188, -0.0354, 0.0187, ..., -0.0106, -0.0001, 0.0115]],
device='cuda:0', grad_fn=<SliceBackward0>)
Layer: linear_relu_stack.0.bias | Size: torch.Size([512]) | Values : tensor([-0.0155, -0.0327], device='cuda:0', grad_fn=<SliceBackward0>)
Layer: linear_relu_stack.2.weight | Size: torch.Size([512, 512]) | Values : tensor([[ 0.0116, 0.0293, -0.0280, ..., 0.0334, -0.0078, 0.0298],
[ 0.0095, 0.0038, 0.0009, ..., -0.0365, -0.0011, -0.0221]],
device='cuda:0', grad_fn=<SliceBackward0>)
Layer: linear_relu_stack.2.bias | Size: torch.Size([512]) | Values : tensor([ 0.0148, -0.0256], device='cuda:0', grad_fn=<SliceBackward0>)
Layer: linear_relu_stack.4.weight | Size: torch.Size([10, 512]) | Values : tensor([[-0.0147, -0.0229, 0.0180, ..., -0.0013, 0.0177, 0.0070],
[-0.0202, -0.0417, -0.0279, ..., -0.0441, 0.0185, -0.0268]],
device='cuda:0', grad_fn=<SliceBackward0>)
Layer: linear_relu_stack.4.bias | Size: torch.Size([10]) | Values : tensor([ 0.0070, -0.0411], device='cuda:0', grad_fn=<SliceBackward0>)