
本文是《PyTorch官方教程中文版》系列文章之一,目录链接:[翻译]PyTorch官方教程中文版:目录
本文翻译自PyTorch官方网站,链接地址:Build Model
神经网络由层或模块组成,这些层或模块包装了对数据的操作。torch.nn 命名空间提供了构建自己的神经网络所需的所有功能。神经网络本身是一个模块,由其他模块(层)组成,神经网络和这些模块都是 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__成员函数中初始化神经网络,在 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 函数,并且PyTorch会执行一些内部操作,不要直接调用 model.forward() 函数。
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的图片,作为一个小批次传递给模型的每一层,来看看通过神经网络传递它们时发生了什么。
input_image = torch.rand(3,28,28)
print(input_image.size())
上述代码输出:
torch.Size([3, 28, 28])
nn.Flatten
我们初始化了一个类型为 nn.Flatten 的层,将每张28x28的2D图片转换成784像素的连续数组。该数组保存在 flat_image 的第0维中。
flatten = nn.Flatten()
flat_image = flatten(input_image)
print(flat_image.size())
上述代码输出:
torch.Size([3, 784])
nn.Linear
nn.Linear 是一个模块,它使用其存储的权重(weights)和偏移(biases)对输入数据执行线性变换。(译者:变换公式:output = input * weights + biases)
layer1 = nn.Linear(in_features=28*28, out_features=20)
hidden1 = layer1(flat_image)
print(hidden1.size())
上述代码输出:
torch.Size([3, 20])
nn.ReLU
非线性激活函数是能在模型输入和输出之间创建复杂映射的原因。它们对线性变换后的数据执行非线性变换,使神经网络能学习各种各样的数据。(译者:nn.ReLU是激活函数,是神经网络能处理非线性问题的原因)
在本文的模型中,我们使用 nn.ReLU 作为激活函数,但你构建自己的模型时,可以使用其他的激活函数。
print(f"Before ReLU: {hidden1}\n\n")
hidden1 = nn.ReLU()(hidden1)
print(f"After ReLU: {hidden1}")
上述代码输出:
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是一个有序的模块容器,数据按照定义nn.Sequential时的顺序依次传递给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,介于[-infty, infty]之间的值,这些值又被传递给了 nn.Softmax 模块。logits 中的每个值被缩放到了[0, 1]之间,表示模型对每个类的预测概率。dim 参数标明 pred_probab 的每个值相加后总和必须等于1(即100%)。
softmax = nn.Softmax(dim=1)
pred_probab = softmax(logits)
模型参数
神经网络中的许多层都是参数化的,即关联的权重(weights)和偏移(biases)会在训练期间被优化。子类化 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>)
进一步阅读
芸芸小站首发,阅读原文:http://xiaoyunyun.net/index.php/archives/293.html