1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48 | package KMeans;
import java.util.*;
public class Main {
public static void main(String[] args) {
KMeans km = new KMeans();
List<List<Integer>> lists = km.kmeans(new int[]{1,2,3,4,5,6,7,7,8,9,9,9,4,4,3});
for(List<Integer> group:lists){
System.out.println(group.toString());
}
}
}
class KMeans{
final double D = 0.001;
double getMean(List<Integer> group){
double s = 0;
for(int i : group) s+=i;
return s/(double)group.size();
}
List<List<Integer>> kmeans(int[] nums){
List<List<Integer>> list = new ArrayList<>();
double m1 = nums[0], m2 = nums[1];
while(true){
System.out.println(m1 + " " + m2);
List<Integer> g1 = new ArrayList<>();
List<Integer> g2 = new ArrayList<>();
for(int i : nums){
if(Math.abs(i-m1)<=Math.abs(i-m2)){
g1.add(i);
}else{
g2.add(i);
}
}
double t1 = getMean(g1), t2 = getMean(g2);
if(Math.abs(m1-t1)<=D && Math.abs(m2-t2)<=D){
list.add(g1);
list.add(g2);
return list;
}else{
m1 = t1;
m2 = t2;
}
}
}
}
|
No comments:
Post a Comment