PyTorch 在 2017 年 1 月由 FAIR(Facebook AI Research)发布,在 Torch(采用 Lua 语言开发的机器学习框架)基础上使用 Python 语言开发,是深度学习框架,实现了众多深度学习模型算法,0.4.0 版本集成 caffe2,1.1.0 版本使用 TensorBoard 增强可视化功能
介绍
PyTorch 优点
- 代码灵活简洁,使用
nn.module封装网络十分方便,基于动态图机制,灵活 - Python 调试方便
- FaceBook 大厂开发和维护,github 贡献者多
- 文档丰富 https://pytorch.org/docs
- 使用者多:学术界(arXiv 论文使用最多)、学生、生产环境等
应用
- 深度学习
- 机器学习智能决策算法
- 人工智能等多领域交叉科学技术
核心
PyTorch 实现模型训练包括五部分:
- 数据(如何预处理数据、如何组织数据进行训练)
- 模型(如果构建模型模块,如何初定义网络和始化网络参数)
- 损失函数(如何创建、选择损失函数?如何设置超参数?)
- 优化器(如何找到最快的学习率?)
- 迭代训练(如何观察训练效果、绘制 Loss、Accuray 曲线?如何使用 TensorBoard 分析)
目标
- 掌握 PyTorch 基础原理
- 熟悉模型训练的始终
- 掌握图像分类、分割、检测,对抗网络及循环网络模型的训练过程和原理
安装
支持 CPU 和 GPU 两种版本,GPU 的环境必需安装 CUDA 和 CuDNN
安装包由 [cuda版本 or cpu ]/torch-<version>-<py-version>-<os-version> 组成,示例:torch-1.10.1%2Bcpu-cp36-cp36m-linux_x86_64.whl
参考 https://pytorch.org/get-started/locally/
# 官方源 CPU 版本
pip3 install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cpu
# or
python3 -m venv .venv/torch
wget https://download.pytorch.org/whl/cpu/torch-1.8.1%2Bcpu-cp36-cp36m-linux_x86_64.whl
. .venv/torch/bin/activate
pip3 install torch-1.8.1+cpu-cp36-cp36m-linux_x86_64.whl
pip3 install ipykernel ipython
python -m ipykernel install --user
# 国内加速
pip3 install torch torchvision torchaudio --index-url https://mirrors.aliyun.com/pytorch-wheels
pip3 install torch torchvision torchaudio -i https://pypi.tuna.tsinghua.edu.cn/simple介绍
PyTorch 在 2017 年 1 月由 FAIR(Facebook AI Research)发布,在 Torch(采用 Lua 语言开发的机器学习框架)基础上使用 Python 语言开发,是深度学习框架,实现了众多深度学习模型算法,0.4.0 版本集成 caffe2,1.1.0 版本使用 TensorBoard 增强可视化功能
PyTorch 优点
- 代码灵活简洁,使用
nn.module封装网络十分方便,基于动态图机制,灵活 - Python 调试方便
- FaceBook 大厂开发和维护,github 贡献者多
- 文档丰富 https://pytorch.org/docs
- 使用者多:学术界(arXiv 论文使用最多)、学生、生产环境等
应用
- 深度学习
- 机器学习智能决策算法
- 人工智能等多领域交叉科学技术
核心
PyTorch 实现模型训练包括五部分:
- 数据(如何预处理数据、如何组织数据进行训练)
- 模型(如果构建模型模块,如何初定义网络和始化网络参数)
- 损失函数(如何创建、选择损失函数?如何设置超参数?)
- 优化器(如何找到最快的学习率?)
- 迭代训练(如何观察训练效果、绘制 Loss、Accuray 曲线?如何使用 TensorBoard 分析)
目标
- 掌握 PyTorch 基础原理
- 熟悉模型训练的始终
- 掌握图像分类、分割、检测,对抗网络及循环网络模型的训练过程和原理
安装
支持 CPU 和 GPU 两种版本,GPU 的环境必需安装 CUDA 和 CuDNN
安装包由 [cuda版本 or cpu ]/torch-<version>-<py-version>-<os-version> 组成,示例:torch-1.10.1%2Bcpu-cp36-cp36m-linux_x86_64.whl
参考 https://pytorch.org/get-started/locally/
# 官方源 CPU 版本
pip3 install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cpu
# or
python3 -m venv .venv/torch
wget https://download.pytorch.org/whl/cpu/torch-1.8.1%2Bcpu-cp36-cp36m-linux_x86_64.whl
. .venv/torch/bin/activate
pip3 install torch-1.8.1+cpu-cp36-cp36m-linux_x86_64.whl
pip3 install ipykernel ipython
python -m ipykernel install --user
# 国内加速
pip3 install torch torchvision torchaudio --index-url https://mirrors.aliyun.com/pytorch-wheels
pip3 install torch torchvision torchaudio -i https://pypi.tuna.tsinghua.edu.cn/simple使用
version
import torch
print(f'{torch.__version__}')
print(f'{torch.cuda.is_available()}')
print(torch.version.cuda)
print(torch.backends.cudnn.version())
# cuda是否可用
print(torch.cuda.is_available())
# GPU 数量
# torch.cuda.device_count()
# 获取 GPU 设备名称
# torch.cuda.get_device_name(0)
# 获取设备索引
# torch.cuda.current_device()1.8.1+cpu
False
None
None
False
Tensor 张量
张量(Tensor) 是一个多维数组,它是标量(0 维张量)、向量(1 维张量)、矩阵(2 位张量)的高纬度扩展,如 3 维张量、n 维张量
Variable 是 torch.autograd 中的数据类型,主要用于封装 Tensor,进行自动求导
data被包装的 Tensorgraddata 的梯度grad_fn创建 Tensor 的 Function,是自动求导的关键requires_grad指示是否需要梯度is_leaf是否是叶子节点(张量)
torch.Tensor 的组成
data被包装的 Tensordtype张量的数据类型,如torch.FloatTensortorch.cuda.FloatTensortorch.int32ortorch.IntTensortorch.int64ortorch.LongTensortorch.BoolTensortorch.cuda.BoolTensor- 等
shape张量的形状,如(2, 3, 6, 6)device张量所在的设备,运算速度的重要指标,GPU/CPUgraddata 的梯度grad_fn创建 Tensor 的 Function,是自动求导的关键requires_grad指示是否需要梯度is_leaf是否是叶子节点(张量)
创建张量
torch.tensor
torch.tensor(data, dtype=None, device=None, requires_grad=False, pin_memory=False)说明:
- 从 data 创建 Tensor,参数说明
- data 数据,可以是 list、numpy
- dtype 数据类型,默认与 data 的一致
- device 运行时设备,cpu/cuda
- requires_grad 是否需要梯度,bool
- pin_memory 是否存在于锁页内存,bool
# pip install numpy
import numpy as np
arr = np.ones((3, 4))
print(f'arr: {arr}')
print(f'dtype: {arr.dtype}')
# t = torch.tensor(arr, device='cuda')
t = torch.tensor(arr)
print(f't: {t}')arr: [[1. 1. 1. 1.]
[1. 1. 1. 1.]
[1. 1. 1. 1.]]
dtype: float64
t: tensor([[1., 1., 1., 1.],
[1., 1., 1., 1.],
[1., 1., 1., 1.]], dtype=torch.float64)
torch.from_numpy(ndarray)
依据数据从 numpy 创建 tensor,此时 tensor 和原 ndarray 共享内存,当修改其中的一个数据时,另一个也会被改动
import numpy as np
import torch
arr = np.array([[1, 2, 3], [4, 5, 6]])
print(f'numpy arr: {arr}')
t = torch.from_numpy(arr)
print(f'tensor: {t}')
# 修改 arr
arr[0, 0] = 8
print(f'updated numpy arr: {arr}')
print(f'updated tensor: {t}')numpy arr: [[1 2 3]
[4 5 6]]
tensor: tensor([[1, 2, 3],
[4, 5, 6]])
updated numpy arr: [[8 2 3]
[4 5 6]]
updated tensor: tensor([[8, 2, 3],
[4, 5, 6]])
torch.zeros() 和 torch.ones()
torch.zeros创建值全为0的张量torch.ones创建全为 1 的张量
torch.zeros(*size, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False)
torch.ones(*size, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False)说明:
size张量的形状,如 (3, 4)out输出的张量layout内存中布局的形式,如 strided、sparse_coodevice所在设备,gpu|cpurequires_grad是否需要梯度
import torch
out_t = torch.tensor([1])
print(f'out_t: {out_t}')
t = torch.zeros((3, 3), out=out_t)
print(f't addr: {id(t)}, t: {t}')
print(f'out_t addr: {id(out_t)}, out_t: {out_t}')
print(f't == out_t is {id(t) == id(out_t)}')out_t: tensor([1])
t addr: 140196890070760, t: tensor([[0, 0, 0],
[0, 0, 0],
[0, 0, 0]])
out_t addr: 140196890070760, out_t: tensor([[0, 0, 0],
[0, 0, 0],
[0, 0, 0]])
t == out_t is True
torch.zeros_like() 和 torch.ones_like()
torch.zeros_like根据input的形状创建全 0 张量torch.ones_like根据input的形状创建全 1 张量
torch.ones_like(input, dtype=None, layout=None, device=None, requires_grad=False)
torch.zeros_like(input, dtype=None, layout=None, device=None, requires_grad=False)说明:
input创建与 input 同形状全 0 张量dtype数据类型layout内存中布局的形式,如 strided、sparse_coodevice所在设备,gpu|cpurequires_grad是否需要梯度
torch.full() 和 torch.full_like()
torch.full根据size的形状创建全 full_value 张量torch.full_like根据input的形状创建全 full_value 张量
torch.full(size, full_value, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False)
torch.full_like(input, full_value, out=None, dtype=None, layout=None, device=None, requires_grad=False)说明:
size张量的形状input创建与 input 同形状、所有元素为 full_value 的张量dtype数据类型layout内存中布局的形式,如 strided、sparse_coodevice所在设备,gpu|cpurequires_grad是否需要梯度
import torch
t = torch.full((3, 3), 3)
print(f't: {t}')
t2 = torch.full_like(t, 4)
print(f't2: {t2}')t: tensor([[3, 3, 3],
[3, 3, 3],
[3, 3, 3]])
t2: tensor([[4, 4, 4],
[4, 4, 4],
[4, 4, 4]])
torch.arange()
创建等差数列(1 维)张量
torch.arange(start=0, end, step=1, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False)说明:
- 数值区间
[start, end) start数列起始值end数量结束值(不包括)step数列公差,默认为 1
import torch
t = torch.arange(2, 10, 2)
print(f't: {t}')t: tensor([2, 4, 6, 8])
torch.linspace
创建均分的 1 维张量
torch.linspace(start, end, steps=100, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False)说明:
- 数值区间
[start, end] start数列起始值end数量结束值steps数量长度
import torch
t = torch.linspace(2, 10, 5)
print(f't: {t}')
t = torch.linspace(2, 10, 6)
print(f't: {t}')t: tensor([ 2., 4., 6., 8., 10.])
t: tensor([ 2.0000, 3.6000, 5.2000, 6.8000, 8.4000, 10.0000])
torch.logspace()
创建对数均分的 1 维张量
torch.logspace(start, end, steps=100, base=10.0, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False)说明:
start数列起始值end数量结束值steps数量长度base对数函数的底,默认为 10.0
torch.eye()
创建单位对角矩阵,2 维张量
torch.eye(n, m=None, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False)说明:
n矩阵行数m矩阵列数
依据概率创建
torch.normal()
生成正态分布(高斯分布)
torch.normal(mean, std, out=None)
torch.normal(mean, std, stize, out=None)说明:
mean均值std标准差
有四种模式:
mean为标量,std为标量mean为标量,std为张量mean为张量,std为标量mean为张量,std为张量
import torch
# mean 为标量,std 为标量
mean = 0
std = 1
t_normal = torch.normal(mean, std, size=(6,))
print(f'mean: {mean}\nstd: {std}\nt_normal: {t_normal}')mean: 0
std: 1
t_normal: tensor([ 0.1499, 1.3398, 1.1951, 1.0725, -0.4254, 2.1158])
import torch
# mean 为张量,std 为标量
mean = torch.arange(1, 5, dtype=torch.float)
std = 2
t_normal = torch.normal(mean, std)
print(f'mean: {mean}\nstd: {std}\nt_normal: {t_normal}')mean: tensor([1., 2., 3., 4.])
std: 2
t_normal: tensor([-0.4372, 1.9243, 5.1586, 5.4141])
import torch
# mean 为标量,std 为张量
mean = 2
std = torch.arange(1, 5, dtype=torch.float)
t_normal = torch.normal(mean, std)
print(f'mean: {mean}\nstd: {std}\nt_normal: {t_normal}')mean: 2
std: tensor([1., 2., 3., 4.])
t_normal: tensor([1.3395, 2.6783, 1.8279, 3.6528])
import torch
# mean 为张量,std 为张量
mean = torch.arange(1, 5, dtype=torch.float)
std = torch.arange(1, 5, dtype=torch.float)
t_normal = torch.normal(mean, std)
print(f'mean: {mean}\nstd: {std}\nt_normal: {t_normal}')mean: tensor([1., 2., 3., 4.])
std: tensor([1., 2., 3., 4.])
t_normal: tensor([ 0.9723, 4.1015, 1.0803, -2.2438])
torch.randn() 和 torch.randn_like()
生成标准正态分布
# 生成区间 `[0, 1)` 上的均匀分布
torch.rand(*size, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False)
torch.rand_like(input, dtype=None, layout=None, device=None, requires_grad=False)
# 生成均值为 0、方差为 1 的标准正态分布
torch.randn(*size, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False)
torch.randn_like(input, dtype=None, layout=None, device=None, requires_grad=False)
# 在区间 [low, high) 生成整数均匀分布
torch.randint(low, high, size, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False)
torch.randint_like()说明:
size张量的形状
torch.randperm()
生成从 0 到 n-1 的随机排列,n 为张量的长度
torch.randperm(n, out=None, dtype=torch.int64, layout=torch.strided, device=None, requires_grad=False)torch.bernoulli()
以 input 为概率,生成伯努利分布(0-1 分布,两点分布),input 为概率值
torch.bernoulli(input, *, generator=None, out=None)张量的操作
拼接
torch.cat()将张量按维度 dim 进行拼接,tensors 为张量序列,dim 为要拼接的维度
torch.cat(tensors, dim=0, out=None)torch.stack()在新创建的维度 dim 上进行拼接,tensors 为张量序列,dim 为要拼接的维度
torch.stack(tensors, dim=0, out=None)import torch
t = torch.ones((2, 3))
t0 = torch.cat([t, t], dim=0)
print(f't0: {t0}, t0.shape: {t0.shape}')
t1 = torch.cat([t, t], dim=1)
print(f't1: {t1}, t1.shape: {t1.shape}')
t2 = torch.cat([t, t, t], dim=1)
print(f't2: {t2}, t2.shape: {t2.shape}')t0: tensor([[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.]]), t0.shape: torch.Size([4, 3])
t1: tensor([[1., 1., 1., 1., 1., 1.],
[1., 1., 1., 1., 1., 1.]]), t1.shape: torch.Size([2, 6])
t2: tensor([[1., 1., 1., 1., 1., 1., 1., 1., 1.],
[1., 1., 1., 1., 1., 1., 1., 1., 1.]]), t2.shape: torch.Size([2, 9])
import torch
t = torch.randn((2, 3))
print(f't: {t}')
t0 = torch.stack([t, t, t], dim=0)
print(f't0: {t0}, t0.shape: {t0.shape}')
t1 = torch.stack([t, t, t], dim=1)
print(f't1: {t1}, t1.shape: {t1.shape}')
t2 = torch.stack([t, t, t], dim=2)
print(f't2: {t2}, t2.shape: {t2.shape}')t: tensor([[ 1.8205, 0.8776, 0.0840],
[-0.9878, -0.9759, -0.7476]])
t0: tensor([[[ 1.8205, 0.8776, 0.0840],
[-0.9878, -0.9759, -0.7476]],
[[ 1.8205, 0.8776, 0.0840],
[-0.9878, -0.9759, -0.7476]],
[[ 1.8205, 0.8776, 0.0840],
[-0.9878, -0.9759, -0.7476]]]), t0.shape: torch.Size([3, 2, 3])
t1: tensor([[[ 1.8205, 0.8776, 0.0840],
[ 1.8205, 0.8776, 0.0840],
[ 1.8205, 0.8776, 0.0840]],
[[-0.9878, -0.9759, -0.7476],
[-0.9878, -0.9759, -0.7476],
[-0.9878, -0.9759, -0.7476]]]), t1.shape: torch.Size([2, 3, 3])
t2: tensor([[[ 1.8205, 1.8205, 1.8205],
[ 0.8776, 0.8776, 0.8776],
[ 0.0840, 0.0840, 0.0840]],
[[-0.9878, -0.9878, -0.9878],
[-0.9759, -0.9759, -0.9759],
[-0.7476, -0.7476, -0.7476]]]), t2.shape: torch.Size([2, 3, 3])
切分
torch.chunk(input, chunks, dim=0)将张量按维度 dim 进行平均切分,返回张量列表,若不能整除,最后一份张量小于其他张量
说明:
input要切分的张量chunks要切分的份数dim要切分的维度
import torch
t = torch.ones((2, 5))
list_of_tensors = torch.chunk(t, dim=1, chunks=2)
for i, v in enumerate(list_of_tensors):
print(f'第{i}个张量:{v},shape is {v.shape}')第 0 个张量:tensor([[1., 1., 1.],
[1., 1., 1.]]),shape is torch.Size([2, 3])
第 1 个张量:tensor([[1., 1.],
[1., 1.]]),shape is torch.Size([2, 2])
torch.split(tensor, split_size_or_sections, dim=0)将张量按维度 dim 进行切分,返回张量列表
说明:
tensor要切分的张量split_size_or_sections为 int 时,表示每一份的长度,为 list 时,按 list 元素切分dim要切分的维度
import torch
t = torch.ones((2, 5))
list_of_tensors = torch.split(t, 2, dim=1)
for i, v in enumerate(list_of_tensors):
print(f'第{i}个张量:{v},shape is {v.shape}')
list_of_tensors = torch.split(t, [2, 1, 2], dim=1)
for i, v in enumerate(list_of_tensors):
print(f'第{i}个张量:{v},shape is {v.shape}')第 0 个张量:tensor([[1., 1.],
[1., 1.]]),shape is torch.Size([2, 2])
第 1 个张量:tensor([[1., 1.],
[1., 1.]]),shape is torch.Size([2, 2])
第 2 个张量:tensor([[1.],
[1.]]),shape is torch.Size([2, 1])
第 0 个张量:tensor([[1., 1.],
[1., 1.]]),shape is torch.Size([2, 2])
第 1 个张量:tensor([[1.],
[1.]]),shape is torch.Size([2, 1])
第 2 个张量:tensor([[1., 1.],
[1., 1.]]),shape is torch.Size([2, 2])
张量索引
torch.index_select(input, dim, index, *, out=None)在维度 dim 上,按 index 索引数据,依 index 索引数据拼接的张量
说明:
input要索引的张量dim要索引的维度index要索引数据的序号
import torch
t = torch.randint(0, 9, size=(3, 3))
index = torch.tensor([0, 2], dtype=torch.long)
t_select = torch.index_select(t, dim=0, index=index)
print(f't: {t}\nindex: {index}\nt_select: {t_select}')t: tensor([[0, 6, 3],
[6, 0, 6],
[1, 2, 5]])
index: tensor([0, 2])
t_select: tensor([[0, 6, 3],
[1, 2, 5]])
torch.masked_select(input, mask, *, out=None)按 mask 中值为 True 进行索引数据
说明:
input要索引的张量mask与 input 同形状的布尔类型张量
import torch
t = torch.randint(0, 9, size=(3, 3))
mask = t.ge(5) # ge: greater than or equel
t_select = torch.masked_select(t, mask)
print(f't: {t}\nmask: {mask}\nt_select: {t_select}')t: tensor([[0, 2, 5],
[6, 2, 5],
[5, 4, 7]])
mask: tensor([[False, False, True],
[ True, False, True],
[ True, False, True]])
t_select: tensor([5, 6, 5, 5, 7])
张量变换
torch.reshape(input, shape)变化张量的形状,当张量在内存中是连续时,新张量与 input 共享数据内存
说明:
input要变换的张量shape新张量的形状
import torch
t = torch.randperm(8)
t_reshape = torch.reshape(t, (2, 4))
print(f't: {t}\nt_reshape: {t_reshape}')
t_reshape = torch.reshape(t, (2, 2, -1)) # -1 表示自动计算,必须能整除
print(f't: {t}\nt_reshape: {t_reshape}')
t[0] = 818
print(f't: {t}\nt_reshape: {t_reshape}')
print(f't.date 内存地址:{id(t.data)}')
print(f't_reshape.date 内存地址:{id(t_reshape.data)}')t: tensor([4, 5, 3, 2, 7, 6, 1, 0])
t_reshape: tensor([[4, 5, 3, 2],
[7, 6, 1, 0]])
t: tensor([4, 5, 3, 2, 7, 6, 1, 0])
t_reshape: tensor([[[4, 5],
[3, 2]],
[[7, 6],
[1, 0]]])
t: tensor([818, 5, 3, 2, 7, 6, 1, 0])
t_reshape: tensor([[[818, 5],
[ 3, 2]],
[[ 7, 6],
[ 1, 0]]])
t.date 内存地址:139908835661144
t_reshape.date 内存地址:139908835661144
- torch.transpose
torch.transpose(input, dim0, dim1)变换张量的两个维度
说明:
input要变化的张量dim0/dim1要交换的维度
import torch
t = torch.rand((2, 3, 4))
t_transpose = torch.transpose(t, dim0=1, dim1=2)
print(f't.shape: {t.shape}, t_transpose.shape: {t_transpose.shape}')t.shape: torch.Size([2, 3, 4]), t_transpose.shape: torch.Size([2, 4, 3])
- torch.t
torch.t(input)2 维张量转置,对矩阵而言,等价于 torch.transpose(input, 0, 1)
- torch.squeeze()
# 压缩长度为1的维度(轴),若 dim 为 None,移除所有长度为 1 的轴;若指定维度,当且仅当该轴长度为 1 时,可以被移除
torch.squeeze(input, dim=None, out=None)
# 依据 dim 扩展维度
torch.unsqueeze(input, dim, out=None)import torch
t = torch.rand((1, 2, 3, 2))
t_sq = torch.squeeze(t)
print(f't.shape: {t.shape}, t_sq.shape: {t_sq.shape}')
t0 = torch.squeeze(t, dim=0)
t1 = torch.squeeze(t, dim=1)
print(f't0.shape: {t0.shape}, t1.shape: {t1.shape}')t.shape: torch.Size([1, 2, 3, 2]), t_sq.shape: torch.Size([2, 3, 2])
t0.shape: torch.Size([2, 3, 2]), t1.shape: torch.Size([1, 2, 3, 2])
专栏文章
最近更新
最新评论