Pytorch:cat、stack、squeeze、unsqueeze的用法

Pytorch:cat、stack、squeeze、unsqueeze的用法

torch.cat

在指定原有维度上链接传入的张量,所有传入的张量都必须是相同形状

torch.cat(tensors, dim=0, *, out=None) → Tensor

tensor:相同形状的tensor

dim:链接张量的维度,不能超过传入张量的维度

python 复制代码
x = torch.tensor([[0, 1, 2]], dtype= torch.float)
y = torch.tensor([[3, 4, 5]], dtype= torch.int)
print(x.shape, y.shape)
print("-"*50)
z = torch.cat((x, y), dim= 0)
print(z)
print(z.shape)
print("-"*50)
z = torch.cat((x, y), dim= 1)
print(z)
print(z.shape)

torch.stack

在一个新的维度上链接张量,输入张量都必须是相同形状的

torch.stack(tensors, dim=0, *, out=None) → Tensor

tensor:相同形状的张量

dim:插入的张量维度,在0和输出张量维度(比输入张量维度多一个)之间

python 复制代码
x = torch.tensor([[0, 1, 2]])
y = torch.tensor([[3, 4, 5]])
print(x.shape, y.shape)
print("-"*50)
z = torch.stack((x, y), dim= 0)
print(z)
print(z.shape)
print("-"*50)
z = torch.stack((x, y), dim= 1)
print(z)
print(z.shape)
print("-"*50)
z = torch.stack((x, y), dim= 2)
print(z)
print(z.shape)

torch.squeeze

压缩张量,去掉输入张量中大小为1的维度,例如:(Ax1xBxCx1)->(AxBxC)

torch.squeeze(input, dim=None) → Tensor

input (Tensor):输入张量

dim (int or tuple of ints, optional):只压缩某个维度,可以不指定,就是压缩所有大小为1的维度

python 复制代码
x = torch.tensor([[0, 1, 2]])
y = torch.rand(size= (1, 2, 1, 2, 1))
print(x.shape, y.shape)
print("-"*50)
z = torch.squeeze(x)
print(z)
print(z.shape)
print("-"*50)
z = torch.squeeze(y)
print(z)
print(z.shape)

torch.unsqueeze

在输入张量中指定位置插入一个大小为1的维度

torch.unsqueeze(input, dim) → Tensor

input (Tensor):输入张量

dim (int):插入维度的指定位置

python 复制代码
x = torch.randn(size= (2,3))
print(x.shape)
print("-"*50)
z = torch.unsqueeze(x, 0)
print(z)
print(z.shape)
print("-"*50)
z = torch.unsqueeze(x, 1)
print(z)
print(z.shape)
相关推荐
fkyyly2 分钟前
企业 Agent 落地的两场战争:内部经营闭环与 ToB 外部规模赋能
人工智能·codeagent
看浪的路人5 分钟前
第9讲:AI 应用混沌工程与容灾演练
人工智能
workflower13 分钟前
AI system product quality model
大数据·人工智能·机器学习·云计算·无人机
众链网络15 分钟前
从 GB/T 30225-2026 的「数据管理」章节,反推景区票务系统的数据层设计
人工智能
kaixin_啊啊18 分钟前
【零基础学AI】第 1 章课后练习与答案
人工智能·ai
yl453021 分钟前
硫酸泄露处理生产商怎么选才够专业
大数据·人工智能·python
搬砖的小码农_Sky23 分钟前
AI Agent:Claude Code以及相关竞品简介
人工智能·人机交互
笨笨饿25 分钟前
140_AI新手村MCP与Skills是干嘛的
开发语言·人工智能·python·stm32·单片机·嵌入式硬件·物联网
看浪的路人34 分钟前
第10讲:AI 应用可观测性全景总结与生产实战
人工智能
青柠之夏cc39 分钟前
AI与教育:个性化学习助手让“因材施教“成为现实,但代价是隐私?
人工智能·学习