举例说明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 分钟前
千问App全球首发点外卖、买东西、订机票等AI购物功能
大数据·人工智能
IT=>小脑虎7 分钟前
Python爬虫零基础学习知识点详解【基础版】
爬虫·python·学习
独自破碎E11 分钟前
说说Copilot模式和Agent模式的区别
人工智能·语言模型·copilot
yhdata24 分钟前
2026年镍合金线行业产业链分析报告
大数据·人工智能
jiguanghover27 分钟前
Langgraph_通过playwright mcp执行自动化
人工智能·agent
清 澜30 分钟前
大模型扫盲式面试知识复习 (二)
人工智能·面试·职场和发展·大模型
kevin 132 分钟前
财务审核场景全覆盖,AI智能审核,自然语言配置规则
人工智能
jieshenai34 分钟前
BERT_Experiment_Template 多种模型与数据集加载,训练、参数保存与评估,适合论文实验的代码模板项目
人工智能·深度学习·bert
蝎蟹居1 小时前
GBT 4706.1-2024逐句解读系列(25) 第7.5条款:不同电压功率需清晰明确
人工智能·单片机·嵌入式硬件·物联网·安全
做萤石二次开发的哈哈1 小时前
萤石开放平台 萤石可编程设备 | 设备 Python SDK 使用说明
开发语言·网络·python·php·萤石云·萤石