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)
相关推荐
u130130几秒前
AI 日报(2026年10月24日)
人工智能·1024程序员节
Solara2 分钟前
进推荐流的文章不是快 1.42 倍,是 3.36 倍:我把错的数写进了长期记忆
人工智能·程序员·ai编程
Geek-Chow8 分钟前
03 · DeepSeek V4.1 Flash 推理概念地图:E/P/D 分离、Wide-EP、分层 KV 缓存与 7 个关键组件
人工智能
先吃饱再说8 分钟前
LangGraph 状态图:从节点、边到中断恢复,手写一个多 Agent 工作流
人工智能·langchain·llm
Geek-Chow12 分钟前
02 · DeepSeek V4.1 Flash 推理部署是什么:技术报告、DeepInfer 与 deepseek-recipe 的定义和开源边界
人工智能
AI日报派送佬13 分钟前
2026年10月24日AI行业日报|OpenAI离线训练前沿模型、Kimi K3.1 Pro上线API、Prism推理引擎开源
人工智能·openai·1024程序员节·ai智能体·kimi·ai日报
zzu123zsw15 分钟前
为什么 Python 做 Agent 总在并发中崩溃?拆解 Blockcell 在 Rust 下的 Host-Cell 隔离与自愈状态机
开发语言·python·rust·大模型·ai agent
jiangliushi619 分钟前
GPT-6.1 Sol 免费用:Python 读文件报 ‘gbk‘ codec can‘t decode?加一个参数就好
python·编码·1024程序员节
vibecoding7719 分钟前
Kimi K3.1 Pro 发布:2.8 万亿参数、Terminal-Bench 超 GPT-6 Astra,定价砍到 Opus 5.5 一半
人工智能·1024程序员节