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)
相关推荐
博、、2 分钟前
AI新零售线上商城系统实战开发指南:从架构设计到部署经验
人工智能·零售
帅哥的AI自修课2 分钟前
模型幻觉检测与抑制技术-金融医疗双案例实战
人工智能·深度学习·金融
小女孩真可爱4 分钟前
GPT(1)----------从零实现 GPT 模型以生成文本
人工智能·python·gpt·nlp
码云骑士6 分钟前
116-Python调用GPT-4V分析图片-Base64编码-多图-JSON结构化输出
开发语言·python·json
程序员cxuan6 分钟前
一招让你的 Claude 被封了也能用
人工智能·后端·程序员
赛逸会展s7 分钟前
2027北京AI健康科技与智慧医疗展6月举办:不是秀场是成交现场
人工智能·科技
Hello_Damon_Nikola8 分钟前
TPA3116D2DADR从入门到精通
人工智能·单片机·嵌入式硬件·物联网
Dachui_11228 分钟前
飞牛 NAS 部署 Hermes AI Agent + ZeroNews 内网穿透,实现远程可管理的 AI 助手
人工智能·ai·远程工作·内网穿透
老郑聊AI业财智造10 分钟前
TensorFlow 技术架构与源码分析
人工智能·python·深度学习·架构·tensorflow·软件工程
民乐团扒谱机11 分钟前
【微科普】压缩感知(CS):违反了奈奎斯特采样定理?不先采集也能还原信号?大白话讲透稀疏采样、L1重建与OMP,一文吃透附代码
python·神经网络·线性代数·算法·数学建模·压缩感知·奈奎斯特