2016-11-23 9 views
0

私はk meansアルゴリズムを書こうとしていますが、今は非常に基本的な段階です。
ランダムクラスタリングのためのセンターを選択するために、次のようにコードがある:私はこれを実行すると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):ループの2回目の繰り返しではどうなりますか?

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)