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

yipeiwu_com5年前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实现flappy bird小游戏

本文实例为大家分享了python实现flappy bird游戏的具体代码,供大家参考,具体内容如下 flappygamemain.py # -*- coding: utf-8 -*-...

pyinstaller参数介绍以及总结详解

pyinstaller参数介绍以及总结详解

最近利用tkinter+python+pyinstaller实现了小工具的项目,在此记录下pyinstaller相关参数以及爬过的坑。 一、pyinstaller相关参数...

Python 普通最小二乘法(OLS)进行多项式拟合的方法

Python 普通最小二乘法(OLS)进行多项式拟合的方法

多元函数拟合。如 电视机和收音机价格多销售额的影响,此时自变量有两个。 python 解法: import numpy as np import pandas as pd #impo...

Python 读写文件和file对象的方法(推荐)

1.open 使用open打开文件后一定要记得调用文件对象的close()方法。比如可以用try/finally语句来确保最后能关闭文件。 file_object = open('the...

关于pytorch中全连接神经网络搭建两种模式详解

pytorch搭建神经网络是很简单明了的,这里介绍两种自己常用的搭建模式: import torch import torch.nn as nn first: class NN...