2016-11-25 9 views
1

Numpyを使用してPython 3でk-meansアルゴリズムを実装しようとしています。私のラベルのどれも同じではない、反復の各ステップにおける何らかの理由k-手段アルゴリズムが動作しない

[[1, 2], 
[3, 4], 
    ... 
[7, 13]] 

:私の入力データ行列は、点の単純なN×2データ・マトリクスです。すべてのラベルが異なります。誰かが私がやっている間違ったことを間違って見ますか?私は自分のコードにいくつかのコメントを追加して、人々が私がやっているさまざまなステップを理解できるようにしました。

def kmeans(X,k): 

    # Initialize by choosing k random data points as centroids 
    num_features = X.shape[1] 
    centroids = X[np.random.randint(X.shape[0], size=k), :] # find k centroids 
    iterations = 0 
    old_labels, labels = [], [] 

    while not should_stop(old_labels, labels, iterations): 
     iterations += 1 

     clusters = [[] for i in range(0,k)] 
     for i in range(k): 
      clusters[i].append(centroids[i]) 

     # Label points 
     old_labels = labels 
     labels = [] 
     for point in X: 
      distances = [np.linalg.norm(point-centroid) for centroid in centroids] 
      max_centroid = np.argmax(distances) 
      labels.append(max_centroid) 
      clusters[max_centroid].append(point) 

     # Compute new centroids 
     centroids = np.empty(shape=(0,num_features)) 
     for cluster in clusters: 
      avgs = sum(cluster)/len(cluster) 
      centroids = np.append(centroids, [avgs], axis=0) 

    return labels 

def should_stop(old_labels, labels, iterations): 
    count = 0 
    if len(old_labels) == 0: 
     return False 
    for i in range(len(labels)): 
     count += (old_labels[i] != labels[i]) 
    print(count) 
    if old_labels == labels or iterations == 2000: 
     return True 
    return False 

答えて

1
max_centroid = np.argmax(distances) 

あなたは距離ではなく、それを最大化するものを最小限に重心を見つけたいです。

+0

duh - ありがとう。 – Apollo

関連する問題