gpt4 book ai didi

python - 从 numpy argmin 中删除轴参数,但仍然矢量化

转载 作者:行者123 更新时间:2023-12-01 08:02:09 24 4
gpt4 key购买 nike

所以我有以下几行代码

np.argmin(distances, axis = 0)

这里的distances是k个质心和n个点之间的距离矩阵。所以它是一个 k x n 矩阵。因此,通过这行代码,我试图通过沿轴 0 取 argmin 来找到每个点最近的质心。

我的目标是拥有一个类似的没有 axis 参数的向量化代码,因为它没有在我正在使用的 numpy 的分支中实现。

任何帮助都会很好:)

最佳答案

这是一个矢量化的 -

def partial_argsort(a):
idar = np.zeros(a.max()+1,dtype=int)
idar[a] = np.arange(len(a))
return idar[np.sort(a)]

def argmin_0(a):
# Define a scaling array to scale each col such that each col is
# offsetted against its previous one
s = (a.max()+1)*np.arange(a.shape[1])

# Scale each col, flatten with col-major order. Find global partial-argsort.
# With the offsetting, those argsort indices would be limited to per-col
# Subtract each group of ncols elements based on the offsetting.
m,n = a.shape
a1D = (a+s).T.ravel()
return partial_argsort(a1D)[::m]-m*np.arange(n)

运行示例进行验证 -

In [442]: np.random.seed(0)
...: a = np.random.randint(11,9999,(1000,1000))
...: idx0 = argmin_0(a)
...: idx1 = a.argmin(0)
...: r = np.arange(len(idx0))
...: print (a[idx0,r] == a[idx1,r]).all()
True

关于python - 从 numpy argmin 中删除轴参数,但仍然矢量化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55685300/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com