我能做些什么来加速numpy中的掩码数组吗?我有一个非常低效的函数,我将其重写为使用掩码数组(我可以只掩码行,而不是像我所做的那样复制和删除行)。然而,我震惊地发现被屏蔽的函数慢了10倍,因为被屏蔽的数组要慢得多。
以下面的代码为例(对我来说,屏蔽的速度要慢6倍以上):
import timeit
import numpy as np
import numpy.ma as ma
def test(row):
return row[0] + row[1]
a = np.arange(1000).reshape(500, 2)
t = timeit.Timer('np.apply_along_axis(test, 1, a)','from __main__ import test, a, np')
print round(t.timeit(100), 6)
b = ma.array(a)
t = timeit.Timer('ma.apply_along_axis(test, 1, b)','from __main__ import test, b, ma')
print round(t.timeit(100), 6)
发布于 2011-07-05 22:14:50
我不知道为什么被屏蔽的数组函数移动得如此之慢,但是因为听起来像是在使用掩码来选择行(而不是单个值),所以可以从被屏蔽的行创建一个规则的数组,并改用np函数:
b.mask = np.zeros(500)
b.mask[498] = True
t = timeit.Timer('c=b.view(np.ndarray)[~b.mask[:,0]]; np.apply_along_axis(test, 1, c)','from __main__ import test, b, ma, np')
print round(t.timeit(100), 6)
更好的是,根本不要使用掩码数组;只需将数据和一维掩码数组作为单独的变量进行维护:
a = np.arange(1000).reshape(500, 2)
mask = np.ones(a.shape[0], dtype=bool)
mask[498] = False
out = np.apply_along_axis(test, 1, a[mask])
https://stackoverflow.com/questions/5760668
复制相似问题