构建神经网络

神经网络由对数据执行操作的层/模块组成。 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使用与否

我们希望能够在 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")

定义类

我们通过子类化来定义我们的神经网络nn.Module,并初始化神经网络层__init__。每个nn.Module子类都在方法中实现对输入数据的操作forward,nn.Module模块中的__call__函数会自动调用forward函数,所有我们只要基础了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):  #Module中存在__calll__会自动调用forward函数
        x = self.flatten(x)
        logits = self.linear_relu_stack(x)
        return logits

我们创建 的一个实例NeuralNetwork网络,并将其移动到device,并打印其结构。`

model = NeuralNetwork().to(device)  #发送到GPU
print(model)
------------------------
out:
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=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}")

模型层

让我们分解 FashionMNIST 模型中的各个层。为了说明这一点,我们将采用 3 张大小为 28x28 的图像的小批量样本,看看当我们将其传递到网络时会发生什么。

input_image = torch.rand(3,28,28)
print(input_image.size())

nn.Flatten
我们初始化nn.Flatten 层,将每个 2D 28x28 图像转换为 784 个像素值的连续数组(维持小批量维度(在 dim=0 时),0维度保持)。

flatten = nn.Flatten()
flat_image = flatten(input_image)
print(flat_image.size())
------------------
out:
torch.Size([3, 784])

nn.Linear

layer1 = nn.Linear(in_features=28*28, out_features=20)
hidden1 = layer1(flat_image)
print(hidden1.size())

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)

三级标题

四级标题
五级标题
六级标题