1

numpy.nanpercentile非常慢。所以,我想使用cupy.nanpercentile; 但尚未cupy.nanpercentile实施。有人有解决方案吗?

4

3 回答 3

2

我的数据集也遇到了 np.nanpercentile 非常慢的问题。我找到了一个可以让你使用标准 np.percentile 的 wokraround。它也可以应用于许多其他库。

这个应该可以解决你的问题。而且它的工作速度也比 np.nanpercentile 快很多:

arr = np.array([[np.nan,2,3,1,2,3],
                [np.nan,np.nan,1,3,2,1],
                [4,5,6,7,np.nan,9]])

mask = (arr >= np.nanmin(arr)).astype(int)

count = mask.sum(axis=1)
groups = np.unique(count)
groups = groups[groups > 0]

p90 = np.zeros((arr.shape[0]))
for g in range(len(groups)):
    pos = np.where (count == groups[g])
    values = arr[pos]
    values = np.nan_to_num (values, nan=(np.nanmin(arr)-1))
    values = np.sort (values, axis=1)
    values = values[:,-groups[g]:]
    p90[pos] = np.percentile (values, 90, axis=1)

因此,它不是使用 nans 获取百分位,而是按有效数据量对行进行排序,并采用这些行的百分位分隔。然后将所有内容重新组合在一起。这也适用于 3D 数组,只需添加 y_pos 和 x_pos 而不是 pos。并注意您正在计算的轴。

于 2020-12-21T13:27:56.813 回答
0
def testset_gen(num):
    init=[]
    for i in range (num):
        a=random.randint(65,122) # Dummy name
        b=random.randint(1,100) # Dummy value: 11~100 and 10% of nan
        if b<11:
            b=np.nan # 10% = nan
        init.append([a,b])
    return np.array(init)

np_testset=testset_gen(30000000) # 468,751KB

def f1_np (arr, num):
    return np.percentile (arr[:,1], num)
# 55.0, 0.523902416229248 sec

打印 (f1_np(np_testset[:,1], 50))

def cupy_nanpercentile (arr, num):
    return len(cp.where(arr > num)[0]) / (len(arr) - cp.sum(cp.isnan(arr))) * 100
    # 55.548758317136446, 0.3640251159667969 sec
    # 43% faster
    # If You need same result, use int(). But You lose saved time.

打印 (cupy_nanpercentile(cp_testset[:,1], 50))

我无法想象测试结果需要几天时间。用我的电脑,似乎有 1 万亿行数据或更多。因此,由于缺乏资源,我无法重现相同的问题。

于 2020-09-12T10:56:34.357 回答
0

这是 numba 的实现。编译后它比 numpy 版本快 7 倍以上。

现在它被设置为沿第一个轴取百分位数,但是它可以很容易地改变。

@numba.jit(nopython=True, cache=True)
def nan_percentile_axis0(arr, percentiles):
    """Faster implementation of np.nanpercentile
    
    This implementation always takes the percentile along axis 0.
    Uses numba to speed up the calculation by more than 7x.

    Function is equivalent to np.nanpercentile(arr, <percentiles>, axis=0)

    Params:
        arr (np.array): Array to calculate percentiles for
        percentiles (np.array): 1D array of percentiles to calculate

    Returns:
        (np.array) Array with first dimension corresponding to
            values as passed in percentiles

    """
    shape = arr.shape
    arr = arr.reshape((arr.shape[0], -1))
    out = np.empty((len(percentiles), arr.shape[1]))
    for i in range(arr.shape[1]):
        out[:,i] = np.nanpercentile(arr[:,i], percentiles)
    shape = (out.shape[0], *shape[1:])
    return out.reshape(shape)
于 2021-09-01T13:28:45.717 回答