Pytorch中一些重要的经典操作和简单讲解

Pytorch中一些重要的经典操作和简单讲解

形状变换操作

reshape() / view()

python 复制代码
import torch

x = torch.randn(2, 3, 4)
print(f"原始形状: {x.shape}")

# reshape可以处理非连续张量
y = x.reshape(6, 4)
print(f"reshape后: {y.shape}")

# view要求张量在内存中连续
z = x.view(2, 12)
print(f"view后: {z.shape}")

transpose() / permute()

python 复制代码
# transpose交换两个维度
x = torch.randn(2, 3, 4)
y = x.transpose(0, 2)  # 交换第0和第2维
print(f"transpose后: {y.shape}")  # torch.Size([4, 3, 2])

# permute重新排列所有维度
z = x.permute(2, 0, 1)  # 将维度重排为 (4, 2, 3)
print(f"permute后: {z.shape}")

拼接和分割操作

cat() / stack()

python 复制代码
# cat在现有维度上拼接
x1 = torch.randn(2, 3)
x2 = torch.randn(2, 3)

# 在第0维拼接
cat_dim0 = torch.cat([x1, x2], dim=0)  # (4, 3)
# 在第1维拼接
cat_dim1 = torch.cat([x1, x2], dim=1)  # (2, 6)

# stack创建新维度并拼接
stacked = torch.stack([x1, x2], dim=0)  # (2, 2, 3)

chunk() / split()

python 复制代码
x = torch.randn(6, 4)

# chunk均匀分割
chunks = torch.chunk(x, 3, dim=0)  # 分成3块,每块(2, 4)

# split按指定大小分割
splits = torch.split(x, 2, dim=0)  # 每块大小为2
splits_uneven = torch.split(x, [1, 2, 3], dim=0)  # 不均匀分割

索引和选择操作

gather() / scatter()

python 复制代码
# gather根据索引收集元素
x = torch.randn(3, 4)
indices = torch.tensor([[0, 1], [2, 3], [1, 0]])
gathered = torch.gather(x, 1, indices)  # (3, 2)

# scatter根据索引分散元素
src = torch.randn(3, 2)
scattered = torch.zeros(3, 4).scatter_(1, indices, src)

masked_select() / where()

python 复制代码
x = torch.randn(3, 4)
mask = x > 0

# 选择满足条件的元素
selected = torch.masked_select(x, mask)

# 条件选择
y = torch.randn(3, 4)
result = torch.where(mask, x, y)  # mask为True选x,否则选y

数学运算操作

clamp() / clip()

python 复制代码
x = torch.randn(3, 4)

# 限制数值范围
clamped = torch.clamp(x, min=-1, max=1)
# 等价于
clipped = torch.clip(x, -1, 1)

norm() / normalize()

python 复制代码
x = torch.randn(3, 4)

# 计算范数
l2_norm = torch.norm(x, p=2, dim=1)  # L2范数
l1_norm = torch.norm(x, p=1, dim=1)  # L1范数

# 归一化
normalized = torch.nn.functional.normalize(x, p=2, dim=1)

统计运算操作

mean() / sum() / std()

python 复制代码
x = torch.randn(3, 4, 5)

# 各种统计量
mean_all = x.mean()  # 全局均值
mean_dim = x.mean(dim=1)  # 沿第1维求均值
sum_keepdim = x.sum(dim=1, keepdim=True)  # 保持维度

# 最值操作
max_val, max_idx = torch.max(x, dim=1)
min_val, min_idx = torch.min(x, dim=1)

广播和重复操作

expand() / repeat()

python 复制代码
x = torch.randn(1, 3)

# expand不复制数据,只是改变视图
expanded = x.expand(4, 3)  # (4, 3)

# repeat实际复制数据
repeated = x.repeat(4, 2)  # (4, 6)

tile() / repeat_interleave()

python 复制代码
x = torch.tensor([1, 2, 3])

# tile像numpy的tile
tiled = x.tile(2, 3)  # 重复2次每行,3次每列

# repeat_interleave每个元素重复
interleaved = x.repeat_interleave(2)  # [1, 1, 2, 2, 3, 3]

类型转换操作

to() / type() / cast()

python 复制代码
x = torch.randn(3, 4)

# 类型转换
x_int = x.to(torch.int32)
x_float = x.type(torch.float64)
x_cuda = x.to('cuda')  # 移到GPU(如果可用)

# 设备转换
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
x_device = x.to(device)

在深度学习领域,这类张量运算操作具有极高的应用频率,尤其在数据预处理、模型架构构建及推理后处理等关键环节中不可或缺。熟练掌握此类算子的应用逻辑,能够显著优化张量数据的处理流程,提升深度学习任务的执行效率与工程实现效能。

相关推荐
一碗白开水一25 分钟前
【第6话:相机模型2】相机标定在自动驾驶中的作用、相机标定方法详解及代码说明
人工智能·数码相机·自动驾驶
The moon forgets26 分钟前
Occ3D: A Large-Scale 3D Occupancy Prediction Benchmark for Autonomous Driving
人工智能·pytorch·深度学习·目标检测·3d
melody_of_Canon27 分钟前
使用 gptqmodel 量化 Qwen3-Coder-30B-A3B-Instruct
python·gptq量化
新智元40 分钟前
刚刚,马斯克 Grok4 干翻谷歌 Gemini!o3 杀入首届大模型对抗赛决战
人工智能·openai
张子夜 iiii1 小时前
机器学习算法系列专栏:逻辑回归(初学者)
人工智能·算法·机器学习·逻辑回归
我想吃烤肉肉1 小时前
leetcode-python-删除链表的倒数第 N 个结点
python·算法·leetcode·链表
nanxun___1 小时前
【多模态微调】【从0开始】Qwen2-VL + llamafactory
人工智能·python·深度学习·机器学习·语言模型
liupengfei-iot1 小时前
物联网后端系统架构:从基础到AI驱动的未来 - 第十章:AI促进IOT领域发生革命式发展
人工智能·物联网·系统架构
彭军辉1 小时前
什么是抽象主义人工智能?
人工智能·算法·语言模型·机器人
瘦的可以下饭了2 小时前
非线性激活
pytorch