快速入门PyTorch

[TOC]

什么是PyTorch

  1. 一个基于Python的机器学习框架
  2. 两个主要特点:
    • 在GPUs上进行N维张量计算(如NumPy)
    • 用于训练深度神经网络的自动微分

前置知识—-tensors的基本使用

tensor是pytorch的基本数据结构,他是一个高维矩阵,类似数组(arrays)。

image-20240901125711927

查看Tensors的维度

1
x.shape()

image-20240901130342727

:warning: PyTorch的dim(维度)等价于 NumPy中的axis(轴)

创建Tensors

直接从数据中获取(比如:list 或者 numpy.ndarray)

1
2
x = torch.tensor([[1, -1], [-1, 1]])
x = torch.from_numpy(np.array([[1, -1], [-1, 1]]))

image-20240901154208367

创建全是0或全是1的常数张量

1
2
x = torch.zeros([2, 2])   	 # [2, 2]指shape    第0维2列,第1维2列
x = torch.ones([1, 2, 5]) # [1, 2, 5]指shape 第0维1列,第1维2列,第2维5列

image-20240901154521790

常用操作

支持常用的算术函数:

  1. 加法:z = x + y
  2. 减法:z = x - y
  3. 幂运算:y = x.pow(2)
  4. 求和:y = x.sum()
  5. 平均:y = x.mean()

Transpose:将指定的两个维度转置:

1
2
3
4
5
x = torch.zeros([2, 3])
x.shape

x = x.transpose(0, 1)
x.shape

image-20240901155701729

image-20240901155714425

Squeeze:删除length = 1的指定维度

1
2
3
4
5
x = torch.zeros([1, 2, 3])
x.shape

x = x.squeeze(0) # dim = 0
x.shape

image-20240901160526740

image-20240901160818038

1
2
3
4
5
x = torch.zeros([2, 1, 3])
x.shape

x = x.squeeze(1) # dim = 1
x.shape

image-20240901160549874

Unsqueeze:扩展一个维度

1
2
3
4
5
x = torch.zeros([2, 3])
x.shape

x = x.unsqueeze(1) # dim = 1
x.shape

image-20240901161101257

image-20240901161148478

1
2
3
4
5
x = torch.zeros([3, 2])
x.shape

x = x.unsqueeze(2) # dim = 2
x.shape

image-20240901161224217

Cat:连接多个张量

1
2
3
4
5
x = torch.zeros([2, 1, 3])
y = torch.zeros([2, 3, 3])
z = torch.zeros([2, 2, 3])
w = torch.cat([x, y, z], dim=1) # 维度1上相加
w.shape

image-20240901161522072

1
2
3
4
5
x = torch.zeros([1, 2, 3])
y = torch.zeros([2, 2, 3])
z = torch.zeros([3, 2, 3])
w = torch.cat([x, y, z], dim=0) # 维度0上相加
w.shape

image-20240901161534795

数据类型

对模型和数据使用不同的数据类型会导致错误。

Data type dtype tensor
32-bit floating point torch.float torch.FloatTensor
64-bit integer (signed) torch.long torch.LongTensor

PyTorch和NumPy对比

类似的属性

PyTorch NumPy
x.shape x.shape
x.dtype x.dtype

许多函数也有相同的名称

PyTorch NumPy
x.reshape / x.view x.reshape
x.squeeze() x.squeeze()
x.unsqueeze(1) np.expand_dims(x, 1)

计算设备

张量和模块将默认使用CPU计算。

使用.to()将张量移动到适当的设备。

CPU:

1
x = x.to('cpu')

GPU:

1
x = x.to('cuda')

检查您的计算机是否有NVIDIA GPU

1
torch.cuda.is_available()

多个GPUs: 指定 ‘cuda:0’, ‘cuda:1 ‘, ‘cuda:2 ‘, …

1
x = x.to('cuda:0')

为什么使用 GPUs?

梯度计算

1
2
3
4
x = torch.tensor([[1., 0.], [-1., 1.]], requires_grad=True)		 # ①
z = x.pow(2).sum() # ②
z.backward() # ③
x.grad # ④

image-20240902094407353

image-20240902094424938

神经网络的训练和测试

如何训练一个神经网络分为三步:定义神经、定义损失函数、定义优化算法。

image-20240901123348781

一个神经网络完整的训练和测试过程包括:神经网络训练、神经网络验证、神经网络测试。神经网络训练和神经网络验证两部分不断迭代,训练好模型。使用训练好的网络进行测试。

image-20240901123754052

下面具体介绍每个部分具体如何使用pytorch编写代码。

第一步-数据加载

使用pytorchdatasetdataloader类处理和加载数据。

image-20240901123922410

Dataset:存储数据样本和需要值

Dataloader:批量分组数据,支持多处理

1
2
3
"""使用示例"""
dataset = MyDataset(file)
dataloader = DataLoader(dataset, batch_size, shuffle=True) # 训练时设置为 True 测试时设置为 False

自定义数据加载,根据需要将数据从磁盘中获取,如:类别,图像,路径等信息。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
from torch.utils.data import Dataset, DataLoader

class MyDataset(Dataset):
def __init__(self, file):
self.data = ... # 数据读取和处理
def __getitem__(self, index):
return self.data[index] # 每次返回一个样本
def __len__(self):
return len(self.data) # 返回数据集的大小


# 定义好的Dataset
dataset = MyDataset(file)
# 在DataLoader中加载数据
dataloader = DataLoader(dataset, batch_size=5, shuffle=False)

image-20240901125508649

第二步-定义神经网络

image-20240902094809971

线性层(全连接层)

Linear Layer (Fully-connected Layer)

1
2
3
import torch.nn as nn

nn.Linear(in_features, out_features)

image-20240902095258317

image-20240902095334516

左边输入维度为32,输出维度为64。Wx + b = y

image-20240902095518722

查看全连接层的权重和偏置

1
2
3
4
5
layer = torch.nn.Linear(32, 64)

layer.weight.shape # W

layer.bias.shape # b

image-20240902095807468

非线性激活函数

  1. Sigmoid激活函数

    1
    nn.Sigmoid()

image-20240902100022861

  1. ReLU激活函数

    1
    nn.ReLU()

image-20240902100116229

构建自己的神经网络

__init__():初始化模型和定义层

forward():计算神经网络的输出

1
2
3
4
5
6
7
8
9
10
11
12
import torch.nn as nn

class MyModel(nn.Module):
def __init__(self):
super(MyModel, self).__init__()
self.net = nn.Sequential(
nn.Linear(10, 32),
nn.Sigmoid(),
nn.Linear(32, 1)
)
def forward(self, x):
return self.net(x)

使用Sequential等价于下面代码,Sequential将各个层串联起来

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import torch.nn as nn

class MyModel(nn.Module):
def __init__(self):
super(MyModel, self).__init__()
self.layer1 = nn.Linear(10, 32)
self.layer2 = nn.Sigmoid(),
self.layer3 = nn.Linear(32,1)

def forward(self, x):
out = self.layer1(x)
out = self.layer2(out)
out = self.layer3(out)
return out

第三步-定义损失函数

image-20240902102441041

  1. 均方差损失函数(Mean Squared Error):常用于回归任务(regression)

    1
    2
    criterion = nn.MSELoss()
    loss = criterion(model_output, expected_value)
  1. 交叉熵损失函数(Cross Entropy):常用于分类任务(classification)

    1
    2
    criterion = nn.CrossEntropyLoss()
    loss = criterion(model_output, expected_value)

第四步-定义优化算法

image-20240902102841785

基于梯度的优化算法,调整网络参数以减少误差。

例如,随机梯度下降(Stochastic Gradient Descent, SGD)

1
optimizer = torch.optim.SGD(model.parameters(), lr, momentum = 0)

对于每批数据:

  1. 调用optimizer.zero_grad()重置模型参数的梯度。
  2. 调用loss.backward()反向传播预测损失的梯度。
  3. 调用optimizer.step()来调整模型参数。

第五步-模型训练验证测试全过程

image-20240902105136467

神经网络训练设置

1
2
3
4
5
dataset = MyDataset(file)                               # 通过MyDataset读取数据
tr_set = DataLoader(dataset, 16, shuffle=True) # 将数据放入Dataloader
model = MyModel().to(device) # 构建模型并迁移到设备(cpu/cuda)
criterion = nn.MSELoss() # 设置损失函数
optimizer = torch.optim.SGD(model.parameters(), 0.1) # 设置优化器

神经网络训练循环迭代

1
2
3
4
5
6
7
8
9
for epoch in range(n_epochs):                  # 遍历批次
model.train() # 设置模型为训练模式
for x, y in trian_loader: # 遍历训练集
optimizer.zero_grad() # 设置梯度为0
x, y = x.to(device), y.to(device) # 移动数据到设备(GPU、CPU)
pred = model(x) # 前向传播,计算输出
loss = criterion(pred, y) # 计算损失
loss.backward() # 反向传播,计算梯度
optimizer.step() # 使用优化器更新模型

神经网络验证循环迭代

1
2
3
4
5
6
7
8
9
model.eval()                                            # 设置模型为验证模式
total_loss = 0
for x, y in valid_loader: # 遍历验证集
x, y = x.to(device), y.to(device) # 移动数据到设备(GPU、CPU)
with torch.no_grad(): # 禁用梯度计算
pred = model(x) # 前向传播,计算输出
loss = criterion(pred, y) # 计算损失
total_loss += loss.cpu().item() * len(x) # 累计损失
avg_loss = total_loss / len(valid_loader.dataset) # 计算平均损失

神经网络测试(预测)循环迭代

1
2
3
4
5
6
7
model.eval()                           # 设置模型为验证模式
preds = []
for x in test_loader: # 遍历测试集
x = x.to(device) # 移动数据到设备(GPU、CPU)
with torch.no_grad(): # 禁用梯度计算
pred = model(x) # 前向传播,计算输出
preds.append(pred.cpu()) # 记录预测结果

:warning: model.eval(), torch.no_grad()

model.eval():更改一些模型层的行为,如dropout和batch normalization。

torch.no_grad():阻止计算被添加到梯度计算图中。通常用于防止对验证/测试数据的意外训练。

第六步-保存/加载训练好的模型

保存模型

1
torch.save(model.state_dict(), path)

加载模型

1
2
ckpt = torch.load(path)
model.load_state_dict(ckpt)

参考资料

Hongyi_Lee_dl_homeworks/Warmup/Pytorch_Tutorial_1.pdf at master · huaiyuechusan/Hongyi_Lee_dl_homeworks (github.com)

PyTorch实用教程(第二版) (tingsongyu.github.io)

李宏毅《机器学习/深度学习》2021课程(国语版本,已授权)

PyTorch深度学习快速入门教程(绝对通俗易懂!)【小土堆】

跟李沐学AI的个人空间-【完结】动手学深度学习 PyTorch版)