Example usage for weka.core Instance numClasses

List of usage examples for weka.core Instance numClasses

Introduction

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

Prototype

public int numClasses();

Source Link

Document

Returns the number of class labels.

Usage

From source file:machinelearningproject.RandomForest.java

@Override
public double classifyInstance(Instance instance) throws Exception {
    HashMap<String, Integer> classMap = new HashMap<>();

    for (int i = 0; i < dtrees.size(); i++) {
        String key = dtrees.get(i).traverseTree(instance);
        if (classMap.isEmpty() || !classMap.containsKey(key)) {
            classMap.put(key, 1);/*www .  j  a  va 2  s.c o m*/
        } else {
            if (classMap.containsKey(key)) {
                classMap.put(key, classMap.get(key) + 1);
            }
        }
    }
    Iterator<String> keySetIterator = classMap.keySet().iterator();
    String modeClass = "";
    int count = 0;
    while (keySetIterator.hasNext()) {
        String key = keySetIterator.next();
        if (count < classMap.get(key)) {
            modeClass = key;
            count = classMap.get(key);
        }
    }

    double result = 0.0;
    for (int i = 0; i < instance.numClasses(); i++) {
        if (modeClass.equals(instance.attribute(instance.classIndex()).value(i))) {
            result = (double) i;
        }
    }

    return result;
}

From source file:ml.ann.BackPropagation.java

License:Open Source License

private void initInputAndTarget(Instance instance) {
    int classAttributeIdx = neuronTopology.instances.classIndex();
    if (neuronTopology.instances.classAttribute().isNumeric()) {
        neuronTopology.target = new double[1];
        neuronTopology.target[0] = instance.value(classAttributeIdx);
    } else if (neuronTopology.instances.classAttribute().isNominal()) {
        neuronTopology.target = new double[instance.numClasses()];
        for (int i = 0; i < instance.numClasses(); i++) {
            neuronTopology.target[i] = 0;
        }/*from  www.j  av  a2 s  .  co m*/
        int idxClassValue = (int) instance.classValue();
        neuronTopology.target[idxClassValue] = 1;
    }
    for (int i = 0; i < instance.numAttributes(); i++) {
        if (i == 0) {
            neuronTopology.input[i] = 1;
            neuronTopology.output[0][i] = 1;
        } else {
            neuronTopology.input[i] = instance.value(i - 1);
            neuronTopology.output[0][i] = instance.value(i - 1);
        }
    }
    //        System.out.println(neuronTopology.originInstances.instance(instancesIdx).toString());
}

From source file:ml.engine.LibSVM.java

License:Open Source License

/**
 * Computes the distribution for a given instance. In case of 1-class
 * classification, 1 is returned at index 0 if libsvm returns 1 and NaN (=
 * missing) if libsvm returns -1./*  ww w .  j a  v a 2  s .c  o  m*/
 * 
 * @param instance the instance for which distribution is computed
 * @return the distribution
 * @throws Exception if the distribution can't be computed successfully
 */
@Override
public double[] distributionForInstance(Instance instance) throws Exception {
    int[] labels = new int[instance.numClasses()];
    double[] prob_estimates = null;

    if (m_ProbabilityEstimates) {
        invokeMethod(Class.forName(CLASS_SVM).newInstance(), "svm_get_labels",
                new Class[] { Class.forName(CLASS_SVMMODEL),
                        Array.newInstance(Integer.TYPE, instance.numClasses()).getClass() },
                new Object[] { m_Model, labels });

        prob_estimates = new double[instance.numClasses()];
    }

    if (!getDoNotReplaceMissingValues()) {
        m_ReplaceMissingValues.input(instance);
        m_ReplaceMissingValues.batchFinished();
        instance = m_ReplaceMissingValues.output();
    }

    if (m_Filter != null) {
        m_Filter.input(instance);
        m_Filter.batchFinished();
        instance = m_Filter.output();
    }

    m_NominalToBinary.input(instance);
    m_NominalToBinary.batchFinished();
    instance = m_NominalToBinary.output();

    Object x = instanceToArray(instance);
    double v;
    double[] result = new double[instance.numClasses()];
    if (m_ProbabilityEstimates && ((m_SVMType == SVMTYPE_C_SVC) || (m_SVMType == SVMTYPE_NU_SVC))) {
        v = ((Double) invokeMethod(Class.forName(CLASS_SVM).newInstance(), "svm_predict_probability",
                new Class[] { Class.forName(CLASS_SVMMODEL),
                        Array.newInstance(Class.forName(CLASS_SVMNODE), Array.getLength(x)).getClass(),
                        Array.newInstance(Double.TYPE, prob_estimates.length).getClass() },
                new Object[] { m_Model, x, prob_estimates })).doubleValue();

        // Return order of probabilities to canonical weka attribute order
        for (int k = 0; k < prob_estimates.length; k++) {
            result[labels[k]] = prob_estimates[k];
        }
    } else {
        v = ((Double) invokeMethod(Class.forName(CLASS_SVM).newInstance(), "svm_predict",
                new Class[] { Class.forName(CLASS_SVMMODEL),
                        Array.newInstance(Class.forName(CLASS_SVMNODE), Array.getLength(x)).getClass() },
                new Object[] { m_Model, x })).doubleValue();

        if (instance.classAttribute().isNominal()) {
            if (m_SVMType == SVMTYPE_ONE_CLASS_SVM) {
                if (v > 0) {
                    result[0] = 1;
                } else {
                    // outlier (interface for Classifier specifies that unclassified
                    // instances
                    // should return a distribution of all zeros)
                    result[0] = 0;
                }
            } else {
                result[(int) v] = 1;
            }
        } else {
            result[0] = v;
        }
    }

    return result;
}

From source file:moa.classifiers.active.ActiveClassifier.java

License:Open Source License

private void labelSelSampling(double incomingPosterior, Instance inst) {
    double p = Math.abs(incomingPosterior - 1.0 / (inst.numClasses()));
    double budget = this.budgetOption.getValue() / (this.budgetOption.getValue() + p);
    if (this.classifierRandom.nextDouble() < budget) {
        this.classifier.trainOnInstance(inst);
        this.costLabeling++;
    }// ww  w. ja v a  2s . c om
}

From source file:moa.classifiers.bayes.NaiveBayesMultinomial.java

License:Open Source License

/**
 * Trains the classifier with the given instance.
 *
 * @param instance the new training instance to include in the model
 *///  w ww. jav a 2s . c  o m
@Override
public void trainOnInstanceImpl(Instance inst) {
    if (this.reset == true) {
        this.m_numClasses = inst.numClasses();
        double laplace = this.laplaceCorrectionOption.getValue();
        int numAttributes = inst.numAttributes();

        m_probOfClass = new double[m_numClasses];
        Arrays.fill(m_probOfClass, laplace);

        m_classTotals = new double[m_numClasses];
        Arrays.fill(m_classTotals, laplace * numAttributes);

        m_wordTotalForClass = new DoubleVector[m_numClasses];
        for (int i = 0; i < m_numClasses; i++) {
            //Arrays.fill(wordTotal, laplace);
            m_wordTotalForClass[i] = new DoubleVector();
        }
        this.reset = false;
    }
    // Update classifier
    int classIndex = inst.classIndex();
    int classValue = (int) inst.value(classIndex);

    double w = inst.weight();
    m_probOfClass[classValue] += w;

    m_classTotals[classValue] += w * totalSize(inst);
    double total = m_classTotals[classValue];

    for (int i = 0; i < inst.numValues(); i++) {
        int index = inst.index(i);
        if (index != classIndex && !inst.isMissing(i)) {
            //m_wordTotalForClass[index][classValue] += w * inst.valueSparse(i);
            double laplaceCorrection = 0.0;
            if (m_wordTotalForClass[classValue].getValue(index) == 0) {
                laplaceCorrection = this.laplaceCorrectionOption.getValue();
            }
            m_wordTotalForClass[classValue].addToValue(index, w * inst.valueSparse(i) + laplaceCorrection);
        }
    }
}

From source file:moa.classifiers.functions.AbsurdOracleClassifier.java

License:Apache License

@Override
public double[] getVotesForInstance(Instance i) {
    DoubleVector observedClassDistribution = new DoubleVector();
    if (this.randNumGen.nextFloat() < this.desiredAccuracyOption.getValue()) {
        observedClassDistribution.addToValue((int) i.classValue(), i.weight());
    } else {//from   w w w .jav  a 2 s.c om
        observedClassDistribution.addToValue(((int) i.classValue() + 1) % i.numClasses(), i.weight());

    }
    return observedClassDistribution.getArrayCopy();
}

From source file:moa.classifiers.functions.NoChange.java

License:Open Source License

public double[] getVotesForInstance(Instance i) {
    double[] votes = new double[i.numClasses()];
    votes[(int) lastSeenClass] = 1.0;
    return votes;
}

From source file:moa.classifiers.functions.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 * this.classifierRandom.nextDouble() - 0.1;
            }// ww w  .  ja  va2s.c  o m
        }
    }

    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.functions.RandomGuess.java

License:Apache License

@Override
public double[] getVotesForInstance(Instance i) {
    DoubleVector observedClassDistribution = new DoubleVector();
    int classToGuess = this.randNumGen.nextInt(i.numClasses());
    //double weightToGuess = this.randNumGen.nextDouble();
    observedClassDistribution.addToValue(classToGuess, i.weight());
    return observedClassDistribution.getArrayCopy();
}

From source file:moa.classifiers.functions.SGD.java

License:Open Source License

/**
 * Calculates the class membership probabilities for the given test
 * instance.//from  ww w .  j a  v  a  2 s . co m
 *
 * @param instance    the instance to be classified
 * @return       predicted class probability distribution
 */
@Override
public double[] getVotesForInstance(Instance inst) {

    if (m_weights == null) {
        return new double[inst.numClasses()];
    }
    double[] result = (inst.classAttribute().isNominal()) ? new double[2] : new double[1];

    double wx = dotProd(inst, m_weights, inst.classIndex());// * m_wScale;
    double z = (wx + m_bias);

    if (inst.classAttribute().isNumeric()) {
        result[0] = z;
        return result;
    }

    if (z <= 0) {
        //  z = 0;
        if (m_loss == LOGLOSS) {
            result[0] = 1.0 / (1.0 + Math.exp(z));
            result[1] = 1.0 - result[0];
        } else {
            result[0] = 1;
        }
    } else {
        if (m_loss == LOGLOSS) {
            result[1] = 1.0 / (1.0 + Math.exp(-z));
            result[0] = 1.0 - result[1];
        } else {
            result[1] = 1;
        }
    }
    return result;
}