@@ -72,20 +72,19 @@ def UpdateMean(n,mean,item):
72
72
73
73
return mean ;
74
74
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
79
77
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 ] ;
83
81
84
- #Add item to cluster
85
- clusters [index ].append (item );
82
+ clusters [classification ].append (item );
86
83
87
84
return clusters ;
88
85
86
+
87
+ ###_Core Functions_###
89
88
def Classify (means ,item ):
90
89
#Classify item to the mean with minimum distance
91
90
@@ -141,7 +140,9 @@ def CalculateMeans(k,items,maxIterations=100000):
141
140
if (noChange ):
142
141
break ;
143
142
144
- return means ;
143
+ clusters = FindClusters (k ,items ,belongsTo );
144
+
145
+ return means , clusters ;
145
146
146
147
147
148
###_Main_###
@@ -150,11 +151,9 @@ def main():
150
151
151
152
k = 3 ;
152
153
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 ;
158
157
159
158
#newItem = [5.4,3.7,1.5,0.2];
160
159
#print Classify(means,newItem);
0 commit comments