UnsupervisedAnomalyDetectionExample.java 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. import java.util.HashMap;
  2. import java.util.LinkedList;
  3. import de.tu_darmstadt.tk.SmartHomeNetworkSim.core.Link;
  4. import de.tu_darmstadt.tk.SmartHomeNetworkSim.core.Packet;
  5. import de.tu_darmstadt.tk.SmartHomeNetworkSim.core.PacketSniffer;
  6. import weka.clusterers.SimpleKMeans;
  7. import weka.core.Instance;
  8. import weka.core.Instances;
  9. /**
  10. * Unsupervised Example - maybe Clustering
  11. *
  12. * @author Andreas T. Meyer-Berg
  13. */
  14. public class UnsupervisedAnomalyDetectionExample implements PacketSniffer {
  15. /**
  16. * Clusterer
  17. */
  18. private SimpleKMeans clusterer;
  19. /**
  20. * True, if instances should be used for training
  21. */
  22. private boolean training = true;
  23. /**
  24. *
  25. */
  26. public UnsupervisedAnomalyDetectionExample() {
  27. clusterer = new SimpleKMeans();
  28. clusterer.setSeed(42);
  29. try {
  30. clusterer.setNumClusters(20);
  31. } catch (Exception e) {
  32. System.out.println("Error while building cluster");
  33. e.printStackTrace();
  34. }
  35. }
  36. @Override
  37. public void processPackets(HashMap<Link, LinkedList<Packet>> packets) {
  38. if(!packets.entrySet().isEmpty() && packets.entrySet().iterator().next().getValue().getFirst().getTimestamp()>10000)
  39. training = false;
  40. Instances processed = preProcess(packets);
  41. if(training)
  42. try {
  43. training(processed);
  44. } catch (Exception e) {
  45. // TODO Auto-generated catch block
  46. e.printStackTrace();
  47. }
  48. else
  49. classify(processed);
  50. }
  51. private Instances preProcess(HashMap<Link, LinkedList<Packet>> packets) {
  52. return null;
  53. }
  54. private void training(Instances processed) throws Exception {
  55. clusterer.buildClusterer(processed);
  56. }
  57. private void classify(Instances processed) {
  58. for(Instance i:processed)
  59. try {
  60. clusterer.clusterInstance(i);
  61. } catch (Exception e) {
  62. System.out.println("Anomaly "+i);
  63. e.printStackTrace();
  64. }
  65. }
  66. }