基于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设计】。

相关文章

PyTorch里面的torch.nn.Parameter()详解

PyTorch里面的torch.nn.Parameter()详解

在看过很多博客的时候发现了一个用法self.v = torch.nn.Parameter(torch.FloatTensor(hidden_size)),首先可以把这个函数理解为类型转换...

解决python执行不输出系统命令弹框的问题

最近做一个的GUI,因为调用了os模块里的system方法,使用pyinstaller打包的时候选择不输出系统命令弹框,程序无法运行,要求要有系统命令框。在网上找到一个解决办法。使用su...

python实现图片变亮或者变暗的方法

python实现图片变亮或者变暗的方法

本文实例讲述了python实现图片变亮或者变暗的方法。分享给大家供大家参考。具体实现方法如下: import Image # open an image file (.jpg or....

解决pytorch GPU 计算过程中出现内存耗尽的问题

Pytorch GPU运算过程中会出现:“cuda runtime error(2): out of memory”这样的错误。通常,这种错误是由于在循环中使用全局变量当做累加器,且累加...

python 提取key 为中文的json 串方法

示例: # -*- coding:utf-8 -*- import json strtest = {"中故宫":"好地方","天涯":"北京"} print strtest ###...