基于torch.where和布尔索引的速度比较

yipeiwu_com6年前Python基础

我就废话不多说了,直接上代码吧!

import torch
import time
x = torch.Tensor([[1, 2, 3], [5, 5, 5], [7, 8, 9],[5,5,5],[1,2,3,],[1,2,4]])
'''
使用pytorch实现对于任意shape的torch.tensor,如果其中的element不等于5则为0,等于5则保留原数值
实现该功能的两种方式,并比较两种实现方式的速度
'''

# x[x!=5]=1
def t2(x):
  x[x!=5]=0
  return x
def t(x):
  zeros=torch.zeros(x.shape)
  # ones=torch.ones(x.shape)
  x=torch.where(x!=5,zeros,x)
  return x

t2_start=time.time()
t2=t2(x)
t2_end=time.time()

t_start=time.time()
t=t(x)
t_end=time.time()
print(t2,t)
print(torch.sum(t-t2))

print('using x[x!=5]=0 time:',t2_end-t2_start)
print('using torch.where time:',t_end-t_start)
'''
tensor([[0., 0., 0.],
    [5., 5., 5.],
    [0., 0., 0.],
    [5., 5., 5.],
    [0., 0., 0.],
    [0., 0., 0.]]) tensor([[0., 0., 0.],
    [5., 5., 5.],
    [0., 0., 0.],
    [5., 5., 5.],
    [0., 0., 0.],
    [0., 0., 0.]])
tensor(0.)
using x[x!=5]=0 time: 0.0010008811950683594
using torch.where time: 0.0

看来大神说的没错,果然是使用torch.where速度更快
 a[a!=5]=0 这种写法,速度比 torch.where 慢了超级多
'''

以上这篇基于torch.where和布尔索引的速度比较就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python中的Numpy入门教程

1、Numpy是什么 很简单,Numpy是Python的一个科学计算的库,提供了矩阵运算的功能,其一般与Scipy、matplotlib一起使用。其实,list已经提供了类似于矩阵的表示...

python安装以及IDE的配置教程

python安装以及IDE的配置教程

一、初识Python   Python官方网站:www.python.org   版本:python-3.4.3.amd64   somebody初次接触Python,没有使用Pytho...

python 抓包保存为pcap文件并解析的实例

首先是抓包,使用scapy模块, sniff()函数 在其中参数为本地文件路径时,操作为打开本地文件 若参数为BPF过滤规则和回调函数,则进行Sniff,回调函数用于对Sniff到的数据...

python批量获取html内body内容的实例

现在有一批完整的关于介绍城市美食、景点等的html页面,需要将里面body的内容提取出来 方法:利用python插件beautifulSoup获取htmlbody标签的内容,并批量处理。...

在Django的URLconf中使用多个视图前缀的方法

在实践中,如果你使用字符串技术,特别是当你的 URLconf 中没有一个公共前缀时,你最终可能混合视图。 然而,你仍然可以利用视图前缀的简便方式来减少重复。 只要增加多个 pattern...