Skip to content

Commit ef9b25b

Browse files
authored
Update kMeans.py
1 parent 691c4e5 commit ef9b25b

File tree

1 file changed

+14
-15
lines changed

1 file changed

+14
-15
lines changed

Clustering/kMeans - Standard/kMeans.py

Lines changed: 14 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -72,20 +72,19 @@ def UpdateMean(n,mean,item):
7272

7373
return mean;
7474

75-
76-
###_Core Functions_###
77-
def FindClusters(means,items):
78-
clusters = [[] for i in range(len(means))]; #Init clusters
75+
def FindClusters(k,items,belongsTo):
76+
clusters = [[] for i in range(k)]; #Init clusters
7977

80-
for item in items:
81-
#Classify item into a cluster
82-
index = Classify(means,item);
78+
for i in range(len(items)):
79+
item = items[i];
80+
classification = belongsTo[i];
8381

84-
#Add item to cluster
85-
clusters[index].append(item);
82+
clusters[classification].append(item);
8683

8784
return clusters;
8885

86+
87+
###_Core Functions_###
8988
def Classify(means,item):
9089
#Classify item to the mean with minimum distance
9190

@@ -141,7 +140,9 @@ def CalculateMeans(k,items,maxIterations=100000):
141140
if(noChange):
142141
break;
143142

144-
return means;
143+
clusters = FindClusters(k,items,belongsTo);
144+
145+
return means, clusters;
145146

146147

147148
###_Main_###
@@ -150,11 +151,9 @@ def main():
150151

151152
k = 3;
152153

153-
means = CalculateMeans(k,items);
154-
print "Means = ", means;
155-
156-
clusters = FindClusters(means,items);
157-
print "Clusters: ", clusters;
154+
means, clusters = CalculateMeans(k,items);
155+
print means;
156+
print clusters;
158157

159158
#newItem = [5.4,3.7,1.5,0.2];
160159
#print Classify(means,newItem);

0 commit comments

Comments
 (0)