当前位置: 首页 > news >正文

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

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

torch.cat

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

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

tensor:相同形状的tensor
dim:链接张量的维度,不能超过传入张量的维度

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和输出张量维度(比输入张量维度多一个)之间

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的维度

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):插入维度的指定位置

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)

在这里插入图片描述

http://www.lryc.cn/news/197009.html

相关文章:

  • 聊聊HttpClient的RedirectStrategy
  • 【1day】复现宏景OA KhFieldTree接口 SQL注入漏洞
  • 同为科技TOWE智能PDU引领数据中心机房远控用电安全高效
  • 支付成功后给指定人员发送微信公众号消息
  • 漏洞复现--安恒明御安全网关文件上传
  • 简单的对称加密
  • vue源码笔记之——响应系统
  • Android Studio Giraffe | 2022.3.1
  • Spring Boot 3.0 已经就绪,您准备好了么?
  • 5+非肿瘤分析,分型+WGCNA+机器学习筛选相关基因
  • 算法课作业2 OJ for Divide and Conquer
  • 申请全国400电话的步骤及注意事项
  • C++ 的设计模式之 工厂方法加单例
  • Deploy、Service与Ingress
  • 定制化推送+精细化运营,Mobpush助力《迷你世界》用户留存率提升23%
  • 深度学习零基础教程
  • 简单测试一下 展锐的 UDX710 性能
  • 一百九十、Hive——Hive刷新分区MSCK REPAIR TABLE
  • 智慧公厕:探索未来城市环境卫生设施建设新标杆
  • 高压放大器在无线电能中应用有哪些
  • 若依集成MybatisPlus
  • List小练习,实现添加图书,并且有序遍历
  • 代码随想录二刷 Day42
  • 【Android】Drawable 和src 的区别和理解
  • Linux网络-UDP/TCP协议详解
  • C语言从入门到高级
  • 【MultiOTP】在Linux上使用MultiOTP进行SSH登录
  • 性能超越 Clickhouse | 物联网场景中的毫秒级查询案例
  • 05、SpringBoot 集成 RocketMQ
  • PR2023中如何导入字幕