Example usage for weka.core Instance value

List of usage examples for weka.core Instance value

Introduction

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

Prototype

public double value(Attribute att);

Source Link

Document

Returns an instance's attribute value in internal format.

Usage

From source file:id3classifier.ID3Classifiers.java

private Map<Instance, Double> valuesByAttribute(List<Instance> instances, Attribute attribute) {

    HashMap<Instance, Double> map = new HashMap<>();

    for (Instance instance : instances) {

        if (!Double.isNaN(instance.value(attribute))) {

            map.put(instance, instance.value(attribute));
        }//from ww w  . ja  va  2  s. co m
    }

    return map;
}

From source file:id3classifier.ID3Classifiers.java

public double getClassification(Instance instance, Leaf node) {

    // set the maxCounts and max values
    int maxCount = -1;
    double maxValue = 0;

    // if the node is indeed a leaf...
    if (node.isLeaf()) {

        // go ahead are return the node's (leaf) value
        return node.getLeafValue();
    } else {//from  ww  w  . j  a  v a  2 s.co  m

        // else... create a new attribute from node's attribute
        Attribute attribute = node.getAttribute();

        // if this attribute is a number
        if (!Double.isNaN(instance.value(attribute))) {

            // set a new double called val equal to the value of instance's
            // node's attribute's value... mouthful
            Double val = instance.value(node.getAttribute());

            // if this is not a number... set val equal to zero
            if (Double.isNaN(val)) {

                val = 0.0;
            }

            // is if node's attribute is not nominal... and if val is < 0.5
            if (!node.getAttribute().isNominal()) {

                if (val < 0.5) {

                    // set that val to 0
                    val = 0.0;
                } else {

                    // if that val was >= to 0.5... reset it to 1
                    val = 1.0;
                }
            }

            // overright child with node's value
            Leaf child = node.get(val);

            // if child is now null... retunr the classification based on k
            // nearest neighbors
            if (child == null) {

                return KNNClassifier.getClassification(node.getInstances());
            } else {

                // else return the classification based on getClassificaion
                // using instance and node's value
                return getClassification(instance, node.get(val));
            }
        } else {

            // else if the attribute is not a number... create a new map of 
            // type double and integer to hold the class counts
            Map<Double, Integer> classToCount = new HashMap<>();

            // for each child of node
            for (Leaf child : node.getChildren()) {

                // get the value of the classification using instance and child
                Double value = getClassification(instance, child);

                // if classes to count does not contain the key matching value,
                // and if classes to count's value is not null put the value in
                // to classes to count at location matching it's value + 1
                if (!classToCount.containsKey(value) && classToCount.get(value) != null) {

                    classToCount.put(value, classToCount.get(value) + 1);
                } else {

                    // else just put value in the slot "1" of classes to count
                    classToCount.put(value, 1);
                }
            }

            // for each double value in classes to counts set of keys... IF
            // classes to count's current key is greater than the max count,
            // and set the max value equal to the current double value
            for (Double doubVal : classToCount.keySet()) {

                if (classToCount.get(doubVal) > maxCount) {

                    maxCount = classToCount.get(doubVal);
                    maxValue = doubVal;
                }
            }

            return maxValue;
        }
    }
}

From source file:imba.classifier.FFNNTubes.java

private void feedForward(Instance instance) {
    input = new double[nAttribute + 1];
    input[0] = 1.0;/* w ww .  j  av a 2 s  .c om*/
    for (int i = 1; i <= nAttribute; i++) {
        input[i] = (double) instance.value(i - 1);
    }
    if (nHidden == 0) {
        output = new double[nOutput];
        for (int i = 0; i < nOutput; i++) {
            output[i] = 0.0;
            double sum = 0.0;
            for (int j = 0; j <= nAttribute; j++) {
                sum = sum + (Weight1[i][j] * input[j]);
            }
            output[i] = activationFunction(sum);
        }
    } else {
        hidden = new double[nNeuron + 1];
        output = new double[nOutput];
        for (int i = 0; i <= nNeuron; i++) {
            hidden[i] = 0.0;
            double sum = 0.0;
            for (int j = 0; j <= nAttribute; j++) {
                sum = sum + (Weight1[i][j] * input[j]);
            }
            hidden[i] = activationFunction(sum);
        }

        for (int i = 0; i < nOutput; i++) {
            output[i] = 0.0;
            double sum = 0.0;
            for (int j = 0; j <= nNeuron; j++) {
                sum = sum + (Weight2[i][j] * hidden[j]);
            }
            output[i] = activationFunction(sum);
        }
    }
}

From source file:iris.ID3.java

private Instances[] makeBins(Instances instances, Attribute att) {
    // Create array of bins based on numValues in Attribute parameter
    Instances[] bins = new Instances[att.numValues()];

    for (int i = 0; i < att.numValues(); i++) {
        bins[i] = new Instances(instances, instances.numInstances());
    }/*from   www. ja va 2  s . co  m*/

    // Create pointer to first instance
    Enumeration instanceEnum = instances.enumerateInstances();

    while (instanceEnum.hasMoreElements()) {
        // Create new instance from the one pointer is pointing at
        Instance oneInstance = (Instance) instanceEnum.nextElement();
        // Add instance to the proper bin
        bins[(int) oneInstance.value(att)].add(oneInstance);
    }

    // Compactify
    for (int i = 0; i < bins.length; i++) {
        bins[i].compactify();
    }
    return bins;
}

From source file:iris.ID3.java

public double classifyInstance(Instance instance) throws Exception {
    // Assign class value
    if (highestInfoGain == null) {
        return classValue;
    }/*from   w  ww  .  j a  v a2s.  co m*/
    // Else, keep going
    else {
        return children[(int) instance.value(highestInfoGain)].classifyInstance(instance);
    }
}

From source file:iris.Network.java

@Override
public double classifyInstance(Instance newInstance) throws Exception {
    List<Double> values = new ArrayList<>();
    List<Double> finalValues = new ArrayList<>();

    for (int i = 0; i < newInstance.numAttributes() - 1; i++) {
        values.add(newInstance.value(i));
    }//from   www.j  a  va 2 s  . c  om

    finalValues = getOutputs(values);

    double maxIndex = 0;

    //sets maxIndex to the highest value we calculated, i.e., what we think
    //the classification of the flower is according to our calculations.
    for (int i = 0; i < finalValues.size(); i++) {
        if (finalValues.get(i) > finalValues.get((int) maxIndex)) {
            maxIndex = i;
        }
    }

    return maxIndex;
}

From source file:irisdriver.IrisDriver.java

/**
 * @param args the command line arguments
 *///  ww w .  j  a  v  a2s.com
public static void main(String[] args) {
    //As an example of arguments: sepallength=5.1 sepalwidth=3.5 petallength=1.4 petalwidth=0.2    
    try {
        Hashtable<String, String> values = new Hashtable<String, String>();
        /*Iris irisModel = new Iris();
                
        for(int i = 0; i < args.length; i++) {
        String[] tokens = args[i].split("=");
                
        values.put(tokens[0], tokens[1]);
        }
                
        System.out.println("Classification: " + irisModel.classifySpecies(values));*/

        //Loading the model
        String pathModel = "";
        String pathTestSet = "";
        JFileChooser chooserModel = new JFileChooser();
        chooserModel.setCurrentDirectory(new java.io.File("."));
        chooserModel.setDialogTitle("Choose the model");
        chooserModel.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
        chooserModel.setAcceptAllFileFilterUsed(true);

        if (chooserModel.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
            File filePathModel = chooserModel.getSelectedFile();
            pathModel = filePathModel.getPath();

            Iris irisModel = new Iris(pathModel);

            //Loading the model
            JFileChooser chooserTestSet = new JFileChooser();
            chooserTestSet.setDialogTitle("Choose TEST SET");
            chooserTestSet.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
            chooserTestSet.setAcceptAllFileFilterUsed(true);

            //Loading the testing dataset
            if (chooserTestSet.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
                File filePathTestSet = chooserTestSet.getSelectedFile();
                pathTestSet = filePathTestSet.getPath();

                //WRITTING THE OUTPUT:
                BufferedWriter writer = new BufferedWriter(new FileWriter("D:\\output_file.txt"));

                //Transforming the data set into pairs attribute-value
                ConverterUtils.DataSource unlabeledSource = new ConverterUtils.DataSource(pathTestSet);
                Instances unlabeledData = unlabeledSource.getDataSet();
                if (unlabeledData.classIndex() == -1) {
                    unlabeledData.setClassIndex(unlabeledData.numAttributes() - 1);
                }

                for (int i = 0; i < unlabeledData.numInstances(); i++) {
                    Instance ins = unlabeledData.instance(i);

                    //ins.numAttributes()-1 --> not to include the label
                    for (int j = 0; j < ins.numAttributes() - 1; j++) {

                        String attrib = ins.attribute(j).name();
                        double val = ins.value(ins.attribute(j));

                        values.put(attrib, String.valueOf(val));

                    }

                    String predictedLabel = irisModel.classifySpecies(values);
                    System.out.println("Classification: " + predictedLabel);
                    values.clear();

                    //Writting the results in a txt
                    writer.write("The label is: " + predictedLabel);

                    //writer.newLine();

                    //writers.write("The error rate of the prediction is : " + eval.errorRate());

                    //writer.newLine();

                }

                writer.flush();
                writer.close();

            }

        }

    } catch (Exception ex) {
        Logger.getLogger(IrisDriver.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:j48.BinC45Split.java

License:Open Source License

/**
 * Creates split on enumerated attribute.
 *
 * @exception Exception if something goes wrong
 *///from   w w w .  ja  v  a 2 s.  c  o m
private void handleEnumeratedAttribute(Instances trainInstances) throws Exception {

    Distribution newDistribution, secondDistribution;
    int numAttValues;
    double currIG, currGR;
    Instance instance;
    int i;

    numAttValues = trainInstances.attribute(m_attIndex).numValues();
    newDistribution = new Distribution(numAttValues, trainInstances.numClasses());

    // Only Instances with known values are relevant.
    Enumeration enu = trainInstances.enumerateInstances();
    while (enu.hasMoreElements()) {
        instance = (Instance) enu.nextElement();
        if (!instance.isMissing(m_attIndex))
            newDistribution.add((int) instance.value(m_attIndex), instance);
    }
    m_distribution = newDistribution;

    // For all values
    for (i = 0; i < numAttValues; i++) {

        if (Utils.grOrEq(newDistribution.perBag(i), m_minNoObj)) {
            secondDistribution = new Distribution(newDistribution, i);

            // Check if minimum number of Instances in the two
            // subsets.
            if (secondDistribution.check(m_minNoObj)) {
                m_numSubsets = 2;
                currIG = m_infoGainCrit.splitCritValue(secondDistribution, m_sumOfWeights);
                currGR = m_gainRatioCrit.splitCritValue(secondDistribution, m_sumOfWeights, currIG);
                if ((i == 0) || Utils.gr(currGR, m_gainRatio)) {
                    m_gainRatio = currGR;
                    m_infoGain = currIG;
                    m_splitPoint = (double) i;
                    m_distribution = secondDistribution;
                }
            }
        }
    }
}

From source file:j48.BinC45Split.java

License:Open Source License

/**
 * Sets split point to greatest value in given data smaller or equal to
 * old split point./*from w  w w .j a  v a 2 s  .  co  m*/
 * (C4.5 does this for some strange reason).
 */
public final void setSplitPoint(Instances allInstances) {

    double newSplitPoint = -Double.MAX_VALUE;
    double tempValue;
    Instance instance;

    if ((!allInstances.attribute(m_attIndex).isNominal()) && (m_numSubsets > 1)) {
        Enumeration enu = allInstances.enumerateInstances();
        while (enu.hasMoreElements()) {
            instance = (Instance) enu.nextElement();
            if (!instance.isMissing(m_attIndex)) {
                tempValue = instance.value(m_attIndex);
                if (Utils.gr(tempValue, newSplitPoint) && Utils.smOrEq(tempValue, m_splitPoint))
                    newSplitPoint = tempValue;
            }
        }
        m_splitPoint = newSplitPoint;
    }
}

From source file:j48.BinC45Split.java

License:Open Source License

/**
 * Returns index of subset instance is assigned to.
 * Returns -1 if instance is assigned to more than one subset.
 *
 * @exception Exception if something goes wrong
 *///w ww.j a  v  a2s. co m

public final int whichSubset(Instance instance) throws Exception {

    if (instance.isMissing(m_attIndex))
        return -1;
    else {
        if (instance.attribute(m_attIndex).isNominal()) {
            if ((int) m_splitPoint == (int) instance.value(m_attIndex))
                return 0;
            else
                return 1;
        } else if (Utils.smOrEq(instance.value(m_attIndex), m_splitPoint))
            return 0;
        else
            return 1;
    }
}