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)

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

相关推荐
Kingairy15 小时前
Pytest 插件:pytest_runtest_protocol
python·pytest
即兴小索奇15 小时前
AI智能金融风控新实践:从信贷秒批到支付防护,筑牢金融安全新屏障
人工智能·ai·商业·ai商业洞察·即兴小索奇
sheji341615 小时前
【开题答辩全过程】以 基于python爬虫对微博数据可视化及实现为例,包含答辩的问题和答案
爬虫·python·信息可视化
Moonbit15 小时前
MoonBit Pearls Vol.08: MoonBit 与 Python集成指南
后端·python·程序员
AKAMAI15 小时前
应用平台更新:可定制目录、基于Git的密钥管理与K8s项目自动化管理
人工智能·云原生·云计算
CodeDevMaster15 小时前
从零开始:用uv构建并发布一个Python CLI应用,集成CI/CD自动化发布与Docker容器化部署
python·ci/cd·docker
二闹15 小时前
三招搞定Python定时任务,总有一款适合你
后端·python
文人sec15 小时前
性能测试-jmeter7-元件提取器
python·jmeter·prometheus·模块测试
机器之心16 小时前
NeurIPS 2025:高分论文也可能被拒,只为保住那25%左右的接收率?
人工智能·openai
余衫马16 小时前
ModelScope 开发环境配置指南
人工智能