Example usage for weka.core Instance classValue

List of usage examples for weka.core Instance classValue

Introduction

In this page you can find the example usage for weka.core Instance classValue.

Prototype

public double classValue();

Source Link

Document

Returns an instance's class value as a floating-point number.

Usage

From source file:moa.classifiers.meta.RandomRules.java

License:Open Source License

private Instance transformInstance(Instance inst, int classifierIndex) {
    if (this.listAttributes == null) {
        this.numAttributes = (int) (this.numAttributesPercentageOption.getValue() * inst.numAttributes()
                / 100.0);/*from   ww  w  .j  a  v  a 2  s.co m*/
        this.listAttributes = new int[this.numAttributes][this.ensemble.length];
        this.dataset = new InstancesHeader[this.ensemble.length];
        for (int ensembleIndex = 0; ensembleIndex < this.ensemble.length; ensembleIndex++) {
            for (int attributeIndex = 0; attributeIndex < this.numAttributes; attributeIndex++) {
                boolean isUnique = false;
                while (isUnique == false) {
                    this.listAttributes[attributeIndex][ensembleIndex] = this.classifierRandom
                            .nextInt(inst.numAttributes() - 1);
                    isUnique = true;
                    for (int k = 0; k < attributeIndex; k++) {
                        if (this.listAttributes[attributeIndex][ensembleIndex] == this.listAttributes[k][ensembleIndex]) {
                            isUnique = false;
                            break;
                        }
                    }
                }
                //this.listAttributes[attributeIndex][ensembleIndex] = attributeIndex;
            }
            //Create Header
            FastVector attributes = new FastVector();
            for (int attributeIndex = 0; attributeIndex < this.numAttributes; attributeIndex++) {
                attributes.addElement(inst.attribute(this.listAttributes[attributeIndex][ensembleIndex]));
                System.out.print(this.listAttributes[attributeIndex][ensembleIndex]);
            }
            System.out.println("Number of attributes: " + this.numAttributes + "," + inst.numAttributes());
            attributes.addElement(inst.classAttribute());
            this.dataset[ensembleIndex] = new InstancesHeader(
                    new Instances(getCLICreationString(InstanceStream.class), attributes, 0));
            this.dataset[ensembleIndex].setClassIndex(this.numAttributes);
            this.ensemble[ensembleIndex].setModelContext(this.dataset[ensembleIndex]);
        }
    }
    //Instance instance = new DenseInstance(this.numAttributes+1);
    //instance.setDataset(dataset[classifierIndex]);
    double[] attVals = new double[this.numAttributes + 1];
    for (int attributeIndex = 0; attributeIndex < this.numAttributes; attributeIndex++) {
        //instance.setValue(attributeIndex, inst.value(this.listAttributes[attributeIndex][classifierIndex]));
        attVals[attributeIndex] = inst.value(this.listAttributes[attributeIndex][classifierIndex]);
    }
    Instance instance = new DenseInstance(1.0, attVals);
    instance.setDataset(dataset[classifierIndex]);
    instance.setClassValue(inst.classValue());
    // System.out.println(inst.toString());
    // System.out.println(instance.toString());
    // System.out.println("============");
    return instance;
}

From source file:moa.classifiers.novelClass.AbstractNovelClassClassifier.java

License:Apache License

@Override
public boolean correctlyClassifies(Instance inst) {
    double[] votes = getVotesForInstance(inst);
    int prediction = Utils.maxIndex(votes);
    int groundTruth = (int) inst.classValue();
    boolean isCorrect = (prediction == groundTruth);
    if (!isCorrect && votes.length > inst.numClasses()) { // If it was intially wrong, 
        if (!this.labelsSeen.containsKey(groundTruth) // becuase the we don't know about the true label,
                && (votes.length >= (this.novelLabelIndex - 1)) // but we used a novel class detection classifier,
                && votes[this.novelLabelIndex] > 0) { // and it marked it as a novel label
            isCorrect = true; // Then we can count it as correct
        }//from   ww w  .ja  va 2  s.c o  m
    }
    return isCorrect;
}

From source file:moa.classifiers.Perceptron.java

License:Open Source License

@Override
public void trainOnInstanceImpl(Instance inst) {

    //Init Perceptron
    if (this.reset == true) {
        this.reset = false;
        this.numberAttributes = inst.numAttributes();
        this.numberClasses = inst.numClasses();
        this.weightAttribute = new double[inst.numClasses()][inst.numAttributes()];
        for (int i = 0; i < inst.numClasses(); i++) {
            for (int j = 0; j < inst.numAttributes(); j++) {
                weightAttribute[i][j] = 0.2 * Math.random() - 0.1;
            }//from  w  ww.j av a 2  s.  com
        }
    }

    double[] preds = new double[inst.numClasses()];
    for (int i = 0; i < inst.numClasses(); i++) {
        preds[i] = prediction(inst, i);
    }
    double learningRatio = learningRatioOption.getValue();

    int actualClass = (int) inst.classValue();
    for (int i = 0; i < inst.numClasses(); i++) {
        double actual = (i == actualClass) ? 1.0 : 0.0;
        double delta = (actual - preds[i]) * preds[i] * (1 - preds[i]);
        for (int j = 0; j < inst.numAttributes() - 1; j++) {
            this.weightAttribute[i][j] += learningRatio * delta * inst.value(j);
        }
        this.weightAttribute[i][inst.numAttributes() - 1] += learningRatio * delta;
    }
}

From source file:moa.classifiers.rules.AbstractAMRules.java

License:Apache License

/**
 * getVotesForInstance extension of the instance method getVotesForInstance 
 * in moa.classifier.java/* ww  w.ja  v  a  2 s .c  om*/
 * returns the prediction of the instance.
 * Called in EvaluateModelRegression
 */
@Override
public double[] getVotesForInstance(Instance instance) {
    ErrorWeightedVote errorWeightedVote = newErrorWeightedVote();
    //DoubleVector combinedVote = new DoubleVector();
    debug("Test", 3);
    int numberOfRulesCovering = 0;

    VerboseToConsole(instance); // Verbose to console Dataset name.
    for (Rule rule : ruleSet) {
        if (rule.isCovering(instance) == true) {
            numberOfRulesCovering++;
            //DoubleVector vote = new DoubleVector(rule.getPrediction(instance));
            double[] vote = rule.getPrediction(instance);
            double error = rule.getCurrentError();
            debug("Rule No" + rule.getRuleNumberID() + " Vote: " + Arrays.toString(vote) + " Error: " + error
                    + " Y: " + instance.classValue(), 3); //predictionValueForThisRule);
            errorWeightedVote.addVote(vote, error);
            //combinedVote.addValues(vote);
            if (!this.unorderedRulesOption.isSet()) { // Ordered Rules Option.
                break; // Only one rule cover the instance.
            }
        }
    }

    if (numberOfRulesCovering == 0) {
        //combinedVote = new DoubleVector(defaultRule.getPrediction(instance));
        double[] vote = defaultRule.getPrediction(instance);
        double error = defaultRule.getCurrentError();
        errorWeightedVote.addVote(vote, error);

        debug("Default Rule Vote " + Arrays.toString(vote) + " Error " + error + "  Y: "
                + instance.classValue(), 3);
    }
    double[] weightedVote = errorWeightedVote.computeWeightedVote();
    double weightedError = errorWeightedVote.getWeightedError();

    debug("Weighted Rule - Vote: " + Arrays.toString(weightedVote) + " Weighted Error: " + weightedError + " Y:"
            + instance.classValue(), 3);
    return weightedVote;
}

From source file:moa.classifiers.rules.AMRules.java

License:Apache License

@Override
public double[] getVotesForInstance(Instance inst) {
    double[] votes = new double[1];
    this.numInstTest = this.numInstTest + 1;
    switch (this.predictionFunctionOption.getChosenIndex()) { // Adaptative strategy.
    case 0: {/*from   w  ww  .  j a  v a2s.  co  m*/
        if (this.orderedRulesOption.isSet()) { //Ordered rule.
            if (this.numInstTest > 100) {
                double perceptronPrediction = getVotesOrderedRulesPerceptron(inst);
                double targetMeanPrediction = getVotesOrderedRulesTargetMean(inst);
                double perceptronError = Math.abs(inst.classValue() - perceptronPrediction);
                double targetMeanError = Math.abs(inst.classValue() - targetMeanPrediction);
                if (perceptronError < targetMeanError) {
                    votes[0] = perceptronPrediction;
                } else {
                    votes[0] = targetMeanPrediction;
                }
            } else {
                votes[0] = getVotesOrderedRulesTargetMean(inst);
            }
        } else { //Unordered rule.
            if (this.numInstTest > 100) {
                double perceptronPrediction = getVotesUnorderedRulesPerceptron(inst);
                double targetMeanPrediction = getVotesUnorderedRulesTargetMean(inst);
                double perceptronError = Math.abs(inst.classValue() - perceptronPrediction);
                double targetMeanError = Math.abs(inst.classValue() - targetMeanPrediction);
                if (perceptronError < targetMeanError) {
                    votes[0] = perceptronPrediction;
                } else {
                    votes[0] = targetMeanPrediction;
                }
            } else {
                votes[0] = getVotesUnorderedRulesTargetMean(inst);
            }
        }
        break;
    }
    case 1: // Perceptron strategy.
    {
        if (this.orderedRulesOption.isSet()) { //Ordered rule.
            if (this.numInstTest > 100) {
                votes[0] = getVotesOrderedRulesPerceptron(inst);
            } else {
                votes[0] = getVotesOrderedRulesTargetMean(inst);
            }
        } else { //Unordered rule.
            if (this.numInstTest > 100) {
                votes[0] = getVotesUnorderedRulesPerceptron(inst);
            } else {
                votes[0] = getVotesUnorderedRulesTargetMean(inst);
            }
        }
        break;
    }
    case 2: // Target mean strategy.
    {
        if (this.orderedRulesOption.isSet()) {
            votes[0] = getVotesOrderedRulesTargetMean(inst);
        } else {
            votes[0] = getVotesUnorderedRulesTargetMean(inst);
        }
        break;
    }
    }
    return votes;
}

From source file:moa.classifiers.rules.AMRules.java

License:Apache License

@Override
public void trainOnInstanceImpl(Instance inst) {
    this.numInstance = this.numInstance + 1;
    int countRuleFiredTrue = 0;
    boolean ruleFired = false;
    this.instance = inst;
    for (int j = 0; j < this.ruleSet.size(); j++) {
        if (this.ruleSet.get(j).ruleEvaluate(inst) == true) {
            countRuleFiredTrue = countRuleFiredTrue + 1;
            this.saveBestValGlobalSDR = new ArrayList<ArrayList<Double>>();
            this.saveBestGlobalSDR = new DoubleVector();
            this.saveTheBest = new ArrayList<Double>();
            double anomaly = computeAnomaly(this.ruleSet.get(j), j, inst); // compute anomaly
            if ((this.ruleSet.get(j).instancesSeen <= this.anomalyNumInstThresholdOption.getValue())
                    || (anomaly < this.anomalyProbabilityThresholdOption.getValue()
                            && this.anomalyDetectionOption.isSet())
                    || !this.anomalyDetectionOption.isSet()) {
                for (int i = 0; i < inst.numAttributes() - 1; i++) {
                    int instAttIndex = modelAttIndexToInstanceAttIndex(i, inst);
                    AttributeClassObserver obs = this.ruleSet.get(j).observers.get(i);
                    if (obs == null) {
                        obs = inst.attribute(instAttIndex).isNominal() ? newNominalClassObserver()
                                : newNumericClassObserverRegression();
                        this.ruleSet.get(j).observers.set(i, obs);
                    }/*  ww  w  .j av  a  2 s.  c o  m*/
                    obs.observeAttributeTarget(inst.value(instAttIndex), inst.classValue());
                }

                double RuleError = computeRuleError(inst, this.ruleSet.get(j), j); // compute rule error
                boolean ph = PageHinckleyTest(RuleError, this.pageHinckleyThresholdOption.getValue(),
                        this.ruleSet.get(j));
                if (ph == true) { //Page Hinckley test.
                    //Pruning rule set.
                    //   System.out.print("Pruning rule set \n");
                    this.ruleSet.remove(j);
                    this.targetValue.remove(j);
                    this.numTargetValue.remove(j);
                    this.ruleTargetMean.remove(j);
                } else {
                    this.expandeRule(this.ruleSet.get(j), j, inst); //Expand the rule.
                }
            }
            if (this.orderedRulesOption.isSet()) { // Ordered rules
                break;
            }
        }
    }
    if (countRuleFiredTrue > 0) {
        ruleFired = true;
    } else {
        ruleFired = false;
    }
    if (ruleFired == false) { //Default rule
        this.saveBestValGlobalSDR = new ArrayList<ArrayList<Double>>();
        this.saveBestGlobalSDR = new DoubleVector();
        this.saveTheBest = new ArrayList<Double>();
        double anomalies = computeAnomalyDefaultRules(inst);
        if ((instancesSeenDefault <= this.anomalyNumInstThresholdOption.getValue())
                || (anomalies < this.anomalyProbabilityThresholdOption.getValue()
                        && this.anomalyDetectionOption.isSet())
                || !this.anomalyDetectionOption.isSet()) {
            for (int i = 0; i < inst.numAttributes() - 1; i++) {
                int instAttIndex = modelAttIndexToInstanceAttIndex(i, inst);
                AttributeClassObserver obs = this.attributeObservers.get(i);
                if (obs == null) {
                    obs = inst.attribute(instAttIndex).isNominal() ? newNominalClassObserver()
                            : newNumericClassObserverRegression();
                    this.attributeObservers.set(i, obs);
                }
                obs.observeAttributeTarget(inst.value(instAttIndex), inst.classValue());
            }
            initialyPerceptron(inst); // Initialize Perceptron if necessary.  
            this.updateAttWeight(inst, this.weightAttributeDefault, this.squaredActualClassStatisticsDefault,
                    this.actualClassStatisticsDefault, this.squaredAttributeStatisticsDefault,
                    this.attributeStatisticsDefault, this.instancesSeenDefault, resetDefault); // Update weights. Ensure actual class and the predicted class are normalised first.
            this.updatedefaultRuleStatistics(inst); //Update the default rule statistics.
            this.createRule(inst);//This function creates a rule
        }
    }
}

From source file:moa.classifiers.rules.AMRules.java

License:Apache License

public double updateAttWeight(Instance inst, double[] weightAtt, double squaredActualClassStatistics,
        double actualClassStatistics, DoubleVector squaredAttributeStatistics, DoubleVector attributeStatistics,
        int instancesSeen, boolean reset) {
    double learningRatio = 0.0;
    if (this.learningRatio_Decay_or_Const_Option.isSet()) { //Decaying learning rate option
        learningRatio = this.learningRatioOption.getValue();
    } else {/*from w ww  .  ja  v  a 2  s .c om*/
        learningRatio = initLearnRate / (1 + instancesSeen * this.learnRateDecay);
    }

    double predict = 0.0;
    if (instancesSeen > 30) {
        predict = this.prediction(inst, weightAtt, squaredActualClassStatistics, actualClassStatistics,
                instancesSeen, reset);
        double sdClass = computeSD(squaredActualClassStatistics, actualClassStatistics, instancesSeen);
        double actualClass = 0.0;
        double predictedClass = 0.0;
        if (sdClass > 0.0000001) {
            actualClass = (inst.classValue() - (actualClassStatistics / instancesSeen)) / (3 * sdClass);
            predictedClass = (predict - (actualClassStatistics / instancesSeen)) / (3 * sdClass);
        }
        double delta = actualClass - predictedClass;
        for (int x = 0; x < inst.numAttributes() - 1; x++) {
            if (inst.attribute(x).isNumeric()) {
                // Update weights. Ensure attribute values are normalised first.
                double sd = Math.sqrt((squaredAttributeStatistics.getValue(x)
                        - ((attributeStatistics.getValue(x) * attributeStatistics.getValue(x)) / instancesSeen))
                        / instancesSeen);
                double instanceValue = 0;
                instanceValue = (inst.value(x) - (attributeStatistics.getValue(x) / instancesSeen));
                if (sd > 0.0000001) {
                    instanceValue = instanceValue / (3 * sd);
                }
                if (sd == 0.0) {
                    weightAtt[x] = 0.0;
                } else {
                    weightAtt[x] += learningRatio * delta * instanceValue;
                }
            }
        }
        weightAtt[inst.numAttributes() - 1] += learningRatio * delta;
    }
    return predict;
}

From source file:moa.classifiers.rules.AMRules.java

License:Apache License

public double[] getPredictionActualValueNormalized(Instance inst, Rule rl, int ruleIndex, double predict) {
    double[] values = new double[2];
    double predictVal = 0.0;
    double classActual = 0.0;
    double sd = computeSD(rl.squaredActualClassStatistics, rl.actualClassStatistics, rl.instancesSeen);
    if (this.predictionFunctionOption.getChosenIndex() == 2) { //Target mean strategy

        predictVal = (this.ruleTargetMean.get(ruleIndex) - (rl.actualClassStatistics / rl.instancesSeen))
                / (3 * sd);/*from w  w w  . j av a 2 s .c o m*/
        classActual = (inst.classValue() - (rl.actualClassStatistics / rl.instancesSeen)) / (3 * sd);
    } else if (this.predictionFunctionOption.getChosenIndex() == 1) { //Perceptron strategy
        if (rl.instancesSeen <= 30) {
            if (sd > 0.0000001) {
                predictVal = (ruleTargetMean.get(ruleIndex) - (rl.actualClassStatistics / rl.instancesSeen))
                        / (3 * sd); //Predicted value normalized.
                classActual = (inst.classValue() - (rl.actualClassStatistics / rl.instancesSeen)) / (3 * sd); //Class value normalized.
            }
        } else {
            if (sd > 0.0000001) {
                predictVal = (predict - (rl.actualClassStatistics / rl.instancesSeen)) / (3 * sd); //Predicted value normalized.
                classActual = (inst.classValue() - (rl.actualClassStatistics / rl.instancesSeen)) / (3 * sd); //Class value normalized.
            }
        }
    } else { //Adaptative strategy.
        double predictValTargetMean = 0;
        double predictValPerceptron = 0;
        if (sd > 0.0000001) {
            predictValTargetMean = (this.ruleTargetMean.get(ruleIndex)
                    - (rl.actualClassStatistics / rl.instancesSeen)) / (3 * sd);
            predictValPerceptron = (predict - (rl.actualClassStatistics / rl.instancesSeen)) / (3 * sd);
            classActual = (inst.classValue() - (rl.actualClassStatistics / rl.instancesSeen)) / (3 * sd);
        }
        double absolutErrorTargetMean = Math.abs(classActual - predictValTargetMean); //Target mean strategy absolute error.
        double absolutErrorPerceptron = Math.abs(classActual - predictValPerceptron); //Perceptron strategy absolute error.
        if (absolutErrorTargetMean < absolutErrorPerceptron) {
            predictVal = predictValTargetMean;
        } else {
            predictVal = predictValPerceptron;
        }
    }
    values[0] = predictVal;
    values[1] = classActual;

    return values;
}

From source file:moa.classifiers.rules.AMRules.java

License:Apache License

public void updateRuleStatistics(Instance inst, Rule rl, int ruleIndex) {
    rl.instancesSeen++;/* www.  j  a  va 2  s.c o  m*/
    double targetValueSize = this.numTargetValue.get(ruleIndex) + 1.0;
    double targetVal = this.targetValue.get(ruleIndex) + inst.classValue();
    this.targetValue.set(ruleIndex, targetVal);
    this.numTargetValue.set(ruleIndex, targetValueSize);
    setRuleTarget(this.targetValue.get(ruleIndex), this.numTargetValue.get(ruleIndex), ruleIndex);
    rl.ValorTargetRule = this.ruleTargetMean.get(ruleIndex);
    for (int s = 0; s < inst.numAttributes() - 1; s++) {
        rl.attributeStatistics.addToValue(s, inst.value(s));
        rl.squaredAttributeStatistics.addToValue(s, inst.value(s) * inst.value(s));
    }
    rl.actualClassStatistics += inst.classValue();
    rl.squaredActualClassStatistics += inst.classValue() * inst.classValue();
}

From source file:moa.classifiers.rules.AMRules.java

License:Apache License

protected void ruleTargetData(Instance inst, int ruleIndex) {
    double target = this.targetValue.get(ruleIndex) + inst.classValue();
    double targetCount = this.numTargetValue.get(ruleIndex) + 1;
    this.targetValue.set(ruleIndex, target);
    this.numTargetValue.set(ruleIndex, targetCount);
}