基于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 continue继续循环用法总结

Python之 continue继续循环 在循环过程中,可以用break退出当前循环,还可以用continue跳过后续循环代码,继续下一次循环。 假设我们已经写好了利用for循环计算平均...

Python 中Django安装和使用教程详解

Python 中Django安装和使用教程详解

  一、安装     一般使用cmd 安装就可以   手动安装通过下载方式    django官方网站:https://www.djangoproject.com/    python官...

举例讲解Python中的身份运算符的使用方法

举例讲解Python中的身份运算符的使用方法

Python身份运算符 身份运算符用于比较两个对象的存储单元 以下实例演示了Python所有身份运算符的操作: #!/usr/bin/python a = 20 b = 20...

python比较两个列表是否相等的方法

本文实例讲述了python比较两个列表是否相等的方法。分享给大家供大家参考。具体如下: 这里演示了 == 和 is两种方法的区别: L1 = [1, ('a', 3)] # same...

Python之eval()函数危险性浅析

一般来说Python的eval()函数可以把字符串“123”变成数字类型的123,但是PP3E上说它很危险,还可以执行其他命令! 对此进行一些试验。果然,如果python写的cgi程序中...