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

ccc-pytorch-基础操作(2)

文章目录

      • 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)aa.shapea.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()

在这里插入图片描述

相关文章:

ccc-pytorch-基础操作(2)

文章目录1.类型判断isinstance2.Dimension实例3.Tensor常用操作4.索引和切片5.Tensor维度变换6.Broadcast自动扩展7.合并与分割8.基本运算9.统计属性10.高阶OP大伙都这么聪明&#xff0c;注释就只写最关键的咯1.类型判断isinstance 常见类型如下&#xff1a; a torch.randn(…...

独居老人一键式报警器

盾王居家养老一键式报警系统&#xff0c;居家养老一键式报警设备 &#xff0c;一键通紧急呼救设备&#xff0c;一键通紧急呼救系统&#xff0c;一键通紧急呼救器 &#xff0c;一键通紧急呼救终端&#xff0c;一键通紧急呼救主机终端产品简介&#xff1a; 老人呼叫系统主要应用于…...

软考案例分析题精选

试题一&#xff1a;阅读下列说明&#xff0c;回答问题1至问题4&#xff0c;将解答填入答题纸的对应栏内。某公司中标了一个软件开发项目&#xff0c;项目经理根据以往的经验估算了开发过程中各项任务需要的工期及预算成本&#xff0c;如下表所示&#xff1a;任务紧前任务工期PV…...

基于SpringBoot+vue的无偿献血后台管理系统

基于SpringBootvue的无偿献血后台管理系统 ✌全网粉丝20W,csdn特邀作者、博客专家、CSDN新星计划导师、java领域优质创作者,博客之星、掘金/华为云/阿里云/InfoQ等平台优质作者、专注于Java技术领域和毕业项目实战✌ &#x1f345;文末获取项目下载方式&#x1f345; 一、项目背…...

详解js在事件中,如何传递复杂数据类型(数组,对象,函数)

文章目录 前言一、何谓预编译&#xff0c;变量提升&#xff1f;二、复杂数据类型的传递 1.数组2.对象3.函数总结前言 在JavaScript这门编程语言学习中&#xff0c;如何传参&#xff0c;什么是变量提升&#xff0c;js代码预编译等等。要想成为一名优秀的js高手&#xff0c;这些内…...

高并发架构 第一章大型网站数据演化——核心解释与说明。大型网站技术架构——核心原理与案例分析

大型网站架构烟花发展历程1.1.1初始阶段的网站构架1.1.2应用服务和数据服务分离1.1.3使用缓存改善网络性能1.1.4使用应用服务器集群改善网站的并发处理能力1.1.5数据库读写分离1.1.6使用反向代理和cdn加速网站相应1.1.1初始阶段的网站构架 大型网站都是由小型网站一步步发展而…...

VPP接口INPUT节点运行数据

在设置virtio接口接收/发送队列函数的最后&#xff0c;更新接口的运行数据。 void virtio_vring_set_rx_queues (vlib_main_t *vm, virtio_if_t *vif) { ...vnet_hw_if_update_runtime_data (vnm, vif->hw_if_index); } void virtio_vring_set_tx_queues (vlib_main_t *vm,…...

RabbitMQ学习(九):延迟队列

一、延迟队列概念延时队列中&#xff0c;队列内部是有序的&#xff0c;最重要的特性就体现在它的延时属性上&#xff0c;延时队列中的元素是希望 在指定时间到了以后或之前取出和处理。简单来说&#xff0c;延时队列就是用来存放需要在指定时间内被处理的 元素的队列。其实延迟…...

TCP并发服务器(多进程与多线程)

欢迎关注博主 Mindtechnist 或加入【Linux C/C/Python社区】一起探讨和分享Linux C/C/Python/Shell编程、机器人技术、机器学习、机器视觉、嵌入式AI相关领域的知识和技术。 TCP并发服务器&#xff08;多进程与多线程&#xff09;1. 多进程并发服务器&#xff08;1&#xff09;…...

第1章 Memcached 教程

Memcached是一个自由开源的&#xff0c;高性能&#xff0c;分布式内存对象缓存系统。 Memcached是以LiveJournal旗下Danga Interactive公司的Brad Fitzpatric为首开发的一款软件。现在已成为mixi、hatena、Facebook、Vox、LiveJournal等众多服务中提高Web应用扩展性的重要因素…...

【2022.12.9】Lammps+Python 在计算g6(r)时遇到的问题

目录写在前面绘制g6( r )执行步骤【updated】如何检查图像的正确性&#xff1a;不是编程问题&#xff0c;而是数学问题的一个小bug废稿2则&#xff1a;写在前面 全部log&#xff1a; 【2022.11.16】LammpsPythonMATLAB在绘制维诺图时遇到的问题 绘制g6( r )执行步骤【updated…...

MySQL使用C语言连接

文章目录MySQL使用C语言连接引入库下载库文件在项目中使用库使用库连接数据库下发SQL请求获取查询结果MySQL使用C语言连接 引入库 要使用C语言连接MySQL&#xff0c;需要使用MySQL官网提供的库。 下载库文件 下载库文件 首先&#xff0c;进入MySQL官网&#xff0c;选择DEVEL…...

JavaScript随手笔记---比较两个数组差异

&#x1f48c; 所属专栏&#xff1a;【JavaScript随手笔记】 &#x1f600; 作  者&#xff1a;我是夜阑的狗&#x1f436; &#x1f680; 个人简介&#xff1a;一个正在努力学技术的CV工程师&#xff0c;专注基础和实战分享 &#xff0c;欢迎咨询&#xff01; &#…...

【C++修炼之路】21.红黑树封装map和set

每一个不曾起舞的日子都是对生命的辜负 红黑树封装map和set前言一.改良红黑树的数据域结构1.1 改良后的结点1.2 改良后的类二. 封装的set和map2.1 set.h2.2 map.h三. 迭代器3.1 迭代器封装3.2 const迭代器四.完整代码实现4.1 RBTree.h4.2 set.h4.3 map.h4.4 Test.cpp前言 上一节…...

下载ojdbc14.jar的10.2.0.1.0版本的包

一、首先要有ojdbc14.jar包 没有的可以去下载一个&#xff0c;我的是从这里下载的ojdbc14.jar下载_ojdbc14.jar最新版下载[驱动包软件]-下载之家&#xff0c; 就是无奈关注了一个公众号&#xff0c;有的就不用下了。 二、找到maven的本地仓库的地址 我的地址在这里D:\apach…...

关于欧拉角你需要知道几个点

基础理解&#xff0c;参照&#xff1a;https://www.cnblogs.com/Estranged-Tech/p/16903025.html 欧拉角、万向节死锁&#xff08;锁死&#xff09;理解 一、欧拉角理解 举例讲解 欧拉角用三次独立的绕确定的轴旋转角度来表示姿态。如下图所示 经过三次旋转&#xff0c;旋…...

git ssh配置

ssh配置 执行以下命令进行配置 git config --global user.name “这里换上你的用户名” git config --global user.email “这里换上你的邮箱” 执行以下命令生成秘钥&#xff1a; ssh-keygen -t rsa -C “这里换上你的邮箱” 执行命令后需要进行3次或4次确认。直接全部回车就…...

Linux进程概念(三)

环境变量与进程地址空间环境变量什么是环境变量常见环境变量环境变量相关命令环境变量的全局属性PWDmain函数的三个参数进程地址空间什么是进程地址空间进程地址空间&#xff0c;页表&#xff0c;内存的关系为什么存在进程地址空间环境变量 什么是环境变量 我们所有写的程序都…...

新手福利——x64逆向基础

一、x64程序的内存和通用寄存器 随着游戏行业的发展&#xff0c;x32位的程序已经很难满足一些新兴游戏的需求了&#xff0c;因为32位内存的最大值为0xFFFFFFFF&#xff0c;这个值看似足够&#xff0c;但是当游戏对资源需求非常大&#xff0c;那么真正可以分配的内存就显得捉襟…...

虚幻c++中的细节之枚举类型(enum)

文章目录前言一、原生c的枚举类型关键字classint8 - 枚举的基础类型&#xff08;underlying type&#xff09;二、枚举类型的灵活运用位运算枚举循环遍历三、虚幻风格的枚举类型UENUMUMETATEnumAsByte总结前言 虚幻引擎中的代码部分实现了一套反射机制&#xff0c;为c代码带了…...

idea大量爆红问题解决

问题描述 在学习和工作中&#xff0c;idea是程序员不可缺少的一个工具&#xff0c;但是突然在有些时候就会出现大量爆红的问题&#xff0c;发现无法跳转&#xff0c;无论是关机重启或者是替换root都无法解决 就是如上所展示的问题&#xff0c;但是程序依然可以启动。 问题解决…...

微信小程序之bind和catch

这两个呢&#xff0c;都是绑定事件用的&#xff0c;具体使用有些小区别。 官方文档&#xff1a; 事件冒泡处理不同 bind&#xff1a;绑定的事件会向上冒泡&#xff0c;即触发当前组件的事件后&#xff0c;还会继续触发父组件的相同事件。例如&#xff0c;有一个子视图绑定了b…...

UDP(Echoserver)

网络命令 Ping 命令 检测网络是否连通 使用方法: ping -c 次数 网址ping -c 3 www.baidu.comnetstat 命令 netstat 是一个用来查看网络状态的重要工具. 语法&#xff1a;netstat [选项] 功能&#xff1a;查看网络状态 常用选项&#xff1a; n 拒绝显示别名&#…...

LeetCode - 394. 字符串解码

题目 394. 字符串解码 - 力扣&#xff08;LeetCode&#xff09; 思路 使用两个栈&#xff1a;一个存储重复次数&#xff0c;一个存储字符串 遍历输入字符串&#xff1a; 数字处理&#xff1a;遇到数字时&#xff0c;累积计算重复次数左括号处理&#xff1a;保存当前状态&a…...

dedecms 织梦自定义表单留言增加ajax验证码功能

增加ajax功能模块&#xff0c;用户不点击提交按钮&#xff0c;只要输入框失去焦点&#xff0c;就会提前提示验证码是否正确。 一&#xff0c;模板上增加验证码 <input name"vdcode"id"vdcode" placeholder"请输入验证码" type"text&quo…...

376. Wiggle Subsequence

376. Wiggle Subsequence 代码 class Solution { public:int wiggleMaxLength(vector<int>& nums) {int n nums.size();int res 1;int prediff 0;int curdiff 0;for(int i 0;i < n-1;i){curdiff nums[i1] - nums[i];if( (prediff > 0 && curdif…...

生成 Git SSH 证书

&#x1f511; 1. ​​生成 SSH 密钥对​​ 在终端&#xff08;Windows 使用 Git Bash&#xff0c;Mac/Linux 使用 Terminal&#xff09;执行命令&#xff1a; ssh-keygen -t rsa -b 4096 -C "your_emailexample.com" ​​参数说明​​&#xff1a; -t rsa&#x…...

C++ 基础特性深度解析

目录 引言 一、命名空间&#xff08;namespace&#xff09; C 中的命名空间​ 与 C 语言的对比​ 二、缺省参数​ C 中的缺省参数​ 与 C 语言的对比​ 三、引用&#xff08;reference&#xff09;​ C 中的引用​ 与 C 语言的对比​ 四、inline&#xff08;内联函数…...

论文浅尝 | 基于判别指令微调生成式大语言模型的知识图谱补全方法(ISWC2024)

笔记整理&#xff1a;刘治强&#xff0c;浙江大学硕士生&#xff0c;研究方向为知识图谱表示学习&#xff0c;大语言模型 论文链接&#xff1a;http://arxiv.org/abs/2407.16127 发表会议&#xff1a;ISWC 2024 1. 动机 传统的知识图谱补全&#xff08;KGC&#xff09;模型通过…...

2023赣州旅游投资集团

单选题 1.“不登高山&#xff0c;不知天之高也&#xff1b;不临深溪&#xff0c;不知地之厚也。”这句话说明_____。 A、人的意识具有创造性 B、人的认识是独立于实践之外的 C、实践在认识过程中具有决定作用 D、人的一切知识都是从直接经验中获得的 参考答案: C 本题解…...