ccc-pytorch-基础操作(2)

news2024/9/20 16:43:16

文章目录

      • 1.类型判断isinstance
      • 2.Dimension实例
      • 3.Tensor常用操作
      • 4.索引和切片
      • 5.Tensor维度变换
      • 6.Broadcast自动扩展
      • 7.合并与分割
      • 8.基本运算
      • 9.统计属性
      • 10.高阶OP

大伙都这么聪明,注释就只写最关键的咯

1.类型判断isinstance

常见类型如下:
image-20230219203754818

 a = torch.randn(2,3)
 a.type()

image-20230219203400016

data = torch.FloatTensor()
isinstance(data,torch.cuda.FloatTensor)
data = data.cuda()
isinstance(data,torch.cuda.FloatTensor)

在这里插入图片描述

2.Dimension实例

Dim0:Loss

torch.tensor(1.0)
torch.tensor(1.3)
a=torch.tensor(2.2)
a.shape
a.size()

image-20230219203939483
Dim1:bias,linear input

a = torch.tensor([1.1])
a.size()
a
a.shape
b = torch.FloatTensor(1)
b.size()

image-20230219204608965
Dim2:linear input batch

 a = torch.randn(2,3)
 a
 a.shape
 a.size(0)
 a.size(1)
 a.shape[1]

在这里插入图片描述
Dim3:RNN input batch

a = toch.rand(1,2,3)
a
a.shape
a[0]

在这里插入图片描述
Dim4:图像输入[b, c, h, w]

a = torch.rand(2,3,28,28)
a
a.shape
list(a.shape)

在这里插入图片描述
Mixed:

a = torch.rand(2,3,28,28)
a.numel()
a.dim()
a = torch.tensor(1)
a.dim()

在这里插入图片描述

3.Tensor常用操作

Import from numpy

a = np.array([2,3.3])
torch.from_numpy(a)
a = np.ones([2,3])
torch.from_numpy(a)

在这里插入图片描述
Import from List

torch.tensor([2.,3.2])
torch.FloatTensor([2.,3.2])#不推荐
torch.tensor([[2.,3.2],[1.,22.3]])

在这里插入图片描述
uninitialized

torch.empty(1)
torch.Tensor(2,3)
torch.IntTensor(2,3)
torch.FloatTensor(2,3)

在这里插入图片描述
set default type

torch.tensor([1.2,3]).type()
torch.set_default_tensor_type(torch.DoubleTensor)
torch.tensor([1.2,3]).type()

在这里插入图片描述
rand/rand_like, randint,randn

torch.rand(3,3)#[0, 1]
a = torch.rand(3,3)
torch.rand_like(a)
torch.randint(1,10,[3,3])#[min, max)
torch.randn(3,3)#N(0,1)

image-20230219212106952
full&arange/range

torch.full([2,3],7)
torch.full([],7)
torch.full([1],7)
torch.arange(0,10)
torch.arange(0,10,2)
torch.range(0,10)#不建议
torch.normal(mean=torch.full([10],0), std=torch.arange(1,0,-0.1))#N(mean,std)

在这里插入图片描述
linspace/logspace

torch.linspace(0,10,steps=4)
torch.linspace(0,10,steps=11)
torch.logspace(0,10,steps=4)

在这里插入图片描述
Ones/zeros/eye

torch.ones(3,3)
torch.zeros(3,3)
torch.eys(3,4)
torch.eys(3,3)
#常用快捷操作
a = torch.zeros(3,3)
torch.ones_like(a)

在这里插入图片描述
randperm

a = torch.rand(2,3)
a
b = torch.rand(2,2)
b
a,b
torch.randperm(10)

在这里插入图片描述

4.索引和切片

Indexing:dim0 优先

a = torch.rand(4,3,28,28)
a[0].shape
a[0,0,2,4]#取值

在这里插入图片描述
select first/last N

a[:2].shape#第一维[0,2)
a[:2,:1,:,:].shape#第一维[0,2),第二维[0,1)
a[:2,1:,:,:].shape#第一维[0,2),第二维[1,_]
a[:2,-1:,:,:].shape#第一维[0,2),第二维(1,_]

在这里插入图片描述
select by steps

a[:,:,0:28:2,0:28:2].shape
a[:,:,::2,::2].shape

在这里插入图片描述
select by specific index

a.index_select(0,torch.tensor([0,2])).shape 
a.index_select(1,torch.tensor([1,2]).shape 
a.index_select(2,torch.arange(8)).shape 

在这里插入图片描述
…:表全部

a[...].shape
a[:,1,...].shape
a[...,:2].shape

在这里插入图片描述
select by mask

x = torch.randn(3,4)
mask = x.ge(0.5)
mask
x
torch.masked_select(x,mask)
torch.masked_select(x,mask).shape

在这里插入图片描述
select by flatten index

 b = torch.tensor([[4,3,5],
                  [6,7,8]])
torch.take(b,torch.tensor([0,2,5]))#返回展开后的索引

在这里插入图片描述

5.Tensor维度变换

View reshape

a = torch.rand(4,1,28,28)
a.shape
a.view(4,28*28)
a.view(4*28,28).shape
b = a.view(4,784)#不推荐,合并尽量写成连乘帮助记忆原数据各维度作用

在这里插入图片描述
Squeeze v.s. unsqueeze

a.shpae
a.unsqueeze(0).shape#第一个空位
a.unsqueeze(-1).shape#最后一个空位
a.unsqueeze(4).shape#第五个空位
a.unsqueeze(-4).shape#倒数第4个空位
a.unsqueeze(-5).shape#导数第5个空位
a.unsqueeze(5).shape#第6个空位,没有

在这里插入图片描述

a = torch.tensor([1.2,2.3])
a.unsqueeze(-1)
a.unsqueeze(0)

image-20230219221608436

b = torch.rand(32)
f = torch.rand(4,32,14,14)
b = b.unsqueeze(1).unsqueeze(2).unsqueeze(0)#每次处理后重新排序
b.shape

image-20230219221758123

b.squeeze().shape#压缩所有为1
b.squeeze(0).shape
b.squeeze(-1).shape
b.squeeze(1).shape#不是1,所以不变
b.squeeze(-4).shape#导数第四个

image-20230219221946606
Expand ( broadcasting)/ repeat(memory copied)

a = torch.rand(4,32,14,14)
b.shape
b.expand(4,32,14,14).shape
b.repeat(4,32,1,1).shape

image-20230219222354763
.t:转置

a = torch.randn(3,4)
a
a.t()#注意高维转置不了

image-20230219222611746
Transpose

a.shape
a1 = a.transpose(1,3)#交换次序
a1.shape

image-20230219223234601
permute

b = torch.rand(4,3,28,32)
b.transpose(1,3).shape
b.transpose(1,3).transpose(1,2).shape
b.permute(0,2,3,1).shape#按索引排列

image-20230219223519170

6.Broadcast自动扩展

broadcast是不同size的tensor进行加减时自动进行的机制,其主要思想以及特点如下:

  • 从最右边的维度开始匹配,前面维度缺失的补1直到维度相同
  • 从最右边的维度开始匹配,维度不等但有一个是1则扩展到相同的值,实例如下:
    image-20230220142625094
  • 节约内存,核心是利用expand,只进行逻辑上的扩展而不会实际拷贝

7.合并与分割

Cat

a = torch.rand(4,3,32,32)
b = torch.rand(5,3,32,32)
a2= torch.rand(4,1,32,32)
torch.cat([a,a2],dim=1).shape
torch.cat([a,a2],dim=0).shape#Error,多个维度不同

image-20230220143834187
stack

a1=torch.rand(4,3,16,32)
a2=torch.rand(4,3,16,32)
torch.cat([a1,a2],dim=2).shape
torch.stack([a1,a2],dim=2).shape

image-20230220144151154
Cat与stack的区别:前者是合并dim,后者是增加dim;后者要求所有一摸一样
Split: by len

c = torch.rand(2,32,8)
aa, bb = c.split([1,1],dim=0)
aa.shape, bb.shape
aa, bb = c.split([2,0],dim=0)
aa.shape, bb.shape
aa, bb = c.split(1,dim=0)
aa.shape, bb.shape
aa, bb = c.split(2,dim=0)

在这里插入图片描述
Chunk: by num

c.shape
aa, bb = c.chunk(2,dim=0)

image-20230220145316617

8.基本运算

basic

a =torch.rand(3,4)
a
b =torch.rand(4)
b
a+b
torch.add(a,b)
torch.all(torch.eq(a-b,torch.sub(a,b)))
torch.all(torch.eq(a*b,torch.mul(a,b)))
torch.all(torch.eq(a/b,torch.div(a,b)))

image-20230220160151657
matmul

a
b = torch.ones(2,2)
b
torch.mm(a,b)#only for 2dim
torch.matmul(a,b)
a@b

image-20230220160506308

a = torch.rand(4,784)
x = torch.rand(4,784)
w = torch.rand(512,784)
(x@w.t()).shape

image-20230220160749310
>2d tensor matmul?

a =torch.rand(4,3,28,64)
b =torch.rand(4,3,64,32)
torch.mm(a,b).shape#用不了2D以上
torch.matmul(a,b).shape#只计算最后两维
b = torch.rand(4,1,64,32)
torch.matmul(a,b).shape#触发Broadcast机制

image-20230220161518890
Power

a = torch.full([2,2],3)
a.pow(2)
a**2
aa = a**2
aa.sqrt()
aa.rsqrt()#平方根的倒数
aa**(0.5)

在这里插入图片描述
Exp log

a = torch.exp(torch.ones(2,2))
a
torch.log(a)

image-20230220162031968
Approximation

a =torch.tensor(3.14)
a.floor(),a.ceil(),a.trunc(),a.frac()#分别是向下取整,向上取整,整数部分,小数部分
a =torch.tensor(3.4999)
a.round()#4舍5入
a = torch.tensor(3.5)
a.round()

在这里插入图片描述
clamp

grad = torch.rand(2,3)*15
grad
grad.max()
grad.median()
grad.clamp(10)
grad.clamp(0,10)

image-20230220163632170
简单解释一下:

torch.clamp(input, min=None, max=None, *, out=None)
限定一个范围,input tensor中数值低于min的返回min,高于max的返回max

9.统计属性

norm1&norm2

a =torch.full([8],1)
a
b=a.view(2,4)
c=a.view(2,2,2)
b
c
a.norm(1),b.norm(1),c.norm(1)#1范数,绝对值之和
a.norm(2),b.norm(2),c.norm(2)#2范数,欧几里得范数,平方和再开方
b.norm(1,dim=1)
b.norm(2,dim=1)
c.norm(1,dim=0)
c.norm(2,dim=0)

在这里插入图片描述
mean, sum, min, max, prod,argmin, argmax

a =torch.arange(8).view(2,4).float()
a
a.min(),a.max(),a.mean(),a.prod()
a.sum()
a.argmax(),a.argmin()#返回索引位置

image-20230220170104467

a=torch.rand(2,3,4)
a
a.argmax()
a=torch.randn(4,10)
a
a.argmax()
a.argmax(dim=1)#相应维度上索引

在这里插入图片描述
dim, keepdim

a
a.max(dim=1)
a.max(dim=1,keepdim=True)#保持输出的维度

在这里插入图片描述
Top-k or k-th

a
a.topk(3,dim=1)
a.topk(3,dim=1,largest=False)#1维最小的前3个
a.kthvalue(8,dim=1)
a.kthvalue(3)#默认选择最后一个维度

在这里插入图片描述
compare

a
a>0
torch.gt(a,0)
(a>0).type()
torch.gt(a,0)
a!=0
a=torch.ones(2,3)
b=torch.randn(2,3)
torch.eq(a,b)
torch.eq(a,a)#逐元素比较
torch.equal(a,a)# 张量比较

在这里插入图片描述

10.高阶OP

Where
在这里插入图片描述
condition成立则填充x否则填充y

cond = torch.rand(2,2)
cond
a =torch.zeros(2,2)
b =torch.ones(2,2)
a,b
torch.where(cond>0.5,a,b)
torch.where(cond<0.5,a,b)

在这里插入图片描述
gather
image-20230220173242533image-20230220173912124

  • 输入input和索引index不会Broadcast
  • output形状与index相同
  • 索引与dim方向相同
  • index.size(dim)<=input.size(dim),保证有元素可取
prob = torch.randn(4,10)
prob
idx = prob.topk(dim=1,k=3)
idx
idx=idx[1]
idx
label = torch.arange(10)+100
label 
torch.gather(label.expand(4,10),dim=1,index=idx.long())

在这里插入图片描述

#其中有
label.expand(4,10)
idx.long()

在这里插入图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/360005.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

iOS开发:对苹果APNs远程推送原理的理解

本篇是对APNs推送原理的一个理解,希望看完后,能让你掌握一个知识点。 APNs是Apple Push Notification Service的缩写,也就是苹果的推送服务器。 远程通知的传递涉及几个关键组件: 您公司的服务器或第三方服务商,称为提供商服务器Apple 推送通知服务 (APNs)用户的设备您的…

Netty进阶实现自定义Rpc

项目地址&#xff1a;xz125/Rpc-msf (github.com)1 项目架构&#xff1a;RPC 框架包含三个最重要的组件&#xff0c;分别是客户端、服务端和注册中心。在一次 RPC 调用流程中&#xff0c;这三个组件是这样交互的&#xff1a;服务端(provider)在启动后会将它提供的服务列表和地址…

RocketMQ 第一章

RocketMQ 第一章 1、什么是MQ Message Queue&#xff08;消息队列&#xff09;&#xff0c;从字⾯上理解&#xff1a;⾸先它是⼀个队列。FIFO 先进先出的数据结构 —— 队列。消息队列就是所谓的存放消息的队列。 消息队列解决的不是存放消息的队列的⽬的&#xff0c;而是解…

AcWing1015.摘花生

AcWing 1015. 摘花生Hello Kitty想摘点花生送给她喜欢的米老鼠。她来到一片有网格状道路的矩形花生地(如下图)&#xff0c;从西北角进去&#xff0c;东南角出来。地里每个道路的交叉点上都有种着一株花生苗&#xff0c;上面有若干颗花生&#xff0c;经过一株花生苗就能摘走该它…

《FPGA学习》->蜂鸣器播放

&#x1f34e;与其担心未来&#xff0c;不如现在好好努力。在这条路上&#xff0c;只有奋斗才能给你安全感。你若努力&#xff0c;全世界都会为你让路。蜂鸣器的发声原理由振动装置和谐振装置组成&#xff0c;而蜂鸣器又分为无源他激型与有源自激型。本实验采用无源蜂鸣器&…

嵌入物理(PINN)还是基于物理(AD)?

文章目录1. 传统"反演问题"1.1 反演问题是什么1.2 常见反演问题1.3 传统反演问题的困境2. 深度学习优势3. AD inversion 例子3.1 ADsurf3.2 ADseismic关于PINN的内容大家可以直接google PINN (Physical-informed neural network),其主要的目的是用一个神经网络拟合物…

K8S 部署 Jenkins

本文使用 bitnami 镜像部署 Jenkins 官方文档&#xff1a;https://github.com/bitnami/charts/tree/main/bitnami/jenkins 添加 bitnami 仓库 helm repo add bitnami https://charts.bitnami.com/bitnami自定义 values.yaml storageClass&#xff1a;集群的存储类&#xff…

(考研湖科大教书匠计算机网络)第五章传输层-第八节1:TCP连接管理理论部分(三次握手与四次挥手)

获取pdf&#xff1a;密码7281专栏目录首页&#xff1a;【专栏必读】考研湖科大教书匠计算机网络笔记导航此部分内容借鉴博主【小林coding】 &#xff0c;其对计算机网络内容的图解可以说是深入浅出&#xff0c;尤其是三次握手和四次挥手这一部分&#xff0c;堪称全网最佳。所这…

OpenEuler安装软件方法

在树莓派上烧录好OpenEuler后上面是什么软件都没有的&#xff0c;像一些gcc的环境都需要自己进行配置。官方提供的安装命令是yum&#xff0c;但是执行yum是找不到命令的&#xff1a;   这个其实是因为OpenEuler中默认的安装软件使用了dnf而不是yum&#xff0c;所以软件的安装…

智能小车红外跟随原理

红外跟随电路红外跟随电路由电位器R17&#xff0c;R28&#xff1b;发光二极管D8&#xff0c;D9&#xff1b;红外发射管 D2&#xff0c;D4和红外接收管D3&#xff0c;D5和芯片LM324等组成,LM234用于信号的比较&#xff0c;并产生比较结果输出给单片机进行处理。智能小车红外跟随…

OpenGL学习日志之纹理

引言 为了使我们渲染的模型拥有更多细节&#xff0c;我们可以添加足够多的顶点&#xff0c;然后给每一个顶点都添加顶点颜色。但是这样就会产生很多额外的开销&#xff0c;因此就出现了纹理映射技术&#xff0c;我们通过纹理采样为物体的表面添加更多的细节。 纹理定义 通俗…

超25亿全球月活,字节依然没有流量

&#xff08;图片来源于网络&#xff0c;侵删&#xff09; 文|螳螂观察 作者| 搁浅虎鲸 注意看&#xff0c;这个男人叫梁汝波&#xff0c;是字节跳动的联合创始人&#xff0c;也是接棒张一鸣的新任CEO。 在字节跳动十周年之际&#xff0c;他发表了激情昂扬的演讲。“激发创…

【Datawhale图机器学习】图嵌入表示学习

图嵌入表示学习 学习视频&#xff1a;https://www.bilibili.com/video/BV1AP4y1r7Pz/ 如何把节点映射成D维向量&#xff1f; 人工特征工程&#xff1a;节点重要度、集群系数、Graphlet图表示学习&#xff1a;通过随机游走构造自监督学习任务。DeepWalk、Node2Vec矩阵分解深度…

win10字体模糊怎么办?看下面4种宝藏解决方法

最近很多用户反映电脑安装了Win10系统后出现字体发虚&#xff0c;模糊不清的问题&#xff0c;这看起来让人非常难受。win10字体模糊怎么办&#xff1f;来看下面4种宝藏解决方法&#xff01;下面的方法适用于各类台式电脑以及笔记本电脑哦&#xff01; 操作环境&#xff1a; 演示…

ESP开发环境搭建

一、windows中搭建 esp-idf tool(可选),下载连接如下:https://dl.espressif.com/dl/esp-idf/?idf4.4 下载安装tools后进入vscode进行插件安装&#xff08;未离线下载idf工具也可以通过第二步通过插件下载安装&#xff09; 1. vscode安装编译环境 ESP-IDF 需要安装一些必备工…

高并发系统设计之负载均衡

本文已收录至Github&#xff0c;推荐阅读 &#x1f449; Java随想录 文章目录DNS负载均衡Nginx负载均衡负载均衡算法负载均衡配置超时配置被动健康检查与主动健康检查LVS/F5Nginx当我们的应用单实例不能支撑用户请求时&#xff0c;此时就需要扩容&#xff0c;从一台服务器扩容到…

【matplotlib】可视化解决方案——如何设置轴标签的透明度和大小

概述 Axes 标签对于读者理解图表非常重要&#xff0c;它描述了图表中展现的数据内容。通过向 axes 对象添加标签&#xff0c;可以有效理解图表所表达的内容。首先来了解一下 matplotlib 是如何组织图表的。最上层是一个 Figure 实例&#xff0c;包含绘图中所有可见和不可见的内…

北斗导航 | 2023 PTTI会议论文 2023 ITM会议论文 2022 ION GNSS+ 会议论文下载:ION 美国导航学会

===================================================== github:https://github.com/MichaelBeechan CSDN:https://blog.csdn.net/u011344545 ===================================================== 2023 PTTI会议论文 2023 ITM会议论文 2022 ION GNSS+ 论文下载百度云链…

Teradata当年数据仓库的“一哥”为何突然退出中国市场:苦撑了3年,员工早有预料

2月15日&#xff0c;Teradata天睿公司官宣即将撤离中国市场。 又是一个艰难的决定&#xff0c;听着似乎很熟悉。Teradata为什么突然宣布结束在中国的直营&#xff1f;其实&#xff0c;回顾Teradata在中国市场的发展状况&#xff0c;一点也不突然。 多年前&#xff0c;我曾经与…

Excel表格自动转Json数据

Excel表格转JSON格式在实际工作中&#xff0c;我们常常使用Excel记录各种数据&#xff0c;但在各种应用系统传输数据却使用JSON格式&#xff0c;这就需要把Excel转为JSON。如果能把数据转换传输过程自动化就更完美了。Excel转JsonXX公司生产日报表为例&#xff0c;生产工人用Ex…