基于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,布尔索引,速度


猜你喜欢
mysql时间戳转成常用可读时间格式的两种方法
2024-01-18 09:38:24
python正则表达式函数match()和search()的区别
2021-10-05 10:25:52
python异步存储数据详解
2023-08-14 09:05:44
Python获取数据库数据并保存在excel表格中的方法
2024-01-22 00:32:56

pycharm全局搜索的具体步骤
2023-11-04 17:31:07

教你使用TensorFlow2识别验证码
2022-06-26 19:24:38

golang 生成对应的数据表struct定义操作
2024-05-21 10:27:47
WEB页面工具语言XML产生背景
2008-05-29 10:52:00
python多个模块py文件的数据共享实例
2022-02-24 23:33:39
Python读取txt文件数据的方法(用于接口自动化参数化数据)
2023-12-28 03:21:52

JS定义函数的几种常用方法小结
2024-04-16 09:26:30
符合语言习惯的 Python 优雅编程技巧【推荐】
2022-07-07 10:43:40
Python pip安装第三方库的攻略分享
2023-02-15 07:53:26

MySQL自动为查询数据结果加序号
2024-01-20 03:17:51
Python3.9新特性详解
2023-03-26 21:56:16

python 七种邮件内容发送方法实例
2022-01-13 21:06:38
python 合并多个excel中同名的sheet
2023-06-06 08:34:27

通过不同的CSS设计字体大小来提高用户体验
2008-12-10 19:17:00
sql2005 存储过程分页示例代码
2024-01-13 03:09:06
php 字符串中是否包含指定字符串的多种方法
2023-06-11 20:21:38