torch.cat和torch.stack的区别

torch.cattorch.stack 是 PyTorch 中用于组合张量的两个常用函数,它们的核心区别在于输入张量的维度和输出张量的维度变化。以下是详细对比:

1. torch.cat (Concatenate)

  • 作用 :沿现有维度 拼接多个张量,不创建新维度

  • 输入要求 :所有张量的形状必须除拼接维度外完全相同

  • 语法

    python 复制代码
    torch.cat(tensors, dim=0)  # dim 指定拼接的维度
  • 示例

    python 复制代码
    a = torch.tensor([[1, 2], [3, 4]])  # shape (2, 2)
    b = torch.tensor([[5, 6]])           # shape (1, 2)
    
    # 沿 dim=0 拼接(行方向)
    c = torch.cat([a, b], dim=0)
    print(c)
    # tensor([[1, 2],
    #         [3, 4],
    #         [5, 6]])  # shape (3, 2)
  • 特点

    • 拼接后的张量在指定维度上的大小是输入张量该维度大小的总和。

    • 其他维度必须完全一致。

2. torch.stack

  • 作用 :沿新维度 堆叠多个张量,创建新维度

  • 输入要求 :所有张量的形状必须完全相同

  • 语法

    python 复制代码
    torch.stack(tensors, dim=0)  # dim 指定新维度的位置
  • 示例

    python 复制代码
    a = torch.tensor([1, 2])  # shape (2,)
    b = torch.tensor([3, 4])  # shape (2,)
    
    # 沿新维度 dim=0 堆叠
    c = torch.stack([a, b], dim=0)
    print(c)
    # tensor([[1, 2],
    #         [3, 4]])  # shape (2, 2)
    
    # 沿新维度 dim=1 堆叠
    d = torch.stack([a, b], dim=1)
    print(d)
    # tensor([[1, 3],
    #         [2, 4]])  # shape (2, 2)
  • 特点

    • 输出张量比输入张量多一个维度

    • 适用于将多个相同形状的张量合并为批次(如 batch_size 维度)。

3. 关键区别总结

4. 直观对比示例

假设有两个张量:

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

torch.cat 结果

python 复制代码
torch.cat([x, y], dim=0)  # tensor([1, 2, 3, 4]), shape (4,)

torch.stack 结果

python 复制代码
torch.stack([x, y], dim=0)  # tensor([[1, 2], [3, 4]]), shape (2, 2)

5. 如何选择?

  • torch.cat 当需要扩展现有维度(如拼接多个特征图)。

  • torch.stack 当需要创建新维度(如构建批次数据或堆叠不同模型的输出)

通过理解两者的维度变化逻辑,可以避免常见的形状错误(如 size mismatch)。

相关推荐
程序员cxuan5 小时前
为每个任务配一套 harness:Claude Code 里的动态工作流
人工智能
程序员cxuan5 小时前
Claude Fable 5 来了
人工智能·后端·程序员
云边云科技_云网融合5 小时前
云边云科技亮相 2026 WOD 制造业数智化博览会 云网融合赋能制造焕新
人工智能·科技·安全·制造
Σίσυφος19005 小时前
激光三角 光平面标定-多高度误差分析
人工智能·计算机视觉·平面
JS菌5 小时前
手写一个 AI Agent 全栈项目:从沙箱执行到子智能体的完整实现
前端·人工智能·后端
lqqjuly5 小时前
前沿算法深度解析(二)
人工智能·算法·机器学习
Bode_20025 小时前
基于大数据分析的全生命周期质量追溯质量评估体系落地方案
大数据·人工智能
分布式存储与RustFS6 小时前
RustFS S3 Table 开源后,我重新梳理了一下 Iceberg 数据湖的选型思路
人工智能·开源·minio·dpu·rustfs·ai存储·s3 table
DevOpenClub6 小时前
用 Agent 搭建网页内容采集与结构化处理流水线
人工智能
56AI6 小时前
2026 企业级AI智能体开发平台推荐:聚焦底层安全与准确率的智能体平台
人工智能·安全·智能体