public class KMeans {
public static void main(String[] args) {
int data[] = {2, 5, 6, 8, 12, 15, 18, 28, 30}; // initial data
int noofclusters = 3;
int centroid[][] = new int[][]{
{0, 0, 0},
{2, 12, 30}
};
getCentroid(data, noofclusters, centroid);
}
public static int[][] getCentroid(int data[], int noofclusters, int centroid[][]) {
int distance[][] = new int[noofclusters][data.length];
int cluster[] = new int[data.length];
int clusternodecount[] = new int[noofclusters];
centroid[0] = centroid[1];
centroid[1] = new int[]{0, 0, 0};
System.out.println("========== Starting to get new centroid =========");
for (int i = 0; i < noofclusters; i++) {
for (int j = 0; j < data.length; j++) {
distance[i][j] = Math.abs(data[j] - centroid[0][i]);
System.out.print(distance[i][j] + " ,");
}
System.out.println();
}
for (int j = 0; j < data.length; j++) {
int smallerDistance = 0;
if (distance[0][j] < distance[1][j] && distance[0][j] < distance[2][j]) {
smallerDistance = 0;
}
if (distance[1][j] < distance[0][j] && distance[1][j] < distance[2][j]) {
smallerDistance = 1;
}
if (distance[2][j] < distance[0][j] && distance[2][j] < distance[1][j]) {
smallerDistance = 2;
}
centroid[1][smallerDistance] = centroid[1][smallerDistance] + data[j];
clusternodecount[smallerDistance] = clusternodecount[smallerDistance] + 1;
cluster[j] = smallerDistance;
}
System.out.println("New centroid is ");
for (int j = 0; j < noofclusters; j++) {
centroid[1][j] = centroid[1][j] / clusternodecount[j];
System.out.print(centroid[1][j] + ",");
}
System.out.println();
boolean isAchived = true;
for (int j = 0; j < noofclusters; j++) {
if (isAchived && centroid[0][j] == centroid[1][j]) {
isAchived = true;
continue;
}
isAchived = false;
}
if (!isAchived) {
getCentroid(data, noofclusters, centroid);
}
if (isAchived) {
System.out.println("======================================== ");
System.out.println(" Final Cluster is ");
for (int i = 0; i < noofclusters; i++) {
for (int j = 0; j < data.length; j++) {
if (cluster[j] == i) {
System.out.print(data[j] + " ,");
}
}
System.out.println();
}
}
return centroid;
}
}
/* OUTPUT
========== Starting to get new centroid =========
0 ,3 ,4 ,6 ,10 ,13 ,16 ,26 ,28 ,
10 ,7 ,6 ,4 ,0 ,3 ,6 ,16 ,18 ,
28 ,25 ,24 ,22 ,18 ,15 ,12 ,2 ,0 ,
New centroid is
4,13,29,
========== Starting to get new centroid =========
2 ,1 ,2 ,4 ,8 ,11 ,14 ,24 ,26 ,
11 ,8 ,7 ,5 ,1 ,2 ,5 ,15 ,17 ,
27 ,24 ,23 ,21 ,17 ,14 ,11 ,1 ,1 ,
New centroid is
5,15,29,
========== Starting to get new centroid =========
3 ,0 ,1 ,3 ,7 ,10 ,13 ,23 ,25 ,
13 ,10 ,9 ,7 ,3 ,0 ,3 ,13 ,15 ,
27 ,24 ,23 ,21 ,17 ,14 ,11 ,1 ,1 ,
New centroid is
5,15,29,
========================================
Final Cluster is
2 ,5 ,6 ,8 ,
12 ,15 ,18 ,
28 ,30 ,
*/
No comments:
Post a Comment