举例说明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]]])
相关推荐
视觉语言导航6 分钟前
RAL-2025 | 清华大学数字孪生驱动的机器人视觉导航!VR-Robo:面向视觉机器人导航与运动的现实-模拟-现实框架
人工智能·深度学习·机器人·具身智能
**梯度已爆炸**16 分钟前
自然语言处理入门
人工智能·自然语言处理
likeGhee29 分钟前
python缓存装饰器实现方案
开发语言·python·缓存
ctrlworks31 分钟前
楼宇自控核心功能:实时监控设备运行,快速诊断故障,赋能设备寿命延长
人工智能·ba系统厂商·楼宇自控系统厂家·ibms系统厂家·建筑管理系统厂家·能耗监测系统厂家
项目題供诗41 分钟前
黑马python(二十五)
开发语言·python
读书点滴1 小时前
笨方法学python -练习14
java·前端·python
笑衬人心。1 小时前
Ubuntu 22.04 修改默认 Python 版本为 Python3 笔记
笔记·python·ubuntu
BFT白芙堂1 小时前
睿尔曼系列机器人——以创新驱动未来,重塑智能协作新生态(上)
人工智能·机器学习·机器人·协作机器人·复合机器人·睿尔曼机器人
蛋仔聊测试1 小时前
Playwright 中 Page 对象的常用方法详解
python
aneasystone本尊1 小时前
使用 MCP 让 Claude Code 集成外部工具
人工智能