我在寻找一个支持轴选项的numpy.unique()的GPU CuPy版本。
我有一个Cupy 2D数组,我需要删除它的重复行。不幸的是,Cupy.unique()函数将数组扁平化,并返回具有唯一值的1D数组。我正在寻找一个类似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?
截至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]
检查 原来 cupy.unique
源码 (这是基于这个的),如果你也想实现return_stuff参数的话。我自己不需要这些。