快速入门PyTorch
快速入门PyTorch
[TOC]
什么是PyTorch
- 一个基于Python的机器学习框架
- 两个主要特点:
- 在GPUs上进行N维张量计算(如NumPy)
- 用于训练深度神经网络的自动微分
前置知识—-tensors的基本使用
tensor
是pytorch的基本数据结构,他是一个高维矩阵,类似数组(arrays
)。
查看Tensors的维度
1 | x.shape() |
:warning: PyTorch的dim(维度)等价于 NumPy中的axis(轴)
创建Tensors
直接从数据中获取(比如:list 或者 numpy.ndarray)
1 | x = torch.tensor([[1, -1], [-1, 1]]) |
创建全是0或全是1的常数张量
1 | x = torch.zeros([2, 2]) # [2, 2]指shape 第0维2列,第1维2列 |
常用操作
支持常用的算术函数:
- 加法:
z = x + y
- 减法:
z = x - y
- 幂运算:
y = x.pow(2)
- 求和:
y = x.sum()
- 平均:
y = x.mean()
Transpose:将指定的两个维度转置:
1 | x = torch.zeros([2, 3]) |
Squeeze:删除length = 1的指定维度
1 | x = torch.zeros([1, 2, 3]) |
1 | x = torch.zeros([2, 1, 3]) |
Unsqueeze:扩展一个维度
1 | x = torch.zeros([2, 3]) |
1 | x = torch.zeros([3, 2]) |
Cat:连接多个张量
1 | x = torch.zeros([2, 1, 3]) |
1 | x = torch.zeros([1, 2, 3]) |
数据类型
对模型和数据使用不同的数据类型会导致错误。
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?
- 以更多核心进行算术计算的并行计算
- What is a GPU and do you need one in Deep Learning? | by Jason Dsouza | Towards Data Science
梯度计算
1 | x = torch.tensor([[1., 0.], [-1., 1.]], requires_grad=True) # ① |
神经网络的训练和测试
如何训练一个神经网络分为三步:定义神经、定义损失函数、定义优化算法。
一个神经网络完整的训练和测试过程包括:神经网络训练、神经网络验证、神经网络测试。神经网络训练和神经网络验证两部分不断迭代,训练好模型。使用训练好的网络进行测试。
下面具体介绍每个部分具体如何使用pytorch
编写代码。
第一步-数据加载
使用pytorch
的dataset
和dataloader
类处理和加载数据。
Dataset
:存储数据样本和需要值
Dataloader
:批量分组数据,支持多处理
1 | """使用示例""" |
自定义数据加载,根据需要将数据从磁盘中获取,如:类别,图像,路径等信息。
1 | from torch.utils.data import Dataset, DataLoader |
第二步-定义神经网络
线性层(全连接层)
Linear Layer (Fully-connected Layer)
1 | import torch.nn as nn |
左边输入维度为32,输出维度为64。Wx + b = y
查看全连接层的权重和偏置
1 | layer = torch.nn.Linear(32, 64) |
非线性激活函数
Sigmoid激活函数
1
nn.Sigmoid()
ReLU激活函数
1
nn.ReLU()
构建自己的神经网络
__init__()
:初始化模型和定义层
forward()
:计算神经网络的输出
1 | import torch.nn as nn |
使用Sequential等价于下面代码,Sequential将各个层串联起来
1 | import torch.nn as nn |
第三步-定义损失函数
均方差损失函数(Mean Squared Error):常用于回归任务(regression)
1
2criterion = nn.MSELoss()
loss = criterion(model_output, expected_value)
交叉熵损失函数(Cross Entropy):常用于分类任务(classification)
1
2criterion = nn.CrossEntropyLoss()
loss = criterion(model_output, expected_value)
第四步-定义优化算法
基于梯度的优化算法,调整网络参数以减少误差。
例如,随机梯度下降(Stochastic Gradient Descent, SGD)
1 | optimizer = torch.optim.SGD(model.parameters(), lr, momentum = 0) |
对于每批数据:
- 调用
optimizer.zero_grad()
重置模型参数的梯度。 - 调用
loss.backward()
反向传播预测损失的梯度。 - 调用
optimizer.step()
来调整模型参数。
第五步-模型训练验证测试全过程
神经网络训练设置
1 | dataset = MyDataset(file) # 通过MyDataset读取数据 |
神经网络训练循环迭代
1 | for epoch in range(n_epochs): # 遍历批次 |
神经网络验证循环迭代
1 | model.eval() # 设置模型为验证模式 |
神经网络测试(预测)循环迭代
1 | model.eval() # 设置模型为验证模式 |
:warning:
model.eval(), torch.no_grad()
model.eval()
:更改一些模型层的行为,如dropout和batch normalization。
torch.no_grad()
:阻止计算被添加到梯度计算图中。通常用于防止对验证/测试数据的意外训练。
第六步-保存/加载训练好的模型
保存模型
1 | torch.save(model.state_dict(), path) |
加载模型
1 | ckpt = torch.load(path) |
参考资料
PyTorch实用教程(第二版) (tingsongyu.github.io)
李宏毅《机器学习/深度学习》2021课程(国语版本,已授权)