举例说明PyTorch函数torch.cat与torch.stack的区别

一、torch.cat与torch.stack的区别

torch.cat用于在给定的维度上连接多个张量,它将这些张量沿着指定维度堆叠在一起。

torch.stack用于在新的维度上堆叠多个张量,它会创建一个新的维度,并将这些张量沿着这个新维度堆叠在一起。

二、torch.cat

Example1:

py 复制代码
import torch

tensor1 = torch.tensor([[1, 2], [3, 4]])
tensor2 = torch.tensor([[5, 6], [7, 8]])

result1 = torch.cat((tensor1, tensor2), dim=0)
result2 = torch.cat((tensor1, tensor2), dim=1)

print(result1.shape)
print(result1)
print(result2.shape)
print(result2)
lua 复制代码
torch.Size([4, 2])
tensor([[1, 2],
        [3, 4],
        [5, 6],
        [7, 8]])
torch.Size([2, 4])
tensor([[1, 2, 5, 6],
        [3, 4, 7, 8]])

三、torch.stack

Example1:

py 复制代码
import torch

tensor1 = torch.tensor([1, 2, 3])
tensor2 = torch.tensor([4, 5, 6])

result1 = torch.stack((tensor1, tensor2), dim=0)
result2 = torch.stack((tensor1, tensor2), dim=1)

print(result1.shape)
print(result1)
print(result2.shape)
print(result2)
lua 复制代码
torch.Size([2, 3])
tensor([[1, 2, 3],
        [4, 5, 6]])
torch.Size([3, 2])
tensor([[1, 4],
        [2, 5],
        [3, 6]])

Example2:

py 复制代码
import torch

tensor1 = torch.tensor([[1, 2], [3, 4], [5, 6]])
tensor2 = torch.tensor([[7, 8], [9, 10], [11, 12]])
tensor3 = torch.tensor([[13, 14], [15, 16], [17, 18]])

result1 = torch.stack((tensor1, tensor2, tensor3), dim=0)
result2 = torch.stack((tensor1, tensor2, tensor3), dim=1)

print(result1.shape)
print(result1)
print(result2.shape)
print(result2)
lua 复制代码
torch.Size([3, 3, 2])
tensor([[[ 1,  2],
         [ 3,  4],
         [ 5,  6]],

        [[ 7,  8],
         [ 9, 10],
         [11, 12]],

        [[13, 14],
         [15, 16],
         [17, 18]]])
torch.Size([3, 3, 2])
tensor([[[ 1,  2],
         [ 7,  8],
         [13, 14]],

        [[ 3,  4],
         [ 9, 10],
         [15, 16]],

        [[ 5,  6],
         [11, 12],
         [17, 18]]])
相关推荐
智算菩萨5 小时前
【实战讲解】ChatGPT 5.4深度文献检索完全指南:提示词工程与学术实战策略
论文阅读·人工智能·gpt·搜索引擎·chatgpt·提示词·论文笔记
gutsyang5 小时前
Google Stitch:最佳实践
人工智能·google·gemini·stitch
ZTLJQ5 小时前
数据的基石:Python中关系型数据库完全解析
开发语言·数据库·python
gloomyfish6 小时前
【最新认知】2026 | 深度学习工业缺陷检测三种技术路线分析与趋势
人工智能·深度学习
Deepoch6 小时前
Deepoc具身模型开发板:赋予机械狗“荒野求生”级VLA智能
人工智能·科技·开发板·具身模型·deepoc
阿里云大数据AI技术6 小时前
阿里云大数据AI平台升级发布:构筑智能体时代的核心基石
人工智能
AI自动化工坊6 小时前
DeerFlow 2.0实战指南:生产级AI Agent框架的Docker化部署与并行编排
人工智能·docker·ai·容器·开源
FreakStudio6 小时前
lvgl-micropython、lv_micropython和lv_binding_micropython到底啥关系?一文读懂
python·单片机·嵌入式·面向对象·电子diy
AI营销先锋6 小时前
原圈科技GEO解密:AI营销变革下,如何抢占增长先机?
大数据·人工智能
冬奇Lab6 小时前
一天一个开源项目(第56篇):人人都能用英语 - AI 时代的外语学习开源项目
人工智能·开源·资讯