我正在尝试编写一个k均值算法,并且现在处于非常基本的阶段 代码如下随机选择聚类中心:
import numpy as np
import random
X = [2,3,5,8,12,15,18]
C = 2
def rand_center(ip,C):
centers = {}
for i in range (C):
if i>0:
while centers[i] != centers[i-1]:
centers[i] = random.choice(X)
else:
centers[i] = random.choice(X)
return centers
print (centers)
rand_center(X,C)
当我运行它时,它给了我KeyError:1
任何人都可以指导我解决此错误?
答案 0 :(得分:1)
while centers[i] != centers[i-1]
... for i in range (C):
循环的第二次迭代会发生什么?
centers[1] != centers[0]
...此时没有centers[1]
。
答案 1 :(得分:0)
我想这个问题是因为数组的索引不正确。因此,如果您重新检查数组中传递的索引可能会帮助您解决此问题。如果您发布了导致此错误的行号,则对我调试代码会更有帮助。
答案 2 :(得分:0)
你的代码错了你应该按如下方式重写
find . -type f -name '*_top_hits.txt' -print -exec cat {} \; > combinedresults.txt
答案 3 :(得分:0)
我希望你期待输出:即。字典与键和价值 在Current,Previous和Next键中没有相同的值。
import numpy as np
import random
X = [2,3,5,8,12,15,18]
C = 2
def rand_center(ip,C):
centers = {}
for i in range (C):
rand_num = random.choice(X)
if i>0:
#Add Key and Value in Dictionary.
centers[i] = rand_num
#Check condition if it Doesn't follow the rule, then change value and retry.
while rand_num != centers[i-1]:
centers[i] = rand_num
#Change the current value
rand_num = random.choice(X)
else:
#First Key 0 not having previous element. Set it as default
centers[i] = rand_num
return centers
print"Output: ",rand_center(X,C)