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)
相关推荐
badhope8 分钟前
Agent 说发布成功,文章却 404:我补了 4 张回读收据
后端·python·ai编程
m0_7196408713 分钟前
2026年高校AI教学实验适配的科研教学机器人选型指南
人工智能·经验分享·机器人
xurileidian13 分钟前
第 30 篇 · 边玩边学Python · 猜数字小游戏 把判断循环异常串起来
前端·python·算法
用户960984579224021 分钟前
改造 agy 启动体验:agyr 启动器、目录级会话隔离与终端五色通知
人工智能
翰墨之道21 分钟前
从RSA-2048到处理器缓存:AI安全边界的三重信号
人工智能·安全·缓存
玫瑰互动GEO27 分钟前
M4推理成本信号:架构优化改写GEO竞争逻辑
大数据·数据库·人工智能·ai·架构·m4·geo优化
用户13359939454232 分钟前
我是如何在一张2000元的卡上把 Qwen4-35B-A3B 从 8tok/s 调到 80tok/s 的?
人工智能·性能优化
远航计算机35 分钟前
豆包GEO算法实证:引用池到答案之间,还有8.3%入选与13%失配两道关
人工智能·深度学习·算法
Rosanci38 分钟前
Agent 测试总分达标就能上线吗?把关键场景失败设为独立发布门禁
大数据·人工智能·agent·ai 办公
360亿方智能1 小时前
律所案件资料如何安全地交给AI使用?中闻AI本地存储与分级授权实践
大数据·人工智能