举例说明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]]])
相关推荐
启雀AI3 分钟前
生物医疗行业如何建设合规、安全、可复用的知识库?
人工智能·安全·软件构建·知识图谱·知识库
x-cmd4 分钟前
Mac 涨价后,本地 AI 还能千元入门吗?
linux·人工智能·macos·ai·agent·amd·本地ai入门
To_OC6 分钟前
跑通第一个 MCP Server 后,我终于搞懂它到底解决了什么问题
人工智能·agent·mcp
楷哥爱开发10 分钟前
如何使用 Claude Fable 5 进行网页抓取?2026最新实战教程
大数据·网络·人工智能
YMWM_11 分钟前
lerobot中use_relative_actions=True需要重新计算meta/stats.json等信息
人工智能·深度学习·lerobot
触底反弹12 分钟前
🔥 DeepSeek 560 万美金干翻 OpenAI?一文讲透「蒸馏」的来龙去脉
人工智能
私人珍藏库30 分钟前
[Android] 会计快题库 -财会职称考试刷题学习
android·人工智能·学习·app·软件·多功能
Sirius Wu1 小时前
OpenClaw Skill:Matplotlib 可视化技能 + 沙箱双层隔离完整详解
服务器·网络·人工智能·安全·ai·架构·aigc
闻道且行之1 小时前
TurboOCR:基于PP-OCRv6的极速Windows离线OCR工具,深度解析3.4GB依赖背后的技术架构
c++·人工智能·python·qt·机器学习·ocr
We0 AI1 小时前
2026 年的 B2B 官网竞争,已经不只是页面竞争了
人工智能·aigc·#ai建站