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

作者:WYXHAHAHA123 时间:2021-10-07 16:20:54 

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


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 慢了超级多
'''

来源:https://blog.csdn.net/WYXHAHAHA123/article/details/88206801

标签:torch.where,布尔索引,速度
0
投稿

猜你喜欢

  • IE8 CSS之生成内容

    2008-09-09 22:14:00
  • Python Flask框架开发之运用SocketIO实现WebSSH方法详解

    2021-11-06 01:03:33
  • python利用socketserver实现并发套接字功能

    2021-01-28 16:36:45
  • Go语言实现的树形结构数据比较算法实例

    2023-08-06 18:18:39
  • 站长如何活用"nofollow"标签

    2008-05-13 12:40:00
  • 给大家整理了19个pythonic的编程习惯(小结)

    2024-01-02 08:00:05
  • TensorFlow实现随机训练和批量训练的方法

    2022-06-07 07:45:29
  • python控制台打印log输出重复的解决方法

    2021-02-23 04:05:17
  • python3.x zip用法小结

    2023-08-13 05:25:05
  • python网络编程之读取网站根目录实例

    2021-03-07 03:04:35
  • 如何通过命令行进入python

    2022-10-28 22:12:56
  • 关于Python中的main方法教程

    2021-12-30 08:31:37
  • IE下,事件触发那点破烂事儿

    2009-04-27 12:31:00
  • 详解laravel安装使用Passport(Api认证)

    2023-11-19 02:08:54
  • Python 序列的方法总结

    2021-12-12 11:14:23
  • python中pdb模块实例用法

    2023-10-14 19:04:48
  • asp如何向前端显示用户请求的信息?

    2010-06-09 18:52:00
  • 讲解无法打开用户默认数据库的解决方法

    2008-12-05 15:55:00
  • Python xlwings插入Excel图片的实现方法

    2023-11-23 05:53:18
  • Django 解决开发自定义抛出异常的问题

    2023-03-05 12:43:55
  • asp之家 网络编程 m.aspxhome.com