Example usage for weka.core Instance attribute

List of usage examples for weka.core Instance attribute

Introduction

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

Prototype

public Attribute attribute(int index);

Source Link

Document

Returns the attribute with the given index.

Usage

From source file:NaiveBayes.NaiveBayes.java

@Override
public double classifyInstance(Instance last) {
    double prob[] = new double[last.classAttribute().numValues()];
    for (int classIndex = 0; classIndex < last.attribute(last.classIndex()).numValues(); classIndex++) {//classifikasi
        double temp = 1;
        int i = 0;

        for (Atribut attr : getList()) {
            if (i == last.classIndex())
                i++;// w  ww. j  a  v  a2s.c om
            //System.out.println(attr.getName()+"="+last.attribute(i).name());
            temp *= attr.getFrekuensiNilai(last.attribute(last.classIndex()).value(classIndex),
                    last.toString(i), last.value(i), last.attribute(i).isNumeric()) / numEachClass[classIndex];
            i++;
        }
        double res;
        res = numEachClass[classIndex] / last.numAttributes() * temp;
        prob[classIndex] = res;
    }
    return maxIndex(prob);
}

From source file:net.sf.jclal.activelearning.multilabel.querystrategy.AbstractMultiLabelQueryStrategy.java

License:Open Source License

/**
 * Get the true labels of the instance// w w w . j a v a 2s . co  m
 * 
 * @param instance The instance to test
 * @return The true category vector
 */
public boolean[] getTrueLabels(Instance instance) {

    boolean[] trueLabels = new boolean[getNumLabels()];

    for (int counter = 0; counter < getNumLabels(); counter++) {

        int classIdx = getLabelIndices()[counter];

        String classValue = instance.attribute(classIdx).value((int) instance.value(classIdx));

        trueLabels[counter] = classValue.equals("1");
    }

    return trueLabels;
}

From source file:org.deidentifier.arx.ARFF2ARX.java

License:Open Source License

/**
 *
 * @param instance/*  www  .  ja  v  a  2s  .  c o m*/
 * @return
 */
protected String[] convertRow(Instance instance) {
    String[] row = new String[instance.numAttributes()];
    for (int i = 0; i < instance.numAttributes(); i++) {
        if (instance.attribute(i).type() == Attribute.NOMINAL
                || instance.attribute(i).type() == Attribute.STRING) {
            row[i] = instance.stringValue(i);
        } else {
            row[i] = String.valueOf((int) instance.value(i));
        }
    }
    return row;
}

From source file:org.hypknowsys.wumprep.WUMprepWrapper.java

License:Open Source License

/**
 * Creates a dummy dataset from the input format, sends it to the script and
 * reads the script output's ARFF information that in turn is used to set
 * <code>this</code>' output format.
 * /*from www  . j a v a  2 s  .  c  o m*/
 * This mechanism allows a WUMprep script to alter the recordset layout as
 * long as this change is documented by the output ARFF header. For example,
 * the <tt>dnsLookup.pl</tt> script changes the <code>host_ip</code> field
 * to <code>host_dns</code> when performing IP lookups.
 * 
 * @param instanceInfo
 *          The input format.
 * @return Object containing the output instance structure.
 */
public Instances getScriptOutputFormat(Instances instanceInfo) {
    Instances outputFormat = instanceInfo;
    Instances testData = new Instances(instanceInfo);
    Instance testInstance = new Instance(testData.numAttributes());

    testData.delete();
    testInstance.setDataset(testData);

    // Initialize the testInstance's attribute values
    for (int i = 0; i < testInstance.numAttributes(); i++) {
        String aName = testInstance.attribute(i).name();
        if (aName.equals("host_ip"))
            testInstance.setValue(i, "127.0.0.1");
        else if (aName.equals("ts_day"))
            testInstance.setValue(i, "01");
        else if (aName.equals("ts_month"))
            testInstance.setValue(i, "Jan");
        else if (aName.equals("ts_year"))
            testInstance.setValue(i, "2005");
        else if (aName.equals("ts_hour"))
            testInstance.setValue(i, "11");
        else if (aName.equals("ts_minutes"))
            testInstance.setValue(i, "55");
        else if (aName.equals("ts_seconds"))
            testInstance.setValue(i, "00");
        else if (aName.equals("tz"))
            testInstance.setValue(i, "+0200");
        else
            testInstance.setValue(i, aName + "-dummy");
    }

    testData.add(testInstance);

    WUMprepWrapper testWrapper = new WUMprepWrapper(m_scriptName, m_args);
    testWrapper.start();
    testWrapper.push(testData.toString());
    testWrapper.push((Instance) null);

    class ErrorReader extends Thread implements Serializable {
        /**  */
        private static final long serialVersionUID = -488779846603045891L;
        PipedReader m_input = null;

        /**
         * Helper class for reading stderr output from the WUMprep script
         * 
         * @param input The script's wrapper's stderr pipe reader
         */
        ErrorReader(PipedReader input) {
            m_input = input;
            this.start();
        }

        public void run() {
            try {
                while (m_input.read() >= 0)
                    ;
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    // read the stderr output
    new ErrorReader(testWrapper.getErrorPipe());

    try {
        // ignore the stderr output
        outputFormat = new org.hypknowsys.wumprep4weka.core.Instances(testWrapper.getOutputPipe());

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return outputFormat;
}

From source file:org.iobserve.analysis.behavior.filter.ClusterMerger.java

License:Apache License

@Override
protected void execute(final Map<Integer, List<Pair<Instance, Double>>> clustering) throws Exception {
    /**//from  w  ww .  j  a va 2  s. c om
     * simply pick the first instance of every cluster lookup attributes to build a new
     * instances Object
     */
    Instance instance = clustering.entrySet().iterator().next().getValue().get(0).getElement1();
    final FastVector attributes = new FastVector();
    for (int j = 0; j < instance.numAttributes(); j++) {
        attributes.addElement(instance.attribute(j));
    }

    final Instances result = new Instances("Clustering Result", attributes, clustering.size());

    for (final List<Pair<Instance, Double>> entry : clustering.values()) {
        if (!entry.isEmpty()) {
            instance = entry.get(0).getElement1();
            result.add(instance);
        }
    }

    if (ClusterMerger.LOGGER.isDebugEnabled()) {
        this.printInstances(result);
    }
    this.outputPort.send(result);
}

From source file:org.knime.knip.suise.node.boundarymodel.contourdata.WekaMIContourDataClassifier.java

License:Open Source License

/**
 * {@inheritDoc}//  ww w  .  jav a  2 s  .co  m
 */
@Override
public double contourProbability(double[] inst) throws Exception {
    Instances bagData = new Instances(m_data.attribute(1).relation(), 1);
    Instance i = new DenseInstance(1, inst);
    i.setDataset(bagData);

    bagData.add(i);

    Instance bag = new DenseInstance(3);
    bag.setDataset(m_data);
    int val = bag.attribute(1).addRelation(bagData);
    bag.setValue(1, val);

    return m_classifier.distributionForInstance(bag)[1];

}

From source file:org.openml.webapplication.algorithm.InstancesHelper.java

License:Open Source License

public static double[] predictionToConfidences(Instances dataset, Instance prediction,
        int[] att_prediction_confidence, int att_prediction) throws Exception {
    double[] confidences = new double[dataset.numClasses()];
    boolean nonNullValue = false;
    for (int i = 0; i < dataset.numClasses(); i++) {
        if (Utils.isMissingValue(prediction.value(att_prediction_confidence[i]))) {
            throw new Exception("Prediction file contains missing values for important attribute ("
                    + prediction.attribute(att_prediction_confidence[i]).name() + "). ");
        }//from   w  w w  .  j av  a2s  .  c om
        confidences[i] = prediction.value(att_prediction_confidence[i]);
        if (confidences[i] > 0) {
            nonNullValue = true;
        }
    }

    if (nonNullValue == false) {
        confidences[(int) prediction.value(att_prediction)] = 1;
    }

    return confidences;
}

From source file:org.opentox.jaqpot3.qsar.util.WekaInstancesProcess.java

License:Open Source License

public static Map<String, Double> getInstanceAttributeValues(Instance inst, int numAttributes) {
    //numAttributes need to be set before adding the new attributes
    Map<String, Double> featureMap = new HashMap();
    if (numAttributes > 0) {
        double res;
        for (int i = 0; i < numAttributes; ++i) {
            res = (!Double.isNaN(inst.value(i))) ? inst.value(i) : 0;
            res = (!Double.isInfinite(res)) ? res : 0;
            featureMap.put(inst.attribute(i).name(), res);
        }/*from  w  w w  . j  ava2 s .c  o m*/
    }
    return featureMap;
}

From source file:org.opentox.jaqpot3.qsar.util.WekaInstancesProcess.java

License:Open Source License

public static PMMLEvaluationContext getInstanceAttributeFieldRefValues(Instance inst, int numAttributes,
        PMMLEvaluationContext context, List<DataField> dataFields) {
    //numAttributes need to be set before adding the new attributes
    for (DataField dataField : dataFields) {
        for (int i = 0; i < numAttributes; ++i) {
            if (StringUtils.equals(inst.attribute(i).name(), dataField.getName().toString())) {
                context.declare(dataField.getName(), inst.value(i));
                break;
            }//w  ww  .  j av a 2 s  .c  om
        }

    }

    return context;
}

From source file:org.scripps.branch.classifier.ManualTree.java

License:Open Source License

/**
 * Trying to get generate distribution of classes
 * //  www.  jav a  2s. c o m
 * @param Instances
 * @Param Attribute index to get distribution of
 * @Param HashMap to put data into
 * 
 * @return HashMap of class distribution data
 */
protected HashMap addDistributionData(Instances instances, int attIndex, HashMap distMap) throws Exception {
    Map<String, Comparable> temp = new HashMap<String, Comparable>();
    ArrayList<Object> distData = new ArrayList();
    // GenerateCSV csv = new GenerateCSV();
    // String data = "";
    boolean isNominal = false;
    instances.sort(attIndex);
    for (int i = 0; i < instances.numInstances(); i++) {
        Instance inst = instances.instance(i);
        if (!Double.isNaN(inst.value(attIndex))) {
            temp = new HashMap<String, Comparable>();
            if (inst.attribute(attIndex).isNominal()) {
                temp.put("value", inst.attribute(attIndex).value((int) inst.value(attIndex)));
                isNominal = true;
                // data+=inst.attribute(m_Attribute).value((int)inst.value(m_Attribute))+",";
            } else {
                temp.put("value", inst.value(attIndex));
                // data+=inst.value(att)+",";
            }
            temp.put("classprob", inst.classAttribute().value((int) inst.classValue()));
            // data+=inst.classAttribute().value((int)
            // inst.classValue())+"\n";
            distData.add(temp);
        }
    }
    if (!distData.isEmpty()) {
        distMap.put("dataArray", distData);
        distMap.put("isNominal", isNominal);
        setDistributionData(distMap);
    }
    return distMap;
    // To check if data is being generated right.
    // csv.generateCsvFile("/home/karthik/Documents/distribution.csv",
    // data);
}