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)

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

相关推荐
哲Zheᗜe༘1 天前
了解学习Python编程之python基础
开发语言·python·学习
救救孩子把1 天前
14-机器学习与大模型开发数学教程-第1章 1-6 费马定理与极值判定
人工智能·数学·机器学习
麦麦大数据1 天前
F024 RNN+Vue+Flask电影推荐可视化系统 python flask mysql 深度学习 echarts
python·rnn·深度学习·vue·echarts·电影推荐
诸葛箫声1 天前
十类图片深度学习提升准确率(0.9317)
人工智能·深度学习
Roc-xb1 天前
ModuleNotFoundError: No module named ‘conda_token‘
开发语言·python·conda
救救孩子把1 天前
11-机器学习与大模型开发数学教程-第1章1-3 极限与连续性
人工智能·数学·机器学习
OG one.Z1 天前
01_机器学习初步
人工智能·机器学习
HyperAI超神经1 天前
AI预判等离子体「暴走」,MIT等基于机器学习实现小样本下的等离子体动力学高精度预测
人工智能·神经网络·机器学习·ai·强化学习·可控核聚变·托卡马克
weixin_525936331 天前
部分Spark SQL编程要点
大数据·python·sql·spark
Xyz996_1 天前
python编程基础知识
python