如何将无效索引固定为标量变量?

问题描述 投票:0回答:1

我尝试编写K-means算法,并在以下行得到此错误:points = np.array ([x[j] for j in range (len (x)) if cluster [j] == i])有人可以帮忙吗?

from copy import deepcopy

def euclidean_distance (a, b, ax = 1):
    return np.linalg.norm (a - b , axis = ax)

c_prev = np.zeros (c.shape)
clusters = np.zeros (len(x))

distance_differences = euclidean_distance (c, c_prev)

while distance_differences.any () != 0:
    for i in range (len(x)):
        distances = euclidean_distance (x[i], c)
        cluster = np.argmin (distances)
        clusters [i] = cluster
    c_prev = deepcopy (c)
    for i in range (k):
        points = [x[j] for j in range (len(x)) if clusters [j] == i]
        if len(points) != 0:
            c[i] = np.mean (points, axis = 0)

    distance_differences = euclidean_distance (c, c_prev)

colors = ['b', 'r', 'y', 'g', 'c', 'm']
for i in range (k):
    points = np.array ([x[j] for j in range (len (x)) if cluster [j] == i])
    if len(points) > 0:
        plt.scatter (points [:, 0], points [:, 1], s= 10, c = colors [i])
    else:
        print ('Please regenerate your centeroids again')

plt.scatter (points [:, 0], points [:, 1], s= 10, c = colors [i])
plt.scatter(c[:, 0], c[:, 1], marker = '*', s =100, c ='k')
plt.show();
python-3.x numpy jupyter-notebook k-means
1个回答
0
投票

是的,您输入中有错字,

points = np.array ([x[j] for j in range (len (x)) if cluster [j] == i])

它应该读为,

points = np.array ([x[j] for j in range (len (x)) if clusters[j] == i])

因为cluster只是一个标量(即只有一个值),clusters是数组

© www.soinside.com 2019 - 2024. All rights reserved.