举例说明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]]])
相关推荐
1***s6322 分钟前
Python爬虫反爬策略,User-Agent与代理IP
开发语言·爬虫·python
数字时代全景窗2 分钟前
从App时代到智能体时代,如何打破“三堵墙”
人工智能·软件工程
weixin_469163695 分钟前
金融科技项目管理方式在AI加持下发展方向之,需求分析精准化减少业务与技术偏差
人工智能·科技·金融·项目管理·需求管理
老蒋新思维23 分钟前
借陈修超之智,搭建 AI 与 IP 的创新增长桥梁|创客匠人
网络·人工智能·网络协议·tcp/ip·ip·知识付费·创客匠人
点PY33 分钟前
TR3D: Towards Real-Time Indoor 3D Object Detection论文精读
人工智能·目标检测·3d
咖啡の猫1 小时前
Python的自述
开发语言·python
九年义务漏网鲨鱼1 小时前
【大模型面经】千问系列专题面经
人工智能·深度学习·算法·大模型·强化学习
北京耐用通信1 小时前
“耐达讯自动化Profibus总线光端机在化工变频泵控制系统中的应用与价值解析”
人工智能·科技·物联网·网络安全·自动化·信息与通信
2401_865854881 小时前
AI软件可以帮助我自动化哪些日常任务?
运维·人工智能·自动化