索引搜索:性能的交易准确性

问题描述 投票:2回答:1

我有一个简单的两行代码块,它根据另一个数组中最接近的元素将值添加到数组中。由于它被埋在MCMC的深处,因此它执行了数百万次,因此我需要使其尽可能地高效。

下面的代码有效,这很容易解释。基本上,数组arr2[0](用于在arr0中查找最接近的元素的数组)包含(10., 25.)范围内的值。目前,我利用arr0已被排序的事实,在arr2[0中为np.searchsorted()中的每个元素寻找arr0中的absolute最近元素。

我愿意为了提高性能而牺牲一些准确性

。也就是说,我可以使用一个索引,该索引指向容忍度为+-0.2的“ close”元素,而不是绝对最接近元素(这是我现在要做的)

可以这样做吗?更重要的是:可以做到这一点,并提高性能

代码吗?
import numpy as np

# Random initial data with the actual shapes used by my code.
Nmax = 1000000
arr0 = np.linspace(5., 30., Nmax)
D = np.random.randint(2, 4)
arr1 = np.random.uniform(-3., 3., (D, Nmax))
arr2 = np.random.uniform(10., 25., (10, 1500))

# Can these two lines be made faster?
# Indexes of elements in 'arr0' closest to the elements in 'arr2[0]'
closest_idxs = np.searchsorted(arr0, arr2[0])
# Add elements from 'arr1' to the first dimensions of 'arr2', according
# to the indexes found above.
arr_final = arr2[:arr1.shape[0]] + arr1[:, closest_idxs]

我有一个简单的两行代码块,它根据另一个数组中最接近的元素将值添加到数组中。由于它被埋在MCMC中的深处,因此它执行了数百万次,...

python performance numpy search
1个回答
0
投票

对于具有给定公差值的近似匹配,我们可以使用它来将第一个arg减小为searchsorted并因此进行优化,就像这样-

© www.soinside.com 2019 - 2024. All rights reserved.