use weka Weka Cross Validation - Java Machine Learning AI

Java examples for Machine Learning AI:weka

Description

use weka Weka Cross Validation

Demo Code



import java.io.File;

import weka.classifiers.Classifier;
import weka.classifiers.evaluation.Evaluation;
import weka.classifiers.functions.LibSVM;
import weka.core.Debug.Random;
import weka.core.Instances;
import weka.core.SerializationHelper;
import weka.core.converters.ArffLoader;
import weka.core.converters.ConverterUtils.DataSource;

public class WekaCrossValidation {
    public static void main(String[] args) throws Exception {
        File inputFile = new File(
                "bank-train.arff");
        atf.setFile(inputFile);/*from w  w  w.  j a  va 2 s. c  o  m*/
        Instances instancesTrain = atf.getDataSet();
                "bank-test.arff");
        Instances instancesTest = source.getDataSet();
        instancesTest.setClassIndex(instancesTest.numAttributes() - 1);

        // libsvm
        Classifier classifier = new LibSVM();

        classifier.buildClassifier(instancesTrain);
        SerializationHelper.write(
                "libsvm.model", classifier);
        System.out.println(classifier.classifyInstance(instancesTest
                .instance(5)));

        Evaluation eval = new Evaluation(instancesTrain);
        eval.crossValidateModel(classifier, instancesTrain, 10, new Random(
                1));
        System.out.println(eval.errorRate());

        classifier = (Classifier) SerializationHelper
                .read("libsvm.model");

        classifier.buildClassifier(instancesTrain);
        System.out.println(classifier.classifyInstance(instancesTest
                .instance(5)));

        eval = new Evaluation(instancesTrain);
        eval.crossValidateModel(classifier, instancesTrain, 10, new Random(
                1));
        System.out.println(eval.errorRate());
    }
}

Related Tutorials