实现 numpy bincount 以更改最常见值的一半



我正在使用numpy实现KMeans算法。

我正在制作一个名为距离的 numpy 数组,如下所示:

[[ 5.  1.  1.  1.  2.  1.  3.  1.  1.  1.]
 [ 5.  4.  4.  5.  7. 10.  3.  2.  1.  0.]
 [ 3.  1.  1.  1.  2.  2.  3.  1.  1.  1.]
 [ 6.  8.  8.  1.  3.  4.  3.  7.  1.  1.]
 [ 4.  1.  1.  3.  2.  1.  3.  1.  1.  1.]
 [ 8. 10. 10.  8.  7. 10.  9.  7.  1.  0.]
 [ 1.  1.  1.  1.  2. 10.  3.  1.  1.  0.]
 [ 2.  1.  2.  1.  2.  1.  3.  1.  1.  1.]
 [ 2.  1.  1.  1.  2.  1.  1.  1.  5.  1.]
 [ 4.  2.  1.  1.  2.  1.  2.  1.  1.  1.]]
其中前 9 列是数据点

,最后一列是数据点分配给初始化的随机质心的聚类。

在这个数组中,我希望看到这些值,最后一列中的 0,1,2。与上面给定的数组一样,我们只能在最后一列中看到 0,1。在这种情况下,我打算将最常见值的一半从最后一列更改为 2。

k=3
for c in range(k):
    if c in distances[:, -1]:
    else:
        x = np.bincount(distances[:,-1]).argmax()
        distances[:len(distances[distances[:,-1]==x])/2,-1][distances[:,-1] == x] = c

但是,这是行不通的。有人可以帮助我解决这个问题吗?

错误 -> 索引错误:布尔索引与维度 0 上的索引数组不匹配;维度为 0,但相应的布尔维度为 10

我认为这可能会对您有所帮助

如果distance是具有数组的变量

x=np.unique(distance[:,-1]).argmax()
pos=np.argwhere(distance[:,-1]==x).flatten()
for i in range(int(len(pos)/2)):
    distance[i,-1]=2

我希望这有帮助!

最新更新