@@ -72,14 +72,15 @@ def UpdateMean(n,mean,item):
72
72
73
73
return mean ;
74
74
75
- def FindClusters (k ,items , belongsTo ):
76
- clusters = [[] for i in range (k )]; #Init clusters
75
+ def FindClusters (means ,items ):
76
+ clusters = [[] for i in range (len ( means ) )]; #Init clusters
77
77
78
- for i in range ( len ( items )) :
79
- item = items [ i ];
80
- classification = belongsTo [ i ] ;
78
+ for item in items :
79
+ #Classify item into a cluster
80
+ index = Classify ( means , item ) ;
81
81
82
- clusters [classification ].append (item );
82
+ #Add item to cluster
83
+ clusters [index ].append (item );
83
84
84
85
return clusters ;
85
86
@@ -110,7 +111,7 @@ def CalculateMeans(k,items,maxIterations=100000):
110
111
111
112
#Initialize clusters, the array to hold
112
113
#the number of items in a class
113
- clusters = [0 for i in range (len (means ))];
114
+ clusterLengths = [0 for i in range (len (means ))];
114
115
115
116
#An array to hold the cluster an item is in
116
117
belongsTo = [0 for i in range (len (items ))];
@@ -119,16 +120,15 @@ def CalculateMeans(k,items,maxIterations=100000):
119
120
for e in range (maxIterations ):
120
121
#If no change of cluster occurs, halt
121
122
noChange = True ;
122
- clusters = [0 for i in range (len (means ))];
123
123
for i in range (len (items )):
124
124
item = items [i ];
125
125
#Classify item into a cluster and update the
126
126
#corresponding means.
127
127
128
128
index = Classify (means ,item );
129
129
130
- clusters [index ] += 1 ;
131
- means [index ] = UpdateMean (clusters [index ],means [index ],item );
130
+ clusterLengths [index ] += 1 ;
131
+ means [index ] = UpdateMean (clusterLengths [index ],means [index ],item );
132
132
133
133
#Item changed cluster
134
134
if (index != belongsTo [i ]):
@@ -140,9 +140,7 @@ def CalculateMeans(k,items,maxIterations=100000):
140
140
if (noChange ):
141
141
break ;
142
142
143
- clusters = FindClusters (k ,items ,belongsTo );
144
-
145
- return means , clusters ;
143
+ return means ;
146
144
147
145
148
146
###_Main_###
@@ -151,7 +149,8 @@ def main():
151
149
152
150
k = 3 ;
153
151
154
- means , clusters = CalculateMeans (k ,items );
152
+ means = CalculateMeans (k ,items );
153
+ clusters = FindClusters (means ,items );
155
154
print means ;
156
155
print clusters ;
157
156
0 commit comments