Example usage for weka.classifiers Classifier classifyInstance

List of usage examples for weka.classifiers Classifier classifyInstance

Introduction

In this page you can find the example usage for weka.classifiers Classifier classifyInstance.

Prototype

public double classifyInstance(Instance instance) throws Exception;

Source Link

Document

Classifies the given test instance.

Usage

From source file:meddle.PredictByDomainOS.java

License:Open Source License

private static boolean predictOneFlow(String line, String domainOS) {
    if (!domainOSModel.containsKey(domainOS))
        return false;
    else {//from  www  .j ava 2 s.c  o m
        try {
            Classifier classifier = domainOSModel.get(domainOS);
            Map<String, Integer> fi = domainOSFeature.get(domainOS);
            Instances structure = domainOSStruct.get(domainOS);
            Instance current = getInstance(line, fi, fi.size());

            Instances is = new Instances(structure);
            is.setClassIndex(is.numAttributes() - 1);
            is.add(current);
            current = is.get(is.size() - 1);
            current.setClassMissing();
            double predicted = classifier.classifyInstance(current);
            if (predicted > 0) {
                return true;
            } else
                return false;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return false;
}

From source file:mlflex.WekaInMemoryLearner.java

License:Open Source License

@Override
protected ModelPredictions TrainTest(ArrayList<String> classificationParameters,
        DataInstanceCollection trainData, DataInstanceCollection testData,
        DataInstanceCollection dependentVariableInstances) throws Exception {
    ArrayList<String> dataPointNames = Lists.SortStringList(trainData.GetDataPointNames());
    FastVector attVector = GetAttributeVector(dependentVariableInstances, dataPointNames, trainData, testData);

    Instances wekaTrainingInstances = GetInstances(dependentVariableInstances, attVector, trainData);
    Instances wekaTestInstances = GetInstances(dependentVariableInstances, attVector, testData);

    ArrayList<String> dependentVariableClasses = Utilities.ProcessorVault.DependentVariableDataProcessor
            .GetUniqueDependentVariableValues();

    Classifier classifier = GetClassifier(classificationParameters);
    classifier.buildClassifier(wekaTrainingInstances);

    Predictions predictions = new Predictions();

    for (DataValues testInstance : testData) {
        String dependentVariableValue = dependentVariableInstances.Get(testInstance.GetID())
                .GetDataPointValue(0);//from w  w  w. ja  va2  s .  c  o m

        // This is the default before the prediction is made
        Prediction prediction = new Prediction(testInstance.GetID(), dependentVariableValue,
                Lists.PickRandomValue(dependentVariableClasses),
                Lists.CreateDoubleList(0.5, dependentVariableClasses.size()));

        if (!testInstance.HasOnlyMissingValues()) {
            Instance wekaTestInstance = GetInstance(wekaTestInstances, attVector, testInstance, null);

            double clsLabel = classifier.classifyInstance(wekaTestInstance);
            String predictedClass = wekaTestInstance.classAttribute().value((int) clsLabel);

            double[] probabilities = classifier.distributionForInstance(wekaTestInstance);
            ArrayList<Double> classProbabilities = Lists.CreateDoubleList(probabilities);

            prediction = new Prediction(testInstance.GetID(), dependentVariableValue, predictedClass,
                    classProbabilities);
        }

        predictions.Add(prediction);
    }

    classifier = null;

    return new ModelPredictions("", predictions);
}

From source file:moa.tud.ke.patching.AdaptivePatchingAdwin.java

private Vector determineSubsets(Instances data, Classifier detector) {
    Vector subsets = new Vector();

    if (detector instanceof DeciderEnumerator) {

        DeciderEnumerator decider = (DeciderEnumerator) detector;

        int numDeciders = decider.getAmountOfDeciders();
        int lastDecider = 0;

        Boolean isMultiDecider = true;

        int d = 0;
        if (numDeciders == 1) { // ACHTUNG: wenn nur ein Decider da ist (also keine Subunterteilung der decision spaces vorliegt)
            d = 1; // dann wird hier die parametrisierung fr die folgende schleife angepasst.
            numDeciders++;//from ww  w  .  java2s  . c om
            isMultiDecider = false;
        }

        //System.out.println("Total instances: "+data.size());
        // In order to save some ram we are going to do this iteratively
        while (d < numDeciders) {
            Instances copy = new Instances(data); // Make a clone of the full dataset

            // Iterate over all instances, classify them and delete all instances
            // that do not belong to the current decider from the dataset
            Iterator i = copy.iterator();

            try {

                while (i.hasNext()) {
                    weka.core.Instance inst = (weka.core.Instance) i.next();

                    double cls = detector.classifyInstance(inst);

                    if (isMultiDecider) {
                        lastDecider = decider.getLastUsedDecider();
                        if (lastDecider != d) {
                            i.remove();
                        } else {
                            if (cls == 1) {
                                i.remove(); // if the initial classification is correct, we wont bother!!
                            }
                        }
                    } else {
                        if (cls == 1) {
                            i.remove(); // if the initial classification is correct, we wont bother!!
                        }
                    }
                }
            } catch (Exception e) {
                System.err.println("Something went wrong while trying to split into subsets:");
                System.err.println(e.getMessage());
            }

            subsets.add(copy);
            d++;
        }

        //            int defaultDecider = decider.getDefaultDecider();
        //            if (decider.getAmountOfDeciders() > 1 && defaultDecider >= 0) {
        //                subsets.remove(defaultDecider);
        //            }
    }

    return subsets;
}

From source file:moa.tud.ke.patching.AdaptivePatchingAdwin.java

private double determinePerformance(Instances data, Classifier classif) {

    double numInstances = data.numInstances();
    double correctInstances = 0;
    double klasse;
    double accuracy;

    change = false;/*from  w ww  .  j a  va  2 s.  c o  m*/

    counter_one = 0;
    counter_zero = 0;

    try {
        Iterator in_it = data.iterator();
        while (in_it.hasNext()) {
            weka.core.Instance ins = (weka.core.Instance) in_it.next();
            klasse = classif.classifyInstance(ins);

            if (klasse == ins.classValue()) {
                correctInstances++;
            }

            double estimatedError = this.ADError.getEstimation();
            //System.out.println("estimatedError1: " + estimatedError);
            if (this.ADError.setInput(klasse == ins.classValue() ? 0 : 1, true)) {
                if (this.ADError.getEstimation() > estimatedError) {
                    change = true;
                    System.out.println("Change detected!");
                } else {
                    System.out.println("no change");
                }
            }

            if (klasse == ins.classValue()) {
                counter_one++;
            } else {
                counter_zero++;
            }

            /*
            System.out.println("Estimation: " + ADError.getEstimation());
            System.out.println("Variance: " + ADError.getVariance());
            System.out.println("Total: " + ADError.getTotal());
            System.out.println("Width: " + ADError.getWidth());
            */

        }

        if (numInstances != 0) {
            accuracy = correctInstances / numInstances;
        } else {
            accuracy = 0;
        }

        return accuracy;

    } catch (Exception e) {
        System.err.println("Something went wrong while trying to classify the data");
        System.err.println(e.getMessage());
    }

    return 0;
}

From source file:moa.tud.ke.patching.AdaptivePatchingAdwin.java

public double classifyInstance(weka.core.Instance inst) throws Exception {

    int region = -1;
    int defaultDecider = -1;
    int amountDeciders = -1;
    double label;

    weka.core.Instance origInst = inst;//from w w  w  .  j  ava  2 s. c  o  m

    try {
        if (this.regionDecider != null) {

            // Handling of optional usage of the base class as an additional attribute.
            if (this.useBaseClassAsAttribute.isSet()) {
                Instances tmp = new Instances(this.prototypeData); // deep copy of our empty prototypeData
                tmp.add(inst);
                tmp = addBaseClassToInstances(tmp);
                weka.core.Instance inst2 = tmp.get(0);
                inst = inst2;
                inst2 = null;
            }

            // Pre-classify instance and retrieve the used Decider
            double regClass = this.regionDecider.classifyInstance(inst);

            if (regClass == 0) { // only if its in a "wrong" region

                Boolean isMultiDecider = false;
                if (this.regionDecider.getAmountOfDeciders() > 1) {
                    isMultiDecider = true;
                }

                Classifier patch;

                if (isMultiDecider) {
                    region = this.regionDecider.getLastUsedDecider();

                    //                        System.out.println("using patch region decider: "+region);

                    patch = (Classifier) regionPatches.elementAt(region);
                    if (patch != null) {
                        return patch.classifyInstance(inst);
                    }
                } else { // case b: we only have a 0/1 information about if its in the error region or not.
                    patch = (Classifier) regionPatches.elementAt(0);
                    if (patch != null) {
                        return patch.classifyInstance(inst);
                    }

                }
            } else { // if its not in a "wrong" region, return the class from the base classifier
                if (this.useBaseClassAsAttribute.isSet()) {
                    return inst.value(0); // this has maybe already been calculated into the first attribute.
                }
            }
        }
    } catch (Exception e) {
        System.err.println("AdaptivePatching : Error in classifyInstance while using regionDecider.");
        System.out.println("Region: " + region + " DefaultDecider:" + defaultDecider + " amountDeciders:"
                + amountDeciders + " regionPatches#:" + regionPatches.size());
        e.printStackTrace();
        System.exit(234545345);
    }

    return baseClassifier.classifyInstance(origInst);
}

From source file:moa.tud.ke.patching.AdaptivePatchingTwoAdwins.java

private Vector determineSubsets(Instances data, Classifier detector) {
    Vector subsets = new Vector();

    if (detector instanceof DeciderEnumerator) {

        DeciderEnumerator decider = (DeciderEnumerator) detector;

        int numDeciders = decider.getAmountOfDeciders();
        int lastDecider = 0;

        Boolean isMultiDecider = true;

        int d = 0;
        if (numDeciders == 1) { // ACHTUNG: wenn nur ein Decider da ist (also keine Subunterteilung der decision spaces vorliegt)
            d = 1; // dann wird hier die parametrisierung fr die folgende schleife angepasst.
            numDeciders++;//from  w  w  w  . ja  v a  2 s.c  o m
            isMultiDecider = false;
        }

        //System.out.println("Total instances: "+data.size());
        // In order to save some ram we are going to do this iteratively
        while (d < numDeciders) {
            Instances copy = new Instances(data); // Make a clone of the full dataset

            // Iterate over all instances, classify them and delete all instances
            // that do not belong to the current decider from the dataset
            Iterator i = copy.iterator();
            try {
                while (i.hasNext()) {
                    weka.core.Instance inst = (weka.core.Instance) i.next();

                    double cls = detector.classifyInstance(inst);
                    if (isMultiDecider) {
                        lastDecider = decider.getLastUsedDecider();
                        if (lastDecider != d) {
                            i.remove();
                        } else {
                            if (cls == 1) {
                                i.remove(); // if the initial classification is correct, we wont bother!!
                            }
                        }
                    } else {
                        if (cls == 1) {
                            i.remove(); // if the initial classification is correct, we wont bother!!
                        }
                    }
                }
            } catch (Exception e) {
                System.err.println("Something went wrong while trying to split into subsets:");
                System.err.println(e.getMessage());
            }

            subsets.add(copy);
            d++;
        }

        //            int defaultDecider = decider.getDefaultDecider();
        //            if (decider.getAmountOfDeciders() > 1 && defaultDecider >= 0) {
        //                subsets.remove(defaultDecider);
        //            }
    }

    return subsets;
}

From source file:moa.tud.ke.patching.AdaptivePatchingTwoAdwins.java

private double determinePerformance(Instances data, Classifier classif) {

    double numInstances = data.numInstances();
    double correctInstances = 0;
    double klasse;
    double accuracy;

    change = false;/*from  w w  w  .  jav  a 2 s. c  om*/
    changeFine = false;

    try {
        Iterator in_it = data.iterator();
        while (in_it.hasNext()) {
            weka.core.Instance ins = (weka.core.Instance) in_it.next();
            klasse = classif.classifyInstance(ins);

            if (klasse == ins.classValue()) {
                correctInstances++;
            }

            double estimatedError = this.ADError.getEstimation();
            //System.out.println("estimatedError1: " + estimatedError);
            if (this.ADError.setInput(klasse == ins.classValue() ? 0 : 1, true)) {
                if (this.ADError.getEstimation() > estimatedError) {
                    change = true;
                    System.out.println("Change detected!");
                } else {
                    System.out.println("no change");
                }
            }

            //System.out.println("estimatedError1: " + estimatedError);
            if (this.ADError.setInput(-1, fineAdwinDelta.getValue(), false)) {
                changeFine = true;
                System.out.println("Fine Change detected!");
            }

            /*
            System.out.println("Estimation: " + ADError.getEstimation());
            System.out.println("Variance: " + ADError.getVariance());
            System.out.println("Total: " + ADError.getTotal());
            System.out.println("Width: " + ADError.getWidth());
            */

        }

        if (numInstances != 0) {
            accuracy = correctInstances / numInstances;
        } else {
            accuracy = 0;
        }

        return accuracy;

    } catch (Exception e) {
        System.err.println("Something went wrong while trying to classify the data");
        System.err.println(e.getMessage());
    }

    return 0;
}

From source file:moa.tud.ke.patching.Patching.java

/**
 * Takes the error space classifier and splits the instances into subsets,
 * each consisting of all instances that belong to one rule or one leaf in
 * the error space classifier. Requirement: error space classifier
 * implements DeciderEnumerator/*from   ww w.ja v  a  2s.c  o m*/
 *
 * @param data
 * @param detector
 * @return
 */
private Vector determineSubsets(Instances data, Classifier detector) {
    Vector subsets = new Vector();

    if (detector instanceof DeciderEnumerator) {

        DeciderEnumerator decider = (DeciderEnumerator) detector;

        int numDeciders = decider.getAmountOfDeciders();
        int lastDecider = 0;

        Boolean isMultiDecider = true;

        int d = 0;
        if (numDeciders == 1) { // ACHTUNG: wenn nur ein Decider da ist (also keine Subunterteilung der decision spaces vorliegt)
            d = 1; // dann wird hier die parametrisierung fr die folgende schleife angepasst.
            numDeciders++;
            isMultiDecider = false;
        }

        // In order to save some ram we are going to do this iteratively
        while (d < numDeciders) {
            Instances copy = new Instances(data); // Make a clone of the full dataset

            // Iterate over all instances, classify them and delete all instances 
            // that do not belong to the current decider from the dataset
            Iterator i = copy.iterator();
            try {
                while (i.hasNext()) {
                    weka.core.Instance inst = (weka.core.Instance) i.next();

                    double cls = detector.classifyInstance(inst);
                    if (isMultiDecider) {
                        lastDecider = decider.getLastUsedDecider();
                        if (lastDecider != d) {
                            i.remove();
                        } else {
                            if (cls == 1) {
                                i.remove(); // if the initial classification is correct, we wont bother!!
                            }
                        }
                    } else {
                        if (cls == 1) {
                            i.remove(); // if the initial classification is correct, we wont bother!!
                        }
                    }
                }
            } catch (Exception e) {
                System.err.println("Something went wrong while trying to split into subsets:");
                System.err.println(e.getMessage());
            }

            subsets.add(copy);
            d++;
        }
    }

    return subsets;
}

From source file:moa.tud.ke.patching.Patching.java

/**
 * Classifies an instance by checking if it lies in an error region and then
 * using the respective patch, or just using the base classifier otherwise.
 *
 * @param inst/*from  w  w w  .  ja va  2 s.  com*/
 * @return
 * @throws Exception
 */
public double classifyInstance(weka.core.Instance inst) throws Exception {

    int region = -1;
    int defaultDecider = -1;
    int amountDeciders = -1;
    double label;

    weka.core.Instance origInst = inst;

    try {
        if (this.regionDecider != null) {

            // Handling of optional usage of the base class as an additional attribute.
            if (this.useBaseClassAsAttribute.isSet()) {
                Instances tmp = new Instances(this.prototypeData); // deep copy of our empty prototypeData
                tmp.add(inst);
                tmp = addBaseClassToInstances(tmp);
                weka.core.Instance inst2 = tmp.get(0);
                inst = inst2;
                inst2 = null;
            }

            // Pre-classify instance and retrieve the used Decider
            double regClass = this.regionDecider.classifyInstance(inst);

            if (regClass == 0) { // only if its in a "wrong" region

                Boolean isMultiDecider = false;
                if (this.regionDecider.getAmountOfDeciders() > 1) {
                    isMultiDecider = true;
                }

                Classifier patch;

                if (isMultiDecider) { // a) if the classifier can disciminate different regions
                    region = this.regionDecider.getLastUsedDecider();

                    patch = (Classifier) regionPatches.elementAt(region);
                    if (patch != null) {
                        return patch.classifyInstance(inst);
                    }
                } else { // case b: we only have a 0/1 information about if its in the error region or not.
                    patch = (Classifier) regionPatches.elementAt(0);
                    if (patch != null) {
                        return patch.classifyInstance(inst);
                    }

                }
            } else { // if its not in a "wrong" region, return the class from the base classifier
                if (this.useBaseClassAsAttribute.isSet()) {
                    // this has maybe already been calculated into the first attribute, so we dont need to 
                    // classify this instance again.
                    return inst.value(0);
                }
            }
        }
    } catch (Exception e) {
        System.err.println("AdaptivePatching : Error in classifyInstance while using regionDecider.");
        System.out.println("Region: " + region + " DefaultDecider:" + defaultDecider + " amountDeciders:"
                + amountDeciders + " regionPatches#:" + regionPatches.size());
        e.printStackTrace();
    }

    return baseClassifier.classifyInstance(origInst);
}

From source file:myclassifier.wekaCode.java

public static Instances classifyUnseenData(Classifier classifiers, Instances dataSet) throws Exception {
    Instances labeledData = new Instances(dataSet);
    // labeling data
    for (int i = 0; i < labeledData.numInstances(); i++) {
        double clsLabel = classifiers.classifyInstance(dataSet.instance(i));
        labeledData.instance(i).setClassValue(clsLabel);
    }// w  ww. j a va  2  s.co m
    return labeledData;
}