举例说明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]]])
相关推荐
DES 仿真实践家1 分钟前
【Day 11-N22】Python类(3)——Python的继承性、多继承、方法重写
开发语言·笔记·python
张较瘦_1 小时前
[论文阅读] 人工智能 + 软件工程 | 需求获取访谈中LLM生成跟进问题研究:来龙去脉与创新突破
论文阅读·人工智能
一 铭2 小时前
AI领域新趋势:从提示(Prompt)工程到上下文(Context)工程
人工智能·语言模型·大模型·llm·prompt
云泽野5 小时前
【Java|集合类】list遍历的6种方式
java·python·list
麻雀无能为力6 小时前
CAU数据挖掘实验 表分析数据插件
人工智能·数据挖掘·中国农业大学
时序之心6 小时前
时空数据挖掘五大革新方向详解篇!
人工智能·数据挖掘·论文·时间序列
IMPYLH6 小时前
Python 的内置函数 reversed
笔记·python
.30-06Springfield6 小时前
人工智能概念之七:集成学习思想(Bagging、Boosting、Stacking)
人工智能·算法·机器学习·集成学习
说私域7 小时前
基于开源AI智能名片链动2+1模式S2B2C商城小程序的超级文化符号构建路径研究
人工智能·小程序·开源
永洪科技7 小时前
永洪科技荣获商业智能品牌影响力奖,全力打造”AI+决策”引擎
大数据·人工智能·科技·数据分析·数据可视化·bi