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)

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

相关推荐
愿没error的x19 小时前
深度学习基础知识总结(一):深入理解卷积(Convolution)
人工智能·深度学习
罗西的思考19 小时前
【智能硬件】AI 眼镜论文笔记
人工智能
AI浩19 小时前
Mamba YOLO: 基于状态空间模型的目标检测简单基线
人工智能·yolo·目标检测
一晌小贪欢19 小时前
Python键盘鼠标自动化库详解:从入门到精通
python·自动化·计算机外设·python鼠标·python键盘·python操控鼠标·python操控键盘
穿西装的水獭19 小时前
python将Excel数据写进图片中
开发语言·python·excel
GitCode官方19 小时前
面壁智能入驻 GitCode:端侧 AI 开发获全新生产力引擎
人工智能·gitcode
拓端研究室19 小时前
专题:2025AI时代的医疗保健业:应用与行业趋势研究报告|附130+份报告PDF、数据、可视化模板汇总下载
大数据·人工智能
咋吃都不胖lyh19 小时前
激活函数是什么,神经网络中为什么要有激活函数
人工智能·深度学习·神经网络·激活函数
Ma04071320 小时前
【论文阅读15】-DiagLLM:基于大型语言模型的多模态推理,用于可解释的轴承故障诊断
人工智能·语言模型·自然语言处理
xiaoxiongip66620 小时前
假设两个设备在不同网段,网关怎么设置才能通呢
网络·爬虫·python·https·智能路由器