EMClustering.java 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. package classifier;
  2. import de.tu_darmstadt.tk.SmartHomeNetworkSim.core.Packet;
  3. import weka.clusterers.EM;
  4. import weka.core.Instance;
  5. import weka.core.Instances;
  6. /**
  7. * Expectation Maximization Clustering Approach
  8. * @author Andreas T. Meyer-Berg
  9. */
  10. public class EMClustering extends BasicPacketClassifier {
  11. /**
  12. * EM cluster which is used
  13. */
  14. private EM clusterer;
  15. /**
  16. * Initialize the clusterer
  17. */
  18. public EMClustering() {
  19. clusterer = new EM();
  20. }
  21. @Override
  22. public void trainModel(Instances instances) {
  23. try {
  24. clusterer.buildClusterer(instances);
  25. } catch (Exception e) {
  26. // TODO Auto-generated catch block
  27. e.printStackTrace();
  28. }
  29. }
  30. @Override
  31. public double classifyInstance(Instance instance, Packet origin) throws Exception {
  32. /**
  33. * Id of the closest cluster
  34. */
  35. int x = clusterer.clusterInstance(instance);
  36. /*
  37. System.out.println(origin.getTextualRepresentation()+": cluster: "+x+" Dens: "+clusterer.logDensityForInstance(instance)+" joined: ");
  38. double[] joined = clusterer.logJointDensitiesForInstance(instance);
  39. for(int i = 0;i<joined.length;) {
  40. System.out.print(joined[i]);
  41. if(++i<joined.length)
  42. System.out.print(", ");
  43. else
  44. System.out.println("");
  45. }
  46. System.out.println("Distribution:");
  47. double[] distribution = clusterer.distributionForInstance(instance);
  48. for(int i = 0;i<distribution.length;) {
  49. System.out.print(distribution[i]);
  50. if(++i<distribution.length)
  51. System.out.print(", ");
  52. else
  53. System.out.println("");
  54. }
  55. double[] priors = clusterer.clusterPriors();
  56. System.out.println("Priors: ");
  57. for(int i = 0; i<priors.length; i++) {
  58. System.out.println("i="+i+": "+priors[i]);
  59. }
  60. double[][][] rest = clusterer.getClusterModelsNumericAtts();
  61. double[][] posteriori = rest[x];
  62. for(int i = 0; i<posteriori.length; i++) {
  63. System.out.println("Att "+i+": Mean: "+posteriori[i][0]+" Std: "+posteriori[i][1]+" ???: "+posteriori[i][2]+" Real: "+instance.value(i));
  64. }*/
  65. return (1-clusterer.distributionForInstance(instance)[x])*800;
  66. }
  67. @Override
  68. public long getClassificationStart() {
  69. return 3600000;
  70. }
  71. @Override
  72. public String getAlgoName() {
  73. return "EM";
  74. }
  75. }