com.sliit.views.KNNView.java Source code

Java tutorial

Introduction

Here is the source code for com.sliit.views.KNNView.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.sliit.views;

import com.sliit.knnanalysis.features.Caplen;
import com.sliit.knnanalysis.features.Destination;
import com.sliit.knnanalysis.features.Feature;
import com.sliit.knnanalysis.features.Hlen;
import com.sliit.knnanalysis.features.Length;
import com.sliit.knnanalysis.features.Protocol;
import com.sliit.knnanalysis.features.Source;
import com.sliit.knnanalysis.features.Version;
import com.sliit.knnanlysis.FileReader;
import com.sliit.knnanlysis.Instance;
import com.sliit.knnanlysis.Neighbor;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
import weka.classifiers.Classifier;
import weka.classifiers.Evaluation;
import weka.classifiers.bayes.NaiveBayes;
import weka.classifiers.evaluation.ThresholdCurve;
import weka.core.Instances;
import weka.core.Utils;
import weka.gui.visualize.PlotData2D;
import weka.gui.visualize.ThresholdVisualizePanel;

/**
 *
 * @author Heshani
 */
public class KNNView extends javax.swing.JPanel {

    private String dataset;
    private String modal;
    final int K = 10;

    /**
     * Creates new form KNNView
     */
    public KNNView() {
        initComponents();
    }

    public KNNView(String dataset, String modal) {
        this();
        this.dataset = dataset;
        this.modal = modal;
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        knnPredictButton = new javax.swing.JButton();
        rouText = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        conclutionText = new javax.swing.JTextArea();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        rocPanel = new javax.swing.JPanel();

        setBackground(new java.awt.Color(255, 255, 255));

        knnPredictButton.setText("Predict");
        knnPredictButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                knnPredictButtonActionPerformed(evt);
            }
        });

        conclutionText.setColumns(20);
        conclutionText.setForeground(new java.awt.Color(255, 0, 0));
        conclutionText.setRows(5);
        jScrollPane1.setViewportView(conclutionText);

        jLabel3.setText("Conclusion : ");

        jLabel4.setText("Fraud Status :");

        rocPanel.setBackground(new java.awt.Color(255, 255, 255));
        rocPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("The Area Under an ROC Curve"));
        rocPanel.setLayout(new java.awt.CardLayout());

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup().addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addGroup(layout.createSequentialGroup().addComponent(knnPredictButton)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                        .addComponent(jLabel4)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(rouText, javax.swing.GroupLayout.PREFERRED_SIZE, 97,
                                                javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 104,
                                                Short.MAX_VALUE)
                                        .addComponent(jLabel3).addGap(18, 18, 18)
                                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 640,
                                                javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addGap(10, 10, 10))
                                .addComponent(rocPanel, javax.swing.GroupLayout.DEFAULT_SIZE,
                                        javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addContainerGap()));
        layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup().addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                        .addComponent(knnPredictButton).addComponent(jLabel4)
                                        .addComponent(rouText, javax.swing.GroupLayout.PREFERRED_SIZE,
                                                javax.swing.GroupLayout.DEFAULT_SIZE,
                                                javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addComponent(jLabel3))
                                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 37,
                                        javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(7, 7, 7)
                        .addComponent(rocPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 357, Short.MAX_VALUE)
                        .addContainerGap()));
    }// </editor-fold>//GEN-END:initComponents

    private void knnPredictButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_knnPredictButtonActionPerformed
        try {
            List<Instance> instances = new FileReader(PredictorPanel.locationText.getText()).getInstances();
            Instance classificationInstance = getClassificationInstance();
            List<Neighbor> nearestNeighbors = getKNearestNeighbors(K, instances, classificationInstance);
            Instance classifiedInstance = determineFraudStatus(classificationInstance, nearestNeighbors);

            System.out.println("Frud Status of Classification Instance : " + classifiedInstance.getFraudStatus());
            String conclusion = "";

            if (classifiedInstance.getFraudStatus() == true) {
                rouText.setText("True");
                conclusion = "Your Machine is Protected.\nSuspicious network traffic not detected.";
            } else {
                rouText.setText("False");
                conclusion = "Your Machine is Highly Vulnerable for an Attack.\nYou will face network treats";
            }

            conclutionText.setText(conclusion);
        } catch (IOException ex) {
            Logger.getLogger(KNNView.class.getName()).log(Level.SEVERE, null, ex);
        }

        getRocCurve();
    }//GEN-LAST:event_knnPredictButtonActionPerformed

    private static Instance getClassificationInstance() {
        List<Feature> attributes = new ArrayList<>();
        Instance instance = new Instance();
        attributes.add(new Source("443"));
        attributes.add(new Destination("63846"));
        attributes.add(new Protocol(Protocol.Protocols.Tcp));
        attributes.add(new Length(54));
        attributes.add(new Caplen(54));
        attributes.add(new Hlen(5));
        attributes.add(new Version(0));
        instance.setFeatures(attributes);
        return instance;
    }

    private static List<Neighbor> getKNearestNeighbors(int K, List<Instance> instances,
            Instance classificationInstance) {

        HashMap<String, Double> ciFeatureDistances = new HashMap<>();
        for (Feature feature : classificationInstance.getFeatures()) {
            ciFeatureDistances.put(feature.getFeatureName(), feature.getDistance());
        }

        List<Neighbor> neighbors = new ArrayList<>();
        for (Instance instance : instances) {
            double distance = 0;
            for (Feature feature : classificationInstance.getFeatures()) {
                double ciFeatureDistance = ciFeatureDistances.get(feature.getFeatureName());
                distance += Math.pow((feature.getDistance() - ciFeatureDistance), 2);
            }
            Neighbor neighbor = new Neighbor(instance, distance);
            neighbors.add(neighbor);
        }

        if (K < neighbors.size()) {
            Collections.sort(neighbors, new Comparator<Neighbor>() {
                @Override
                public int compare(Neighbor neighbor1, Neighbor neighbor2) {
                    double difference = neighbor1.getDistance() - neighbor2.getDistance();
                    if (difference == 0) {
                        return 0;
                    } else if (difference > 0) {
                        return 1;
                    } else {
                        return -1;
                    }
                }
            });

            neighbors = neighbors.subList(0, K);
        }
        return neighbors;
    }

    private static Instance determineFraudStatus(Instance classificationInstance, List<Neighbor> nearestNeighbors) {
        int frudCount = 0, normalCount = 0;

        for (Neighbor neighbor : nearestNeighbors) {
            if (neighbor.getInstance().isFraud()) {
                frudCount++;
            } else {
                normalCount++;
            }
        }

        if (frudCount > normalCount) {
            classificationInstance.setFraudStatus(true);
        } else {
            classificationInstance.setFraudStatus(false);
        }

        return classificationInstance;
    }

    void getRocCurve() {
        try {
            Instances data;
            data = new Instances(new BufferedReader(new java.io.FileReader(PredictorPanel.modalText.getText())));
            data.setClassIndex(data.numAttributes() - 1);

            // train classifier
            Classifier cl = new NaiveBayes();
            Evaluation eval = new Evaluation(data);
            eval.crossValidateModel(cl, data, 10, new Random(1));

            // generate curve
            ThresholdCurve tc = new ThresholdCurve();
            int classIndex = 0;
            Instances result = tc.getCurve(eval.predictions(), classIndex);

            // plot curve
            ThresholdVisualizePanel vmc = new ThresholdVisualizePanel();
            vmc.setROCString("(Area under ROC = " + Utils.doubleToString(tc.getROCArea(result), 4) + ")");
            vmc.setName(result.relationName());
            PlotData2D tempd = new PlotData2D(result);
            tempd.setPlotName(result.relationName());
            tempd.addInstanceNumberAttribute();
            // specify which points are connected
            boolean[] cp = new boolean[result.numInstances()];
            for (int n = 1; n < cp.length; n++) {
                cp[n] = true;
            }
            tempd.setConnectPoints(cp);
            // add plot
            vmc.addPlot(tempd);

            rocPanel.removeAll();
            rocPanel.add(vmc, "vmc", 0);
            rocPanel.revalidate();

        } catch (IOException ex) {
            Logger.getLogger(DataVisualizerPanel.class.getName()).log(Level.SEVERE, null, ex);
        } catch (Exception ex) {
            Logger.getLogger(DataVisualizerPanel.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextArea conclutionText;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JButton knnPredictButton;
    private javax.swing.JPanel rocPanel;
    private javax.swing.JTextField rouText;
    // End of variables declaration//GEN-END:variables
}