torch.cat和torch.stack的区别

torch.cat 和 torch.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)。

相关推荐
Hello.Reader24 分钟前
一个开源项目,让 AI 做逆向不再靠猜reverse-skill 架构解析与本地实战
人工智能·架构·开源
wespaul1 小时前
VeapAI 自然语言操作实战|第 05 篇:向量与召回——从知识条目到可检索资产
大数据·数据库·人工智能·milvus
mingbaiceping1 小时前
复旦-华盛顿大学EMBA:2026年AI课程矩阵解析
人工智能
李福春1 小时前
技术思考问题17:上了LangChain框架就等于AI-Agent工程化吗?
大数据·人工智能·langchain·深圳同盟·腾讯云架构师技术同盟·llm应用架构·编排抽象
揽秀亭长2 小时前
AIGC 检测原理拆解与论文降 AI 率的可复现处理流程(2026版)
人工智能·aigc
羞儿2 小时前
【DSH】为什么需要-Harness
人工智能·大模型·harness·认知构建
JackLam4 小时前
AI-安装ChatGpt Codex
人工智能
强哥聊算力4 小时前
《算力江湖·英伟达传奇》第七集:ChatGPT出现前夜,英伟达发生了什么?
服务器·人工智能·算法·ai·chatgpt·gpu算力
吴佳浩5 小时前
Run:ai 开源了,我把 GPU 编排摆回 AI 栈里看了一遍
人工智能
IT_Octopus6 小时前
【零基础入门 LLM 开发 · Day 13】:LangChain 的对话记忆——Message 对象版
人工智能·python·langchain