【问题标题】:Is there a CuPy version supporting (axis) option in cupy.unique() function? Any workaround?Cupy.unique() 函数中是否有 CuPy 版本支持(轴)选项?任何解决方法?
【发布时间】:2019-11-01 15:45:49
【问题描述】:

我正在寻找支持轴选项的 numpy.unique() 的 GPU CuPy 对应物。

我有一个 Cupy 二维数组,我需要删除它的重复行。不幸的是, cupy.unique() 函数将数组展平并返回具有唯一值的一维数组。我正在寻找像 numpy.unique(arr, axis=0) 这样的函数来解决这个问题,但 CuPy 还不支持 (axis) 选项

x = cp.array([[1,2,3,4], [4,5,6,7], [1,2,3,4], [10,11,12,13]])
y = cp.unique(x)
y_r = np.unique(cp.asnumpy(x), axis=0)

print('The 2D array:\n', x)
print('Required:\n', y_r, 'But using CuPy')
print('The flattened unique array:\n', y)

print('Error producing line:', cp.unique(x, axis=0))

I expect a 2D array with unique rows but I get a 1D array with unique numbers instead. Any ideas about how to implement this with CuPy or numba?

【问题讨论】:

    标签: python gpu unique axis cupy


    【解决方案1】:

    截至 CuPy 版本 8.0.0b2,函数 cupy.lexsort 已正确实现。此函数可用作带有轴参数的cupy.unique 的解决方法(尽管可能不是最有效的)。

    假设数组是 2D 的,并且您想沿轴 0 查找唯一元素(否则适当的转置/交换):

        ###################################
        # replacement for numpy.unique with option axis=0
        ###################################
    
        def cupy_unique_axis0(array):
            if len(array.shape) != 2:
                raise ValueError("Input array must be 2D.")
            sortarr     = array[cupy.lexsort(array.T[::-1])]
            mask        = cupy.empty(array.shape[0], dtype=cupy.bool_)
            mask[0]     = True
            mask[1:]    = cupy.any(sortarr[1:] != sortarr[:-1], axis=1)
            return sortarr[mask]
    

    如果您也想实现 return_stuff 参数,请检查the original cupy.unique source code(这是基于)。我自己不需要这些。

    【讨论】:

    • 非常感谢您的回复。我不是在寻找沿特定轴的唯一(元素),而是在寻找唯一的行或列,例如: if x = [[ 0 1 2 3 4] [ 0 1 2 3 4] [10 11 12 13 14] [15 16 17 18 19] [20 21 22 23 24]] 它们必须返回: [[ 0 1 2 3 4] [10 11 12 13 14] [15 16 17 18 19] [20 21 22 23 24 ]]
    • 这就是这个函数的作用,我的措辞可能令人困惑。您可以使用您的数组对其进行测试:x = cupy.arange(25).reshape((5,5)); x[1] = x[0]; print(x); print(cupy_unique_axis0(x)).
    • 这真的很有帮助。对此,我真的非常感激。谢谢!
    猜你喜欢
    • 2023-03-31
    • 1970-01-01
    • 2016-07-15
    • 1970-01-01
    • 1970-01-01
    • 2011-03-05
    • 2018-07-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多