/* * Kmeans.java * * (C) 2008, Alex S. */ import java.awt.*; import java.util.*; /** * K-means, with K=4. * * This is an EM (Expectation Maximization) algorithm: 2 steps. * * In the first step (Expectation), we assign each point to a mean. * In the second step (Maximization), we recompute the mean from all assigned points. * repeat until the means are stable. */ public class Kmeans extends BufferedApplet { private int width,height; // points are read into this thing. private Vector points = new Vector(); private Vector classes = new Vector(); // point classes. // means/string/color private double[][] means = new double[4][2]; private String[] meansstr = new String[]{"x","o","w","a"}; private Color[] meanscolors = new Color[]{Color.red, Color.lightGray, Color.green, Color.blue }; // matrices to easily move from model to screen and vice versa. private pMatrix toscreen = null; private pMatrix tomodel = null; /** * initialize things */ public void init(){ super.init(); width = bounds().width; height = bounds().height; tomodel = pMatrix.reflecty3d().mult(pMatrix.translate3d(-width/2,-height/2,0)); toscreen = tomodel.inv3d(); // generate random means. for(int i=0;i 0){ means[i][0] /= cnt; means[i][1] /= cnt; }else{ // if nothing assigned to point, then make random mean. means[i][0] = Math.random()*width - width/2; means[i][1] = Math.random()*height - height/2; } } } // shade background according to classification. for(int y=0;y<=height;y+=4){ for(int x=0;x<=width;x+=4){ double[] p = tomodel.mult(new double[] { x-2, y-2,0,1 } ); int minmean = 0; double mindist = 999999999; // find the closest mean. for(int i=0;i