ffnn.TucilWeka.java Source code

Java tutorial

Introduction

Here is the source code for ffnn.TucilWeka.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 ffnn;

import weka.core.SerializationHelper;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import weka.core.Attribute;
import weka.core.DenseInstance;
import weka.core.Instances;
import weka.core.converters.ConverterUtils.DataSource;
import weka.filters.Filter;
import weka.filters.supervised.attribute.Discretize;
import weka.filters.unsupervised.attribute.NumericToNominal;
import weka.classifiers.Evaluation;
import weka.classifiers.trees.J48;
import java.util.Random;
import weka.classifiers.Classifier;
import weka.classifiers.bayes.NaiveBayes;
import weka.core.Instance;

/**
 *
 * @author ASUS
 */
public class TucilWeka {
    public static Instances readDataSet(String filepath) {
        //Membaca dataset

        Instances data = null;
        try {
            data = DataSource.read(filepath);
        } catch (Exception ex) {
            Logger.getLogger(TucilWeka.class.getName()).log(Level.SEVERE, null, ex);
        }
        data.setClassIndex(data.numAttributes() - 1);
        return data;
    }

    public static Instances filterDiscretize(Instances a) {
        Discretize filter = new Discretize();
        Instances b = null;
        try {
            filter.setInputFormat(a);
            b = Filter.useFilter(a, filter);
        } catch (Exception ex) {
            Logger.getLogger(TucilWeka.class.getName()).log(Level.SEVERE, null, ex);
        }
        return b;
    }

    public static Instances filterNumericToNominal(Instances a) {
        NumericToNominal filter = new NumericToNominal();
        Instances b = null;
        try {

            filter.setInputFormat(a);
            b = Filter.useFilter(a, filter);
        } catch (Exception ex) {
            Logger.getLogger(TucilWeka.class.getName()).log(Level.SEVERE, null, ex);
        }
        return b;
    }

    public static Evaluation crossValidation(Instances data) {
        //10-fold cross validation
        Evaluation eval = null;
        try {

            eval = new Evaluation(data);
            Classifier cls = new FFNNTubesAI();
            if (cls == null) {
                System.out.println("MODEL CANNOT BE USED");
            } else {
                System.out.println("MODEL IS USED");
            }
            cls.buildClassifier(data);
            //crossValidateModel:
            //param 1 = tipe classifier (disini J48)
            //param 2 = Instances data
            //param 3 = jumlah fold
            //param 4 = Randomizer (seed)

            eval.crossValidateModel(cls, data, 10, new Random(1));
        } catch (Exception ex) {
            Logger.getLogger(TucilWeka.class.getName()).log(Level.SEVERE, null, ex);
        }
        return eval;
    }

    public static Evaluation fullTraining(Instances data) {
        //10-fold cross validation
        Evaluation eval = null;
        Instances train = new Instances(data);
        Instances test = new Instances(data);
        try {
            Classifier classify = new J48();
            //Membuat klasifier dari data training
            classify.buildClassifier(train);
            eval = new Evaluation(train);
            eval.evaluateModel(classify, test);
        } catch (Exception ex) {
            Logger.getLogger(TucilWeka.class.getName()).log(Level.SEVERE, null, ex);
        }
        return eval;
    }

    public static Classifier getClassifier(Instances data) {
        Classifier classify = new NaiveBayes();
        try {
            classify.buildClassifier(data);
        } catch (Exception ex) {
            Logger.getLogger(TucilWeka.class.getName()).log(Level.SEVERE, null, ex);
        }
        return classify;
    }

    public static void saveModel(Instances data) {
        //Menyimpan model ke file eksternal
        String pathFile = null;
        System.out.println("Masukkan nama file: ");
        Scanner scan = new Scanner(System.in);
        pathFile = scan.next();
        Classifier cls = getClassifier(data);
        try {
            SerializationHelper.write(pathFile, cls);
        } catch (Exception ex) {
            Logger.getLogger(TucilWeka.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    public static Object readModel() {
        String pathFile = null;
        Object o = null;
        System.out.println("Masukkan nama file: ");
        Scanner scan = new Scanner(System.in);
        pathFile = scan.next();
        try {
            o = SerializationHelper.read(pathFile);
        } catch (Exception ex) {
            Logger.getLogger(TucilWeka.class.getName()).log(Level.SEVERE, null, ex);
        }
        return o;
    }

    public static Instances createInstances(int max) {
        //List of Attributes dan List of Class untuk Header
        //Jumlah attributes: 4 jika tanpa class, 5 jika dengan class
        ArrayList<Attribute> attrs = new ArrayList<Attribute>(5);
        ArrayList<String> classVal = new ArrayList<String>();

        //Menambahkkan class yang mungkin ke List
        classVal.add("Iris-setosa");
        classVal.add("Iris-versicolor");
        classVal.add("Iris-virginica");

        //Menambahkan attributes ke List
        Attribute sepallength = new Attribute("sepallength");
        attrs.add(sepallength); //Numeric Attributes
        Attribute sepalwidth = new Attribute("sepalwidth");
        attrs.add(sepalwidth); //Numeric Attributes
        Attribute petallength = new Attribute("petallength");
        attrs.add(petallength); //Numeric Attributes
        Attribute petalwidth = new Attribute("petalwidth");
        attrs.add(petalwidth); //Numeric Attributes
        Attribute classValue = new Attribute("@@class@@", classVal);
        attrs.add(classValue); //String Attributes

        //Pembuatan
        //Constructor dengan param Nama, List of Attribute, size
        Instances dataRaw = new Instances("irisNew", attrs, 0); //Instances kosong
        dataRaw.setClassIndex(dataRaw.numAttributes() - 1);
        Scanner scan = new Scanner(System.in);

        for (int i = 0; i < max; i++) {
            //Weka mennyimpan instance sebagai double
            double temp;
            Instance inst = new DenseInstance(dataRaw.numAttributes());
            System.out.println("Sepallength:");
            temp = scan.nextDouble();
            inst.setValue(sepallength, temp);
            System.out.println("Sepalwidth:");
            temp = scan.nextDouble();
            inst.setValue(sepalwidth, temp);
            System.out.println("Petallegth:");
            temp = scan.nextDouble();
            inst.setValue(petallength, temp);
            System.out.println("Petalwidth:");
            temp = scan.nextDouble();
            inst.setValue(petalwidth, temp);

            //System.out.println("Masukan kelima:");
            //temp = scan.nextDouble();
            //0 -> setosa, 1 -> vesicolor, 2-> virginica
            //instS.setValue(classValue, temp); //tidak dibutuhkan sebenarnya

            //Menambahkan instance ke instances
            dataRaw.add(inst);
        }
        return dataRaw;
    }

    public static String testInstance(Classifier cls, Instances testData) {
        String value = null;
        double result = 0;
        try {
            result = cls.classifyInstance(testData.get(0));
        } catch (Exception ex) {
            Logger.getLogger(TucilWeka.class.getName()).log(Level.SEVERE, null, ex);
        }
        if (result == 0) {
            value = "iris-setosa / 0";
        } else if (result == 1) {
            value = "iris-vesicolor / 1";
        } else if (result == 2) {
            value = "iris-virginica / 2";
        } else {
            value = "error";
        }

        return value;
    }
}