【问题标题】:How to fix Invalid index to scalar variable?如何修复标量变量的无效索引?
【发布时间】:2020-09-13 00:53:36
【问题描述】:

我尝试编写 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();

【问题讨论】:

  • 请详细说明错误并可能解释您要达到的目标,而不是期望读者事先知道您的意思!
  • 还有c、x和k是什么?
  • 抱歉简短的解释。我想编写 k-means 聚类算法并对其进行测试。 c 是随机质心,x 是包含所有示例点的矩阵,k 是簇的编号。

标签: python-3.x numpy jupyter-notebook k-means


【解决方案1】:

是的,你的行中有错字,

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 是数组

【讨论】:

  • 是的,这是我的错误,现在可以使用了!谢谢!
猜你喜欢
  • 2016-01-03
  • 2021-01-01
  • 2020-05-17
  • 2020-06-20
  • 1970-01-01
  • 1970-01-01
  • 2020-05-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多