System.out.println("Vector size: " + vectors.size());
// SPECIAL CASE: If only one vector
if (vectors.size() == 1) {
// Create a single cluster and return it
DoubleArray vector = vectors.get(0);
Cluster cluster = new Cluster(vectorsSize);
cluster.addVector(vector);
clusters.add(cluster);
return clusters;
}
// (1) Randomly generate k empty clusters with a random mean (cluster
// center)
for(int i=0; i< k; i++){
int rand = 0 + (int)(Math.random() * vectors.size()-1);
DoubleArray meanVector = vectors.get(rand);
Cluster cluster = new Cluster(vectorsSize);
cluster.setMean(meanVector);
clusters.add(cluster);
}
// (2) Repeat the two next steps until the assignment hasn't changed
boolean changed;
while(true) {
iterationCount++;
changed = false;
// (2.1) Assign each point to the nearest cluster center.
// / for each vector
for (DoubleArray vector : vectors) {
// find the nearest cluster and the cluster containing the item
Cluster nearestCluster = null;
Cluster containingCluster = null;
double distanceToNearestCluster = Double.MAX_VALUE;
// for each cluster
for (Cluster cluster : clusters) {
// calculate the distance of the cluster mean to the vector
double distance = euclideanDistance(cluster.getmean(), vector);
// if it is the smallest distance until now, record this cluster
// and the distance
if (distance < distanceToNearestCluster) {
nearestCluster = cluster;
distanceToNearestCluster = distance;
}
// if the cluster contain the vector already,
// remember that too!
if (cluster.contains(vector)) {
containingCluster = cluster;
}
}
// if the nearest cluster is not the cluster containing
// the vector
if (containingCluster != nearestCluster) {
// remove the vector from the containing cluster
if (containingCluster != null) {
containingCluster.remove(vector);
}
// add the vector to the nearest cluster
nearestCluster.addVector(vector);
changed = true;
}