Kmeans聚类代码报错:list indices must be integers or slices, not tuple如何修复?
修复Kmeans代码中的"list indices must be integers or slices, not tuple"错误
错误原因
你遇到的错误是因为初始化的centroids是Python列表,而非numpy数组,而代码中使用了numpy特有的多维索引语法centroids[:, np.newaxis]——列表不支持这种元组形式的索引操作,因此抛出该错误。
修复步骤
- 将初始centroids转为numpy数组:在完成初始质心的循环选择后,把列表类型的
centroids转换为numpy数组,这样才能支持后续的多维索引运算。 - 移除冗余变量:代码中
n和d变量未被使用,直接删除即可。 - 避免硬编码样本数量:把
random.randint(0, 5610)改为random.randint(0, len(X)-1),让代码适配任意长度的输入数据,不用依赖固定的5610这个数值。
修改后的完整代码
import numpy as np import random def kmeans(X, k, max_iter = 100): centroids = [] for i in range(k): # 用len(X)-1替代硬编码的5610,适配任意输入长度 a = random.randint(0, len(X)-1) centroids.append(X[a]) # 关键:将列表转为numpy数组 centroids = np.array(centroids) for i in range(max_iter): distances = np.sqrt(((X - centroids[:, np.newaxis])**2).sum(axis=2)) label = np.argmin(distances, axis=0) new_centroids = np.array([X[label==j].mean(axis=0) for j in range(k)]) if np.allclose(centroids, new_centroids): break centroids = new_centroids return label, centroids
额外说明
- 原代码中
lable是拼写错误,已修正为label。 - 确保输入的
X本身是numpy数组,否则X[a]和后续的数组运算可能会出现其他问题。
内容的提问来源于stack exchange,提问作者Iman Khalil
相关产品推荐
相关产品推荐

