Example usage for weka.core Instance classIndex

List of usage examples for weka.core Instance classIndex

Introduction

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

Prototype

public int classIndex();

Source Link

Document

Returns the class attribute's index.

Usage

From source file:edu.oregonstate.eecs.mcplan.ml.Memorizer.java

License:Open Source License

/**
 * 'instance' must be labeled with the class label in the same position
 * as in the training instances./*  w  ww.  j av a  2s  .c o m*/
 * 
 * @see weka.classifiers.Classifier#classifyInstance(weka.core.Instance)
 */
@Override
public double classifyInstance(final Instance instance) throws Exception {
    assert (instance.classIndex() == class_idx_);
    final double[] x = instance.toDoubleArray();
    x[class_idx_] = 0;
    return m_.get(new ArrayHolder(x));
}

From source file:edu.umbc.cs.maple.utils.WekaUtils.java

License:Open Source License

/**
 * Converts an instance to a feature vector excluding the class attribute.
 * @param instance The instance./* www  .jav a2 s .c o  m*/
 * @return A vector representation of the instance excluding the class attribute
 */
public static double[] instanceToDoubleArray(Instance instance) {
    double[] vector = new double[(instance.classIndex() != -1) ? instance.numAttributes() - 1
            : instance.numAttributes()];
    double[] instanceDoubleArray = instance.toDoubleArray();
    int attIdx = 0;
    for (int i = 0; i < vector.length; i++) {
        if (i == instance.classIndex()) {
            attIdx++;
        }
        vector[i] = instanceDoubleArray[attIdx++];
    }
    return vector;
}

From source file:edu.umbc.cs.maple.utils.WekaUtils.java

License:Open Source License

/** Converts a set of instances to svm-light format
 * @param data the weka instances//from  w ww  .j  a va 2  s. c  o  m
 * @return the weka instances in svm-light format
 */
public static String arffToSVMLight(Instance data, SVMLightLabelFormat labelFormat) {

    if (labelFormat == SVMLightLabelFormat.CLASSIFICATION && data.numClasses() != 2) {
        throw new IllegalArgumentException(
                "SVM-light classification label format requires that the data contain only two classes.");
    }

    String str = "";
    String endline = System.getProperty("line.separator");

    int numAttributes = data.numAttributes();
    int classAttIdx = data.classIndex();

    // convert the instance label
    if (labelFormat == SVMLightLabelFormat.CLASSIFICATION) {
        str += (data.classValue() == 0) ? "-1" : "1";
    } else {
        str += data.classValue();
    }

    str += " ";

    // convert each feature
    for (int attIdx = 0; attIdx < numAttributes; attIdx++) {
        // skip the class attribute
        if (attIdx == classAttIdx)
            continue;
        str += (attIdx + 1) + ":" + data.value(attIdx) + " ";
    }

    // append the instance info string
    str += "#";

    str += endline;

    return str;
}

From source file:elh.eus.absa.WekaWrapper.java

License:Open Source License

/**
 *   Simple function to print the results of a multilabel prediction.
 * /*  w  ww . j  a  va2  s .  co  m*/
 * @param HashMap<Instance, double[]> pred hashmap containing a set of instances and their corresponding
 *         multilabel prediction, as computed by the multiLabelPrediction() function in this class.
 */
public void printMultilabelPredictions(HashMap<Instance, double[]> pred) {
    for (Instance i : pred.keySet()) {
        double[] kk = pred.get(i);
        int c = 0;
        System.out.print("instance " + Integer.parseInt(Double.toString(i.value(0))) + " (" + i.classValue()
                + "|" + i.stringValue(i.classIndex()) + ") --> ");
        for (double d : kk) {
            System.out.print("cl_" + c + "=" + d + "; ");
            c++;
        }
        System.out.print("\n");
    }

}

From source file:fantail.core.Tools.java

License:Open Source License

public static int getNumberTargets(Instance inst) throws Exception {
    if (inst == null) {
        throw new Exception("inst can't be null.");
    }// w ww . j  a  v  a 2 s  .  c o m
    Instances targets = inst.relationalValue(inst.classIndex());
    return targets.numAttributes();
}

From source file:fantail.core.Tools.java

License:Open Source License

public static double[] getTargetVector(Instance inst) {
    Instances targetBag = inst.relationalValue(inst.classIndex());
    double[] values = new double[targetBag.numAttributes()];
    for (int i = 0; i < values.length; i++) {
        values[i] = targetBag.instance(0).value(i);
    }/*from   ww w .ja  va  2 s . com*/
    return values;
}

From source file:fantail.core.Tools.java

License:Open Source License

public static String[] getTargetNames(Instance inst) {
    Instances targetBag = inst.relationalValue(inst.classIndex());
    String[] names = new String[targetBag.numAttributes()];
    for (int i = 0; i < names.length; i++) {
        names[i] = targetBag.attribute(i).name();
    }/*from   ww  w.j a  va  2s . c  o  m*/
    return names;
}

From source file:fantail.core.Tools.java

License:Open Source License

public static ReasonerComponent[] getTargetObjects(Instance inst) {

    Instances targetBag = inst.relationalValue(inst.classIndex());
    String[] names = new String[targetBag.numAttributes()];
    ReasonerComponent res[] = new ReasonerComponent[names.length];

    for (int i = 0; i < names.length; i++) {
        ReasonerComponent cl = new ReasonerComponent(i, targetBag.instance(0).value(i));
        res[i] = cl;/*  ww w . j ava2s .c  o m*/
    }
    return res;
}

From source file:faster_pca.faster_pca.java

License:Open Source License

/**
* Transform an instance in original (unormalized) format.
* 
* @param instance an instance in the original (unormalized) format
* @return a transformed instance//from w ww  .j  a va 2 s .  co m
* @throws Exception if instance can't be transformed
*/
protected Instance convertInstance(Instance instance) throws Exception {
    Instance result;
    double[] newVals;
    Instance tempInst;
    double cumulative;
    int i;
    int j;
    double tempval;
    int numAttsLowerBound;

    newVals = new double[m_OutputNumAtts];
    tempInst = (Instance) instance.copy();

    /*m_ReplaceMissingFilter.input(tempInst);
    m_ReplaceMissingFilter.batchFinished();
    tempInst = m_ReplaceMissingFilter.output();*/

    m_NominalToBinaryFilter.input(tempInst);
    m_NominalToBinaryFilter.batchFinished();
    tempInst = m_NominalToBinaryFilter.output();

    if (m_AttributeFilter != null) {
        m_AttributeFilter.input(tempInst);
        m_AttributeFilter.batchFinished();
        tempInst = m_AttributeFilter.output();
    }

    if (!super.getCenterData()) {

        tempInst = f_norm.filter(tempInst);
    } else {

        tempInst = f_center.filter(tempInst);
    }

    if (m_HasClass) {
        newVals[m_OutputNumAtts - 1] = instance.value(instance.classIndex());
    }

    if (m_MaxAttributes > 0) {
        numAttsLowerBound = m_NumAttribs - m_MaxAttributes;
    } else {
        numAttsLowerBound = 0;
    }
    if (numAttsLowerBound < 0) {
        numAttsLowerBound = 0;
    }

    double tempInstCpy[] = new double[m_NumAttribs];
    for (j = 0; j < m_NumAttribs; j++) {
        tempInstCpy[j] = tempInst.value(j);
    }

    cumulative = 0;
    for (i = m_NumAttribs - 1; i >= numAttsLowerBound; i--) {
        tempval = 0.0;
        for (j = 0; j < m_NumAttribs; j++) {
            tempval += m_Eigenvectors[j][m_SortedEigens[i]] * tempInstCpy[j];
        }

        newVals[m_NumAttribs - i - 1] = tempval;
        cumulative += m_Eigenvalues[m_SortedEigens[i]];
        if ((cumulative / m_SumOfEigenValues) >= m_CoverVariance) {
            break;
        }
    }

    // create instance
    if (instance instanceof SparseInstance) {
        result = new SparseInstance(instance.weight(), newVals);
    } else {
        result = new DenseInstance(instance.weight(), newVals);
    }

    return result;
}

From source file:GClass.EvaluationInternal.java

License:Open Source License

/**
 * Prints the predictions for the given dataset into a String variable.
 *///from   w  w  w.ja  v  a 2s  .  c  o  m
protected static String printClassifications(Classifier classifier, Instances train, String testFileName,
        int classIndex, Range attributesToOutput) throws Exception {

    StringBuffer text = new StringBuffer();
    if (testFileName.length() != 0) {
        BufferedReader testReader = null;
        try {
            testReader = new BufferedReader(new FileReader(testFileName));
        } catch (Exception e) {
            throw new Exception("Can't open file " + e.getMessage() + '.');
        }
        Instances test = new Instances(testReader, 1);
        if (classIndex != -1) {
            test.setClassIndex(classIndex - 1);
        } else {
            test.setClassIndex(test.numAttributes() - 1);
        }
        int i = 0;
        while (test.readInstance(testReader)) {
            Instance instance = test.instance(0);
            Instance withMissing = (Instance) instance.copy();
            withMissing.setDataset(test);
            double predValue = ((Classifier) classifier).classifyInstance(withMissing);
            if (test.classAttribute().isNumeric()) {
                if (Instance.isMissingValue(predValue)) {
                    text.append(i + " missing ");
                } else {
                    text.append(i + " " + predValue + " ");
                }
                if (instance.classIsMissing()) {
                    text.append("missing");
                } else {
                    text.append(instance.classValue());
                }
                text.append(" " + attributeValuesString(withMissing, attributesToOutput) + "\n");
            } else {
                if (Instance.isMissingValue(predValue)) {
                    text.append(i + " missing ");
                } else {
                    text.append(i + " " + test.classAttribute().value((int) predValue) + " ");
                }
                if (Instance.isMissingValue(predValue)) {
                    text.append("missing ");
                } else {
                    text.append(classifier.distributionForInstance(withMissing)[(int) predValue] + " ");
                }
                text.append(instance.toString(instance.classIndex()) + " "
                        + attributeValuesString(withMissing, attributesToOutput) + "\n");
            }
            test.delete(0);
            i++;
        }
        testReader.close();
    }
    return text.toString();
}