Pytorch有关张量的各种操作

一,创建张量

1. 生成float格式的张量:

a = torch.tensor([1,2,3],dtype = torch.float)

2. 生成从1到10,间隔是2的张量:

b = torch.arange(1,10,step = 2)

3. 随机生成从0.0到6.28的10个张量

注意:
(1).生成的10个张量中包含0.0和6.28(两端点)
(2).生成的张量步长是随机的

c = torch.linspace(0.0,2*3.14,10)

4. zeros_like是生成与a格式相同,但是是全0且格式是float的张量

a = torch.ones((3,3),dtype = torch.int)
b = torch.zeros_like(a,dtype = torch.float)

5. 将b中为0或NULL元素替换成5

torch.fill_(b,5)

6. 均匀随机分布:torch.manual_seed(0)为CPU中设置种子,生成随机数

torch.manual_seed(0)
minval,maxval = 0,10
a = minval + (maxval-minval)*torch.rand([5])

7. 正态分布随机

均值means是一个张量,包含每个输出元素相关的正态分布的均值。
std是一个张量,包含每个输出元素相关的正态分布的标准差。
均值和标准差的形状不须匹配,但每个张量的元素个数须相同。

b = torch.normal(mean = torch.zeros(3,3), std = torch.ones(3,3))

8. 正态分布随机

mean,std = 2,5
c = std*torch.randn((3,3))+mean

9. 整数随机排列

d = torch.randperm(20) 

10. 生成特殊矩阵

I = torch.eye(3,3) #单位矩阵
t = torch.diag(torch.tensor([1,2,3])) #对角矩阵

二,索引切片

张量的索引切片方式和numpy几乎是一样的。切片时支持缺省参数和省略号。

1.切片第1行至第3行

print(t[1:4,:])

2.切片第1行至最后一行,第0列到最后一列每隔两列取一列

print(t[1:4,:4:2])

3.可以使用索引和切片修改部分元素

x = torch.tensor([[1,2],[3,4]],dtype = torch.float32,requires_grad=True)
x.data[1,:] = torch.tensor([0.0,0.0])

4.对于不规则的切片提取

可以使用torch.index_select, torch.take, torch.gather, torch.masked_select.

  1. 抽取每个班级第0个学生,第5个学生,第9个学生的全部成绩
torch.index_select(scores,dim = 1,index = torch.tensor([0,5,9]))
  1. 抽取每个班级第0个学生,第5个学生,第9个学生的第1门课程,第3门课程,第6门课程成绩
q = torch.index_select(torch.index_select(scores,dim = 1,index = torch.tensor([0,5,9])),dim=2,index = torch.tensor([1,3,6]))
  1. 抽取第0个班级第0个学生的第0门课程,第2个班级的第4个学生的第1门课程,第3个班级的第9个学生第6门课程成绩
    take将输入看成一维数组,输出和index同形状
s = torch.take(scores,torch.tensor([0*10*7+0,2*10*7+4*7+1,3*10*7+9*7+6]))   #感觉跟数组序列号一样
  1. 抽取分数大于等于80分的分数(布尔索引),结果是1维张量
g = torch.masked_select(scores,scores>=80)

5.通过修改张量的部分元素值得到新的张量

torch.where可以理解为if的张量版本。
torch.index_fill的选取元素逻辑和torch.index_select相同。
torch.masked_fill的选取元素逻辑和torch.masked_select相同。

  1. 如果分数大于60分,赋值成1,否则赋值成0
ifpass = torch.where(scores>60,torch.tensor(1),torch.tensor(0))
  1. 将每个班级第0个学生,第5个学生,第9个学生的全部成绩赋值成满分
torch.index_fill(scores,dim = 1,index = torch.tensor([0,5,9]),value = 100)
#等价于 scores.index_fill(dim = 1,index = torch.tensor([0,5,9]),value = 100)
  1. 将分数小于60分的分数赋值成60分
b = torch.masked_fill(scores,scores<60,60)
#等价于b = scores.masked_fill(scores<60,60)

三,维度变换相关函数

维度变换相关函数主要有 torch.reshape(或者调用张量的view方法),torch.squeeze,torch.unsqueeze, torch.transpose
torch.reshape 可以改变张量的形状。
torch.squeeze 可以减少维度。
torch.unsqueeze 可以增加维度。
torch.transpose 可以交换维度。

1. 改成 (3,6)形状的张量

b = a.view([3,6]) #torch.reshape(a,[3,6])

2. 改回成 [1,3,3,2] 形状的张量

c = torch.reshape(b,[1,3,3,2]) # b.view([1,3,3,2])

3. torch.squeeze消除维度。

如果张量在某个维度上只有一个元素,利用torch.squeeze可以消除这个维度。

s = torch.squeeze(a)

4. torch.unsqueeze

torch.unsqueeze的作用和torch.squeeze的作用相反,增加维度。

#在第0维插入长度为1的一个维度
d = torch.unsqueeze(s,axis=0)

5.转换成 Pytorch默认的图片格式

torch.transpose可以交换张量的维度,torch.transpose常用于图片存储格式的变换上。
如果是二维的矩阵,通常会调用矩阵的转置方法 matrix.t(),等价于 torch.transpose(matrix,0,1)。

# 转换成 Pytorch默认的图片格式 Batch,Channel,Height,Width
# 需要交换两次
data_t = torch.transpose(torch.transpose(data,1,2),1,3)print(matrix.t()) #等价于torch.transpose(matrix,0,1)

四,合并分割

可以用torch.cat方法和torch.stack方法将多个张量合并,可以用torch.split方法把一个张量分割成多个张量。

1.torch.cat和torch.stack

torch.cat和torch.stack有略微的区别,torch.cat是连接,不会增加维度,而torch.stack是堆叠,会增加维度。

abc_cat = torch.cat([a,b,c],dim = 0)
abc_stack = torch.stack([a,b,c],axis = 0)
#torch中dim和axis参数名可以混用,=0时是按照行连接,=1列连接
torch.cat([a,b,c],axis = 1)

2.torch.split

torch.split是torch.cat的逆运算,可以指定分割份数平均分割,也可以通过指定每份的记录数量进行分割。

a,b,c = torch.split(abc_cat,split_size_or_sections = 2,dim = 0) #每份2个进行分割
p,q,r = torch.split(abc_cat,split_size_or_sections =[4,1,1],dim = 0) #每份分别为[4,1,1]

五,张量数学计算

1.取整

print(torch.round(x)) #保留整数部分,四舍五入
print(torch.floor(x)) #保留整数部分,向下归整
print(torch.ceil(x))  #保留整数部分,向上归整
print(torch.trunc(x)) #保留整数部分,向0归整

2.除法余数

print(torch.fmod(x,2)) #作除法取余数
print(torch.remainder(x,2)) #作除法取剩余的部分,结果恒正

3.幅值裁剪

x = torch.tensor([0.9,-0.8,100.0,-20.0,0.7])
y = torch.clamp(x,min=-1,max = 1)
z = torch.clamp(x,max = 1)

4.累乘,标准差,方差,中位数

print(torch.prod(a)) #累乘
print(torch.std(a))  #标准差
print(torch.var(a))  #方差
print(torch.median(a)) #中位数

5.张量排序

torch.sort和torch.topk可以对张量排序

print(torch.topk(a,2,dim = 1),"\n") #沿给定dim维度返回输入张量input中 k 个最大值。
print(torch.sort(a,dim = 1),"\n")

六,矩阵运算

1.矩阵乘法

print(a@b)  #等价于torch.matmul(a,b) 或 torch.mm(a,b)

2.矩阵转置

print(a.t())

3.矩阵逆,必须为浮点类型

print(torch.inverse(a))

4.矩阵求trace

print(torch.trace(a))

5.矩阵求范数

print(torch.norm(a))

6.矩阵行列式

print(torch.det(a))

7.矩阵特征值和特征向量

print(torch.eig(a,eigenvectors=True))

8.矩阵QR分解

矩阵QR分解, 将一个方阵分解为一个正交矩阵q和上三角矩阵r
QR分解实际上是对矩阵a实施Schmidt正交化得到q

q,r = torch.qr(a)
print(q@r)#还原a

9.矩阵svd分解

svd分解可以将任意一个矩阵分解为一个正交矩阵u,一个对角阵s和一个正交矩阵v.t()的乘积
svd常用于矩阵压缩和降维

u,s,v = torch.svd(a)
print(u@torch.diag(s)@v.t())    #还原a

七,广播机制

torch.broadcast_tensors

torch.broadcast_tensors可以将多个张量根据广播规则转换成相同的维度。

a_broad,b_broad = torch.broadcast_tensors(a,b)  #转换成相同的维度

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

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

相关文章

mongodb安装失败与解决方法(附安装教程)

安装mongodb遇到的一些坑 浪费了大量的时间 在此记录一下 主要是电脑系统win10企业版自带的防火墙 当然还有其他的一些坑 一般的问题在第6步骤都可以解决&#xff0c;本教程的安装步骤不够详细的话 请自行百度或谷歌 安装教程很多 我是基于node.js使用mongodb结合Robo 3T数…

【洛谷算法题】P1046-[NOIP2005 普及组] 陶陶摘苹果【入门2分支结构】Java题解

&#x1f468;‍&#x1f4bb;博客主页&#xff1a;花无缺 欢迎 点赞&#x1f44d; 收藏⭐ 留言&#x1f4dd; 加关注✅! 本文由 花无缺 原创 收录于专栏 【洛谷算法题】 文章目录 【洛谷算法题】P1046-[NOIP2005 普及组] 陶陶摘苹果【入门2分支结构】Java题解&#x1f30f;题目…

web性能优化(理论)

什么是性能优化&#xff1f; 就是让用户感觉你的网站加载速度很快。。。哈哈哈。 分析 让我们来分析一下从用户按下回车键到网站呈现出来经历了哪些和前端相关的过程。 缓存 首先看本地是否有缓存&#xff0c;如果有符合使用条件的缓存则不需要向服务器发送请求了。DNS查询建立…

python多项式回归_如何在Python中实现多项式回归模型

python多项式回归Let’s start with an example. We want to predict the Price of a home based on the Area and Age. The function below was used to generate Home Prices and we can pretend this is “real-world data” and our “job” is to create a model which wi…

充分利用UC berkeleys数据科学专业

By Kyra Wong and Kendall Kikkawa黄凯拉(Kyra Wong)和菊川健多 ( Kendall Kikkawa) 什么是“数据科学”&#xff1f; (What is ‘Data Science’?) Data collection, an important aspect of “data science”, is not a new idea. Before the tech boom, every industry al…

文本二叉树折半查询及其截取值

using System;using System.ComponentModel;using System.Data;using System.Drawing;using System.Text;using System.Windows.Forms;using System.Collections;using System.IO;namespace CS_ScanSample1{ /// <summary> /// Logic 的摘要说明。 /// </summary> …

nn.functional 和 nn.Module入门讲解

本文来自《20天吃透Pytorch》 一&#xff0c;nn.functional 和 nn.Module 前面我们介绍了Pytorch的张量的结构操作和数学运算中的一些常用API。 利用这些张量的API我们可以构建出神经网络相关的组件(如激活函数&#xff0c;模型层&#xff0c;损失函数)。 Pytorch和神经网络…

10.30PMP试题每日一题

SC>0&#xff0c;CPI<1&#xff0c;说明项目截止到当前&#xff1a;A、进度超前&#xff0c;成本超值B、进度落后&#xff0c;成本结余C、进度超前&#xff0c;成本结余D、无法判断 答案将于明天和新题一起揭晓&#xff01; 10.29试题答案&#xff1a;A转载于:https://bl…

02-web框架

1 while True:print(server is waiting...)conn, addr server.accept()data conn.recv(1024) print(data:, data)# 1.得到请求的url路径# ------------dict/obj d["path":"/login"]# d.get(”path“)# 按着http请求协议解析数据# 专注于web业…

ai驱动数据安全治理_AI驱动的Web数据收集解决方案的新起点

ai驱动数据安全治理Data gathering consists of many time-consuming and complex activities. These include proxy management, data parsing, infrastructure management, overcoming fingerprinting anti-measures, rendering JavaScript-heavy websites at scale, and muc…

从Text文本中读值插入到数据库中

/// <summary> /// 转换数据&#xff0c;从Text文本中导入到数据库中 /// </summary> private void ChangeTextToDb() { if(File.Exists("Storage Card/Zyk.txt")) { try { this.RecNum.Visibletrue; SqlCeCommand sqlCreateTable…

Dataset和DataLoader构建数据通道

重点在第二部分的构建数据通道和第三部分的加载数据集 Pytorch通常使用Dataset和DataLoader这两个工具类来构建数据管道。 Dataset定义了数据集的内容&#xff0c;它相当于一个类似列表的数据结构&#xff0c;具有确定的长度&#xff0c;能够用索引获取数据集中的元素。 而D…

铁拳nat映射_铁拳如何重塑我的数据可视化设计流程

铁拳nat映射It’s been a full year since I’ve become an independent data visualization designer. When I first started, projects that came to me didn’t relate to my interests or skills. Over the past eight months, it’s become very clear to me that when cl…

Django2 Web 实战03-文件上传

作者&#xff1a;Hubery 时间&#xff1a;2018.10.31 接上文&#xff1a;接上文&#xff1a;Django2 Web 实战02-用户注册登录退出 视频是一种可视化媒介&#xff0c;因此视频数据库至少应该存储图像。让用户上传文件是个很大的隐患&#xff0c;因此接下来会讨论这俩话题&#…

BZOJ.2738.矩阵乘法(整体二分 二维树状数组)

题目链接 BZOJ洛谷 整体二分。把求序列第K小的树状数组改成二维树状数组就行了。 初始答案区间有点大&#xff0c;离散化一下。 因为这题是一开始给点&#xff0c;之后询问&#xff0c;so可以先处理该区间值在l~mid的修改&#xff0c;再处理询问。即二分标准可以直接用点的标号…

从数据库里读值往TEXT文本里写

/// <summary> /// 把预定内容导入到Text文档 /// </summary> private void ChangeDbToText() { this.RecNum.Visibletrue; //建立文件&#xff0c;并打开 string oneLine ""; string filename "Storage Card/YD" DateTime.Now.…

DengAI —如何应对数据科学竞赛? (EDA)

了解机器学习 (Understanding ML) This article is based on my entry into DengAI competition on the DrivenData platform. I’ve managed to score within 0.2% (14/9069 as on 02 Jun 2020). Some of the ideas presented here are strictly designed for competitions li…

Pytorch模型层简单介绍

模型层layers 深度学习模型一般由各种模型层组合而成。 torch.nn中内置了非常丰富的各种模型层。它们都属于nn.Module的子类&#xff0c;具备参数管理功能。 例如&#xff1a; nn.Linear, nn.Flatten, nn.Dropout, nn.BatchNorm2d nn.Conv2d,nn.AvgPool2d,nn.Conv1d,nn.Co…

有效沟通的技能有哪些_如何有效地展示您的数据科学或软件工程技能

有效沟通的技能有哪些What is the most important thing to do after you got your skills to be a data scientist? It has to be to show off your skills. Otherwise, there is no use of your skills. If you want to get a job or freelance or start a start-up, you ha…

java.net.SocketException: Software caused connection abort: socket write erro

场景&#xff1a;接口测试 编辑器&#xff1a;eclipse 版本&#xff1a;Version: 2018-09 (4.9.0) testng版本&#xff1a;TestNG version 6.14.0 执行testng.xml时报错信息&#xff1a; 出现此报错原因之一&#xff1a;网上有人说是testng版本与eclipse版本不一致造成的&#…