K-Means Clustering Algorithm > Java Program
K-Means Clustering Algorithm > Java Program
Data Warehousing and Mining
Program:
import java.util.*;
public class KMeans {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter Number of Elements");
int n = sc.nextInt();
float[] a = new float[n];
for (int i = 0; i < n; i++) {
System.out.println("Enter Element:");
a[i] = sc.nextFloat();
}
System.out.println("Enter Number of Clusters");
int noclust = sc.nextInt();
float[] m = new float[noclust];
float temp[] = new float[n];
float clusters[][] = new float[noclust][n];
for (int i = 0; i < noclust; i++) {
m[i] = a[i];
}
while (true) {
//Display Mean Values
for (int p = 0; p < noclust; p++) {
System.out.print(m[p] + "\t");
}
System.out.print("\n");
boolean fin = true;
for (int i = 0; i < n; i++) {
int loc = 0;
temp[i] = (float) Math.abs(a[i] - m[0]);
for (int j = 1; j < noclust; j++) {
if (temp[i] > (float) Math.abs(a[i] - m[j])) {
temp[i] = (float) Math.abs(a[i] - m[j]);
loc = j;
}
}
if (clusters[loc][i] == 0) {
for (int x = 0; x < noclust; x++) {
clusters[x][i] = 0;
fin = false;
}
clusters[loc][i] = a[i];
}
}
for (int j = 0; j < noclust; j++) {
float sum = 0, count = 0;
for (int x = 0; x < n; x++) {
if (clusters[j][x] != 0) {
sum = sum + clusters[j][x];
count++;
}
}
m[j] = sum / count;
}
for (int p = 0; p < noclust; p++) {
for (int q = 0; q < n; q++) {
if (clusters[p][q] > 0) {
System.out.print(clusters[p][q] + "\t");
}
}
System.out.print("\n");
}
System.out.print("\n");
if (fin == true) {
break;
}
}
}
}
Output:
run:
Enter Number of Elements
9
Enter Element:
2
Enter Element:
4
Enter Element:
10
Enter Element:
12
Enter Element:
3
Enter Element:
20
Enter Element:
30
Enter Element:
11
Enter Element:
25
Enter Number of Clusters
2
2.0 4.0
2.0 3.0
4.0 10.0 12.0 20.0 30.0 11.0 25.0
2.5 16.0
2.0 4.0 3.0
10.0 12.0 20.0 30.0 11.0 25.0
3.0 18.0
2.0 4.0 10.0 3.0
12.0 20.0 30.0 11.0 25.0
4.75 19.6
2.0 4.0 10.0 12.0 3.0 11.0
20.0 30.0 25.0
7.0 25.0
2.0 4.0 10.0 12.0 3.0 11.0
20.0 30.0 25.0
BUILD SUCCESSFUL (total time: 36 seconds)
Comments
Post a Comment