2016-11-23 86 views
0

我想寫一個k平均值算法,現在在非常基礎的階段。
的代碼如下隨機選擇聚類中心:Keyerror:1 python

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
任何人都可以引導我解決這個問題?

+1

順便說一句,你不能打印(或做任何事)後,返回的資料 –

回答

1

while centers[i] != centers[i-1] ... for i in range (C):循環的第二次迭代會發生什麼?

centers[1] != centers[0] ...在那時沒有centers[1]

0

我想這個問題是因爲數組的索引不正確。所以如果你重新檢查在數組中傳遞的索引可能會幫助你解決這個問題。如果您發佈了出現此錯誤的行號,那麼調試您的代碼會更有幫助。

0

你的代碼是錯誤的,你應該重新如下

import numpy as np 
import random 

X = [2,3,5,8,12,15,18] 

C = 2 

def rand_center(ip,C): 
    if C<1: 
     return [] 
    centers = [random.choice(ip)] 
    for i in range(1,min(C,len(ip))): 
     centers.append(random.choice(ip)) 
     while centers[i] in centers[:i]: 
      centers[i] = random.choice(ip)   
    return centers 

print (rand_center(X,C)) 
+0

謝謝大家! – leo

0

我希望你正在尋找輸出寫:即。帶有鍵和值的字典 在當前,上一個和下一個鍵中沒有相同的值。

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)