00001 package edu.tum.cs.clustering; 00002 import java.util.Arrays; 00003 00004 import weka.clusterers.SimpleKMeans; 00005 00010 public class SimpleClusterer extends BasicClusterer<SimpleKMeans> { 00011 00012 int[] clusterIndex2sortedClusterIndex; 00013 00014 public SimpleClusterer(SimpleKMeans clusterer) { 00015 super(clusterer); 00016 } 00017 00018 public SimpleClusterer() { 00019 this(new SimpleKMeans()); 00020 } 00021 00022 public void buildClusterer(int numClusters) throws Exception { 00023 if(numClusters != 0) 00024 setNumClusters(numClusters); 00025 buildClusterer(); 00026 } 00027 00028 @Override 00029 public void buildClusterer() throws Exception { 00030 super.buildClusterer(); 00031 clusterIndex2sortedClusterIndex = getSortedCentroidIndices(); 00032 } 00033 00034 public void setNumClusters(int n) throws Exception { 00035 clusterer.setNumClusters(n); 00036 } 00037 00038 public double[] getCentroids() { 00039 return clusterer.getClusterCentroids().attributeToDoubleArray(0); 00040 } 00041 00042 public double[] getStdDevs() { 00043 return clusterer.getClusterStandardDevs().attributeToDoubleArray(0); 00044 } 00045 00051 @Override 00052 public int classify(double value) throws Exception { 00053 int i = super.classify(value); 00054 return clusterIndex2sortedClusterIndex[i]; 00055 } 00056 00062 protected int[] getSortedCentroidIndices() { 00063 // get an unsorted and a sorted version of the centroids array 00064 int numClusters = clusterer.getNumClusters(); 00065 double[] values = getCentroids(); 00066 double[] sorted_values = (double[]) values.clone(); 00067 Arrays.sort(sorted_values); 00068 // get an array of indices that corresponds to the sort order 00069 int[] indices = new int[numClusters]; 00070 for(int i = 0; i < numClusters; i++) 00071 for(int j = 0; j < numClusters; j++) 00072 if(sorted_values[i] == values[j]) 00073 indices[j] = i; 00074 return indices; 00075 } 00076 }