I have implemented the k-Means Clustering Algorithm using the Wolfram Language. However, I think it can be more efficient. Do you have any idea how to make it more efficient (e.g., by removing the Table[], Do[], AppendTo[])?
Many thank!
kMeans[data_, k_] := Module[{x = N[data], c, cn, n = Length[data], min, clusters, sum,
t = 0},
(* Randomly choose k centriods from the data points *)
c = RandomSample[x, k];
Do [
t++;
Print["iteration # ", t];
(* Initialize the clusters as empty *)
clusters = Table[{}, k];
(* Assign each point to the cluster of the closest centriod *)
Table [
d = Map[EuclideanDistance[#, x[[i]]] &, c];
min = Ordering[d, 1][[1]];
AppendTo[clusters[[min]], x[[i]]];
, {i, 1, n}]; (* End do *)
Print["Centroids = ", c];
(* Calculate the new centriods *)
cn = Mean /@ clusters;
(* If the centriods are the "almost" same then terminate*)
If [ Select[
Flatten[
MapThread[Abs[#1 - #2] &, { c, cn}]], # > 0.001 &] == {} ,
Break[], c = cn];
, {10 (* Maximum number of iterations *)}];
{clusters, c}
]
FindClusters
(see the "possible settings for Method" in the Details and options section). Are there specific features that you are trying to add to the existing implementation? $\endgroup$