Pytorch 的 Tensor 常用函数与操作

Pytorch tensor处理函数/技巧汇总 Cook Blog(持续更新) 二维tensor一次多行/多列 提取行列交叉的技巧(可扩展到三维) import torch a = torch.tensor ( [[1,2,3,4], [2,3,1,5], [5,1,7,2]]) print(a[[1,0]]) #一次多行提取 print(a[...,[1,0]]) #一次多列提取 # a[...,[1,0]]等价于a[:,0:2] print(a[[1,0],[1,2]]) #获得 阅读详情

Tensor的算术运算

import torch
a = torch.Tensor([1, 2])
b = torch.Tensor([3, 4])

### 加法运算
c = a + b
c = torch.add(a, b)
c = a.add(b)
print(a)
c = a.add_(b) 
print(a)

### 减法运算
c = a - b
c = torch.sub(a, b)
c = a.sub(b)
print(c)
print(a)
c = a.sub_(b) 
print(c)
print(a)

### 乘法运算
c = a * b
c = torch.mul(a, b)
c = a.mul(b)
print(c)
c = a.mul_(b) 
print(c)

### 除法运算
c = a / b
c = torch.div(a, b)
c = a.div(b)
print(c)
c = a.div_(b) 
print(c)

### 矩阵运算 a*b ->(m,n)*(n,k)
a = torch.ones(2, 1)
b = torch.ones(1, 3)
print(a,b)
### a*b  

c = torch.mm(a, b)
c = torch.matmul(a, b)
print(c)
c = a @ b
c = a.matmul(b)
c = a.mm(b)
print(c)

### 幂运算
c = torch.pow(a, 2)
c = a.pow(2)
c = a**2
c = a.pow_(2)
print(c)

### e**n exp运算
c = torch.exp(a)
c = a.exp_()
print(c)

### 开方运算
c = a.sqrt()
c = a.sqrt_()
print(c)

### 对数运算
c = torch.log2(a)
c = torch.log10(a)
c = torch.log(a)
c = torch.log_(a)
print(c)

Tensor序列的创建

# 初始化一个全是1的tensor
a = torch.ones(2,5)

# 初始化一个全零的tensor
a = torch.zeros(3,3)

# 初始化一个对角线为1的tensor
a = torch.eye(3,3)

#定义一个与a形状相同的全零tensor
b = torch.zeros_like(a)
#定义一个与a形状相同的全为1的tensor
b = torch.ones_like(a)

#pytorch的tensor操作类似于numpy,可以进行类比,如下
import numpy as np
b = np.array([
    [1,2,3],[2,3,4]])
b = np.ones((2,3))
c = np.zeros_like(b)
# Tensor与numpy非常相似,可以理解为在numpy的基础上套了一层tensor
# 随机tensor
a = torch.rand(2,3) #指定shape,返回[0,1]之间的随机值
 
# 指定特定分布的tensor,比如正态分布
a  = torch.normal(mean=0.0, std=torch.rand(5))   #5代表形状

#均匀分布
a = torch.Tensor(2,3).uniform_(-1,1) #定义[-1,1]之间进行均匀采样,(2,3)是shape

# 标准正态分布
a = torch.randn(10)

# 生成序列
a = torch.arange(0, 10, 1) #生成从[0,10),步长是1的序列

# 等间隔切分
a = torch.linspace(2, 10, 5) #生成从[2,10]之间,等间隔的5个序列

# 打乱序列
a = torch.randperm(10) #生成一个从[0,m)的序列并进行打乱,这里m=10


Tensor的索引与数据筛选:torch.where()、torch.index_select()、torch.masked_select()、torch.gt()、torch.nonzero()、torch.take()

###torch.where
#torch.where(condition, a, b):按条件从a和b中选出满足条件的元素组成新的tensor

a = torch.rand(4, 4)
b = torch.rand(4, 4)
print(a)
print(b)
out = torch.where(a> 0.5, a, b)
print(out)

###torch.index_select
# torch.index_select(input, dim, index, out=None):按照指定索引输出tensor

a = torch.rand(4, 4)
print(a)
out = torch.index_select(a, dim = 0, index=torch.tensor([0, 3, 2]))
print(out)

### torch.masked_select
# torch.masked_select(input, mask, out=None):将满足mask(掩码、遮罩等等,随便翻译)的指示,将满足条件的点选出来输出tensor,输出为向量
# torch.gt(a,b)函数比较a中元素大于(这里是严格大于)b中对应元素,大于则为1,不大于则为0,这里a为Tensor,b可以为与a的size相同的Tensor或常数。

a = torch.linspace(1, 16, 16)
# print(a)

a = a.view(4, 4)
print(a)

mask = torch.gt(a, 8)
print(mask)

out = torch.masked_select(a, mask)
print(out)

### torch.take
#torch.take(input, indices):将输入看成1D-tensor,按照索引得到输出tensor

a = torch.linspace(1, 16, 16).view(4, 4)
b = torch.take(a, index=torch.tensor([0, 15, 13, 10]))
print(a)
print(b)

### torch.nonzero
#torch.nonzero(input, out=None):输出非0元素的坐标
a = torch.tensor([
    [0, 1, 2, 0], [2, 3, 0, 1]
])
print(a)

out = torch.nonzero(a)
print(out)

Tensor的组合与拼接

# torch.cat(seq, dim=0, out=None):按照已经存在的维度进行拼接
# torch.stack(seq, dim=0, out=None):按照新的维度进行拼接

# torch.cat
a = torch.zeros((2, 4))
b = torch.ones((2, 4))
print(a)
print(b)

out = torch.cat((a, b), dim=0) 
print(out)
print(out.shape)

#torch.stack
a = torch.linspace(1, 9, 9).view(3, 3)
b = torch.linspace(10, 18, 9).view(3, 3)
print(a)
print(b)

out = torch.stack((a, b), dim=2)
print(out)
# print(out.shape)
print(out[:, :, 0])
print(out[:, :, 1])

分割、压缩、变形—torch.chunk()、torch.split()、torch.t()、torch.transpose() 、torch.squeeze()、torch.unsqueeze()、torch.unbind() 、torch.flip()、torch.full()

# torch.chunk() # 按照某个维度平均分块(最后一个可能小于平均值)
a = torch.rand((5,4))
print(a)

out = torch.chunk(a,2,dim = 0)  # 按照某个维度平均分块(最后一个可能小于平均值)
print(out)

# torch.split()  切片,每片包含几行或者几列
a = torch.linspace(1,20,20).view(4,5)
print(a)
print("===========================")
out = torch.split(a,2,dim = 1)
print(out)

out1 = torch.split(a,[1,2,2],dim = 0) # 切成1行、2行、3行 sum[1,2,2]等于a的行数
print(out1)

#torch.reshape()变形
a = torch.rand((5,4))
out = torch.reshape(a,(4,5))  # 类似于view
print(out)

# torch.t()  转置
print(torch.t(a))

# torch.transpose() 交换维度
print(out)
out1 = torch.transpose(out,0,1) 
print(out1)

# torch.squeeze() 删除维度为1的张量
print(a)
print(a.shape)
out = torch.squeeze(a)
print(out)
print(out.shape)


# torch.unsqueeze() 扩充维度
print(a)
print(a.shape)
print('---------------------')
out = torch.unsqueeze(a,-1) # -1是用来扩充最后一个维度
out = torch.unsqueeze(a,1) # 1是用来扩充第一个维度
print(out)
print(out.shape)

# torch.unbind() 去除某一个维度
print(a)
print(a.shape)
print('---------------------')
out = torch.unbind(a,dim = 1) # 这个意思是在第二个维度上面进行操作,生成两个【1,3】的张量
                             # 类似于split
print(out)
print(out[0].shape)

# torch.flip():翻转操作
print(a)
print(a.shape)
print('---------------------')
out = torch.flip(a,dims = [1])
print(out)

# torch.full():    定义一个tensor,并填充指定的数值
out = torch.full((6,6),6)
print(out)

练习1:创建 a、b 两个张量,调整两个张量的 shape,分别采用 tensor.mul()、
tensor.dot()、tensor.matmul()进行计算,比较三者的区别。

import torch
a = torch.linspace(1,16,16).view(4,4)
b = torch.rand(4,4)
out = torch.mul(a,b)   # torch.mul(a,b)这里面的a,b必须维度相同 
print(out)

a = torch.Tensor([1,2])
b = torch.Tensor([5,6])
print(a.shape,b.shape)
out = torch.dot(a,b)   # torch.dot(a,b)只能对1维的tensor进行点成运算
print(out)

a = torch.linspace(1,16,16).view(4,4)
b = torch.rand(4,5)
print(a.shape,b.shape)
out = torch.matmul(a,b)   # torch.matmul()满足(m,n)*(n,k)
print(out)

练习2:创建一个张量 c 服从标准正态分布,将 c 中的负数替换成该数的绝对值。

c1 = torch.randn(10)
print(c1)

c3 = torch.where(c1>0,c1,abs(c1))
print(c3)

练习3:创建 d、e 两个张量,tensor.cat()和 tensor.stack()两种方式拼接两个张量,再以任意方式降维

d = torch.rand(3,3)
e = torch.linspace(1,9,9).view(3,3)
out = torch.cat((d,e),dim = 1)# torch.cat(seq, dim=0, out=None):按照已经存在的维度进行拼接
print(out,out.shape)
out_un = torch.unbind(out,dim = 1)
print(out_un)
#也可以通过reshape来降低维度
f2 = torch.reshape(out,[2,9])
print(f2.shape)

out1 = torch.stack((d,e),dim = 1)
out1_un = torch.squeeze(out1)
print(out1)
print(out1_un)

练习4:zeros 张量,shape=(2,4),将张量中的 index=[0,2]和 index=[1,3]的元素填 充为 1

z = torch.zeros(2, 4).scatter_(1, torch.LongTensor([[2], [3]]), 1)
print(z)

torch.LongTensor是64位整型

补充:scatter_()函数

scatter(dim, index, src)
dim:沿着哪个维度进行索引
index: 用来scatter的元素索引
src: 用来scatter的源元素,可以使一个标量也可以是一个张量

Pytorch常用函数手册 第六章torch.nn.init .............................................................................................................. 144。第十四章torch.utils.model_zoo .......................................................................................... 168。 阅读详情

相关推荐

pytorch tensor flip

因为使用中用到数据 需要flip,在python代码中使用numpy的flip很方便,但是c++中使用flip就不那么方便了。 本来图像数据,想要使用vtk去做数据处理,后来发现使用pytoch的torch处理更合适一些。 torch.flip(input,dim):第一个参数是输入,第二个参数是输入的第几维度,按照维度对输入进行翻转 # -*- coding : UTF-8 -*- # @file : torch_t1.py # @Time : 2021/8/29 22:37 # @Author

juluwangriyue的博客 1693

PyTorch:Tensor的常用基础函数

PyTorch中一些常见函数的用法和示例

baidu_38797690的博客 4117

解决tensor.sub_(mean).div_(std)RuntimeError: output with shape [1, 28, 28] doesn‘t match the broadcas

项目场景: MNIST数据集 GANs生成 问题描述: 完整报错: Traceback (most recent call last): File "pytorch_MNIST_cGAN.py", line 229, in <module> for x_, y_ in train_loader: File "/root/anaconda3/envs/dpm-pc-gen/lib/python3.7/site-packages/torch/utils/data/datal

沉迷单车的追风少年 1982

【Pytorch基础教程39】torch常用tensor处理函数

一、tensor的创建 二、tensor的加减乘除 三、torch.argmax()函数 四、gathter函数 小栗子1 小栗子2:如果每行需要索引多个元素: 四、改变维度、拼接、堆叠等操作# 一、tensor的创建 - `torch.tensor`会复制data,不想复制可以使用`torch.Tensor.detach()`。 - 如果是获得numpy数组数据,可以使用`torch.from_numpy()`,共享内存 ```python # 1. tensor torch.tensor(data, d

发现问题,并解决问题,批判性思维 6649

手把手教你离线部署bert-base-uncased模型(附完整文件清单)

本文提供了一份详尽的bert-base-uncased模型离线部署指南。针对严格内网或无网络环境,文章不仅列出了包括config.json、pytorch_model.bin在内的完整必需文件清单,还详细解释了每个文件的作用,并给出了使用snapshot_download工具或手动下载的两种文件获取方法。重点阐述了如何正确设置本地路径、编写健壮的加载代码,并通过多层次验证确保模型在离线环境下成功运行,有效解决了部署过程中常见的文件缺失和路径错误问题。

weixin_29034963的博客 324

机场数据治理系列介绍(1):机场行业数据中台中的数据管理顶层设计方案

民航机场行业的数据中台中,有关数据管理顶层设计方案需要结合机场行业的业务特点和技术需求进行具体的设计,今日我们简要考量设计提供一个参考方案:

机场信息系统研究员的专栏 1615

PyTorch学习之路(五)Tensor操作及其常用函数

目录创建tensor新建tensor的方法表格t.tensor和t.Tensor的区别基本操作tensor 大小: t.size(), t.shape()转为list: t.tolist()tensor中元素总个数: t.numel()调整形状 t.view(), t.resize()增减维度 t.squeeze(), t.unsqueeze()?索引操作数学运算in place操作(是否修改自...

一听音频技术 5185

Android流畅度优化实战:从掉帧定位到布局与渲染调优

在移动应用开发中,性能优化是决定用户体验与留存率的关键环节,其中Android流畅度优化更是核心命题。用户感知的“卡顿”往往并非持续低帧率,而是由于掉帧率波动引发的偶发不流畅。本文从性能优化理论出发,系统讲解如何使用Systrace、CPU Profiler等工具定位掉帧瓶颈,深入分析布局层级过深、过度绘制、对象分配与GC压力等常见诱因。同时结合冷启动耗时、列表滚动掉帧、Bitmap加载等真实工程案例,阐述从应用层到系统层的分级优化策略,并给出低端机适配、异步化改造及线上监控体系搭建的实践方案。内容覆盖布局

weixin_29185493的博客 206

Pytorch List Tensor转Tensor,reshape拼接等操作

Pytorch List Tensor转Tensor,reshape拼接等操作 持续更新一些常用的Tensor操作,比如List,Numpy,Tensor之间的转换,Tensor的拼接,维度的变换等操作。其它Tensor操作如 einsum等见:待更新。 List Tensor转Tensor

bagba的知识分享库 2万+

SEG-Y 数据介绍及读写

无

1万+

实战指南 | 快速修复Adobe Acrobat 2020安装过程中的常见注册表错误

本文提供了Adobe Acrobat 2020安装过程中遇到“无法打开键”注册表错误的详细修复指南。通过安全编辑注册表,精准定位并删除残留键值,可快速解决此常见安装报错,确保软件顺利安装。同时,文章也介绍了其他安装问题的应对策略与预防措施。

weixin_29200485的博客 568

《深度学习框架PyTorch入门与实践》——学习笔记

表3-1: 常见新建tensor的方法 函数 功能 Tensor(*sizes) 基础构造函数 tensor(data,) 类似np.array的构造函数 ones(*sizes) 全1Tensor zeros(*sizes) 全0Tensor eye(*sizes) 对角线为1,其他为0 arange(s,e,step 从s到e,步长为step linspace(s,e...

Escape_x1n的博客 1159

保姆级教程:用OpenCV和MediaPipe在Python里实现实时手势识别(附完整代码)

本文提供了一份详细的Python教程,教你如何使用OpenCV和MediaPipe实现实时手势识别系统。从环境配置、手部关键点检测到手势分类算法,逐步讲解如何构建高精度手势识别应用,适用于智能家居控制、PPT操作等场景。教程包含完整代码示例和性能优化技巧,特别适合计算机视觉初学者和开发者实践。

weixin_28677005的博客 338

Pytorch框架教程

深度学习:Pytorch教程

u013250861的博客 589

爆肝5万字❤️Open3D 点云数据处理基础(Python版)

本文为Open3D 点云数据处理基础教程(Python版),小白也能轻松上手!还等什么呢,学起来!

孙悟空 13万+

Win7没有usb驱动怎么办?Win7没有usb驱动的解决方法

之后发现USB驱动不能够使用,那么碰到这种问题应该怎么办呢?下面就和小编一起来看看有什么解决方法吧。1、我们先使用驱动管理软件进行扫描安装驱动,如果安装后,还不行的话,我们就要进入到控制面板。我们经常会因为各种原因来更新电脑的系统,不过有一些小伙伴在重装完。4、点击usb选项后,找到显示感叹号和问号的usb驱动。2、在控制面板中,点击硬件声音,选择设备管理器。3、进入到设备管理器的页面,找到USB控制选项。6、如果计算机已经联网,我们可以在线更新驱动。5、然后鼠标右键点击更新驱动。

2401_88800025的博客 970

基于PyTorch学AI——一切从Tensor开始

介绍关于PyTorch中Tensor的一些常用函数。

道至简 1860

文档:亲测可用解决vnc灰屏,黑屏,鼠标大黑叉情况

主要解决vnc-viewer灰屏,黑屏,鼠标大黑叉等现象,详细见文档。

pytorch基础: Tensor数据类型与基础函数

pytorch基础: Tensor数据类型与基础函数 1. Tensor的数据类型 在PyTorch中,主要有10种类型的tensor,其中重点使用的为以下八种(还有BoolTensor和BFloat16Tensor): Data type dtype dtype 32-bit floating point torch.float32 or torch.float torch.(cuda).FloatTensor 64-bit floating point torch.float64 o

a123456789032的博客 3517

jre9下载 jdk9

(Java SE Runtime Environment 9.0) 9.0u175 官方最新版 【x86|x64】

WINCC7.3破解文件

WINCC7.3硬件够破解文件,有需要的下载!WINCC7.3硬件够破解文件,有需要的下载!

pytorch nonzero_Pytorch深度指南-torch与Tensor常用操作方法

pytorch深度指南-torch与Tensor常用操作方法import torch.Tensor会继承某些torch的某些数学运算,例如sort, min/max....不需要调用相应的torch.funciton进行处理,下文中如果是torch/Tensor即表示该函数可以直接对self的tensor使用,也可以使用torch给的相应函数接口torch/Tensor.reshape(input...

weixin_39813200的博客 320

pytorch tensor_深度学习框架pytorch(五)

一、tensor与numpy之间的相互转换二、CPU tensor与GPU tensor之间的转换三、Tensor的操作四、Variable五、pytorch实现简单的线性回归六、逻辑回归七、使用Optimizer优化八、更多的loss一、tensor与numpy之间的相互转换# pytorch与numpy之间的转换 二、CPU tensor与GPU tensor之间的转换x 三、Tensor的操...

weixin_39604983的博客 70

[Pytorch]Pytorch中tensor常用语法

[Pytorch]Pytorch中tensor常用语法 原文地址:https://zhuanlan.zhihu.com/p/31494491 上次我总结了在PyTorch中建立随机数Tensor的多种方法的区别。这次我把常用的Tensor的数学运算总结到这里,以防自己在使用PyTorch做实验时,忘记这些方法应该传什么参数。总结的方法包括:Tens...

急流勇进 4126

pytorch基础数据类型--tensor

文章目录一. 创建tensor二. tensor属性1. 判断属性is_cuda 是否存储在GPU上is_quantizedis_meta2. 基本属性dtype 数据类型device 计算引擎shape 形状3. 操作T 转置real 返回复数实部的新tensorimag 返回复数虚部的新tensor4. 其它grad 梯度ndim三. tensor方法1. 构造新tensornew_tensor 创建新tensornew_full 创建指定形状指定值的tensornew_empty 创建指定形状的空te

p1049990866的博客 1200

Pytorch最最适合研究生的入门教程,Q1 Tensor的初认识

①view方法返回的是一个新的视图(view)对象,它共享原始Tensor的内存,这意味着任何对视图所做的修改都会反映到原始Tensor上。2.如果两个张量在某个维度上的大小不一致,但其中一个张量在该维度上的大小是1,则可以在该维度上进行广播。1.如果两个张量的维度数量不同,则将较小的那个张量的形状前面补1,直到两个张量的维度数量相同。使用rand创建一个3x3的张量,再创建一个6x6的张量,尝试将它们相加。张量的切片操作类似于数组的切片操作,与numpy的切片操作一致。

qq_39935495的博客 1080

Pytorch 笔记——tensor

tensor和numpy中的ndarray很相似,唯一的不同是tensor可以应用在GPU上,来加速计算。 1 创建tensor randn 创建一个标准正态分布内随机的矩阵 zeros 全零矩阵 tensor 创建一个内容为参数的tensor linspace 同nump.

qq_40206371的博客 472

[实验笔记] pytorch tensor和numpy的一些操作函数

1. tensor.mean(),取算术平均值。指定参数可以计算每一行或者 每一列的算术平均数 2. tensor.unsqueeze(i): 在某个维度(从0开始)增加一个维度。squeeze(i)去掉某一维度 3.numpy转tensor时的Double Tensor 和Float Tensor 不一致:对numpy用astype(np.float32)可以解决 RuntimeErro...

小星星的小房子 412

Pytorch 创建Tensor

Pytorch 创建Tensor tensor创建 import numpy as np import torch a = np.array([2, 3.3]) b = torch.from_numpy(a) print("b: \t", b) c = np.ones([2,3]) d = torch.from_numpy(c) print("d: \t", d) b: tensor([2.0000, 3.3000], dtype=torch.float64) d: tensor([[1

weixin_44533869的博客 352
上一篇: 几种激活函数的详解及代码实现:sigmoid()、softmax()、tanh()、relu()、leaky_relu()
下一篇: python中的max()与min()的用法介绍
Amanda_ABAP_Python
博客等级 码龄6年 45粉丝 101原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
⌂ 换网址