Example usage for weka.core Instance dataset

List of usage examples for weka.core Instance dataset

Introduction

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

Prototype

public Instances dataset();

Source Link

Document

Returns the dataset this instance has access to.

Usage

From source file:adams.flow.transformer.WekaTrainClassifier.java

License:Open Source License

/**
 * Executes the flow item./*from   w  w  w.  j a va2 s .  c  o m*/
 *
 * @return      null if everything is fine, otherwise error message
 */
@Override
protected String doExecute() {
    String result;
    Instances data;
    Instance inst;
    weka.classifiers.Classifier cls;

    result = null;

    try {
        cls = null;
        if ((m_InputToken != null) && (m_InputToken.getPayload() instanceof Instances)) {
            cls = getClassifierInstance();
            data = (Instances) m_InputToken.getPayload();
            cls.buildClassifier(data);
            m_OutputToken = new Token(new WekaModelContainer(cls, new Instances(data, 0), data));
        } else if ((m_InputToken != null) && (m_InputToken.getPayload() instanceof Instance)) {
            if (m_IncrementalClassifier == null) {
                cls = getClassifierInstance();
                if (!(cls instanceof UpdateableClassifier))
                    result = m_Classifier + "/" + cls.getClass().getName()
                            + " is not an incremental classifier!";
            }
            if (result == null) {
                inst = (Instance) m_InputToken.getPayload();
                if (m_IncrementalClassifier == null) {
                    m_IncrementalClassifier = cls;
                    if (m_SkipBuild) {
                        ((UpdateableClassifier) m_IncrementalClassifier).updateClassifier(inst);
                    } else {
                        data = new Instances(inst.dataset(), 1);
                        data.add((Instance) inst.copy());
                        m_IncrementalClassifier.buildClassifier(data);
                    }
                } else {
                    ((UpdateableClassifier) m_IncrementalClassifier).updateClassifier(inst);
                }
                m_OutputToken = new Token(
                        new WekaModelContainer(m_IncrementalClassifier, new Instances(inst.dataset(), 0)));
            }
        }
    } catch (Exception e) {
        m_OutputToken = null;
        result = handleException("Failed to process data:", e);
    }

    if (m_OutputToken != null)
        updateProvenance(m_OutputToken);

    return result;
}

From source file:adams.flow.transformer.WekaTrainClusterer.java

License:Open Source License

/**
 * Executes the flow item./*from   w  w  w .ja  va2  s. c o  m*/
 *
 * @return      null if everything is fine, otherwise error message
 */
@Override
protected String doExecute() {
    String result;
    Instances data;
    Instance inst;
    weka.clusterers.Clusterer cls;
    WekaModelContainer cont;

    result = null;

    try {
        cls = null;
        if ((m_InputToken != null) && (m_InputToken.getPayload() instanceof Instances)) {
            cls = getClustererInstance();
            data = (Instances) m_InputToken.getPayload();
            cls.buildClusterer(data);
            cont = new WekaModelContainer(cls, new Instances(data, 0), data);
            cont = m_PostProcessor.postProcess(cont);
            m_OutputToken = new Token(cont);
        } else if ((m_InputToken != null) && (m_InputToken.getPayload() instanceof Instance)) {
            if (m_IncrementalClusterer == null) {
                cls = getClustererInstance();
                if (!(cls instanceof UpdateableClusterer))
                    result = m_Clusterer + "/" + cls.getClass().getName() + " is not an incremental clusterer!";
            }
            if (result == null) {
                inst = (Instance) m_InputToken.getPayload();
                if (m_IncrementalClusterer == null) {
                    m_IncrementalClusterer = cls;
                    data = new Instances(inst.dataset(), 1);
                    data.add((Instance) inst.copy());
                    m_IncrementalClusterer.buildClusterer(data);
                } else {
                    ((UpdateableClusterer) m_IncrementalClusterer).updateClusterer(inst);
                    ((UpdateableClusterer) m_IncrementalClusterer).updateFinished();
                }
                m_OutputToken = new Token(
                        new WekaModelContainer(m_IncrementalClusterer, new Instances(inst.dataset(), 0)));
            }
        }
    } catch (Exception e) {
        m_OutputToken = null;
        result = handleException("Failed to process input: " + m_InputToken.getPayload(), e);
    }

    if (m_OutputToken != null)
        updateProvenance(m_OutputToken);

    return result;
}

From source file:adams.gui.visualization.debug.inspectionhandler.WekaInstances.java

License:Open Source License

/**
 * Returns further inspection values./*from   w  w  w .j a  v a  2  s  .c o m*/
 *
 * @param obj      the object to further inspect
 * @return      the named inspected values
 */
@Override
public Hashtable<String, Object> inspect(Object obj) {
    Hashtable<String, Object> result;
    Instances data;
    Instance inst;

    result = new Hashtable<String, Object>();

    if (obj instanceof Instances) {
        data = (Instances) obj;
        inst = null;
    } else {
        inst = (Instance) obj;
        data = inst.dataset();
    }

    result.put("relation", data.relationName());
    result.put("num attributes", data.numAttributes());
    result.put("class attribute", (data.classIndex() == -1) ? "-none-"
            : ((data.classIndex() + 1) + " (" + data.classAttribute().name() + ")"));
    if (inst == null) {
        result.put("num instances", data.numInstances());
        result.put("instances", data.toArray());
    }

    return result;
}

From source file:adams.gui.visualization.debug.objectexport.WekaInstancesExporter.java

License:Open Source License

/**
 * Performs the actual export.//ww w  . j a  v a  2 s.c o m
 *
 * @param obj      the object to export
 * @param file   the file to export to
 * @return      null if successful, otherwise error message
 */
@Override
protected String doExport(Object obj, File file) {
    Instances data;
    Instance inst;

    try {
        if (obj instanceof Instances) {
            DataSink.write(file.getAbsolutePath(), (Instances) obj);
            return null;
        } else {
            inst = (Instance) obj;
            if (inst.dataset() != null) {
                data = new Instances(inst.dataset());
                data.add((Instance) inst.copy());
                DataSink.write(file.getAbsolutePath(), data);
                return null;
            } else {
                return "Instance has no dataset associated, cannot export as ARFF!";
            }
        }
    } catch (Exception e) {
        return "Failed to write Instances to '" + file + "'!\n" + Utils.throwableToString(e);
    }
}

From source file:adams.gui.visualization.debug.objectrenderer.WekaInstancesRenderer.java

License:Open Source License

/**
 * Performs the actual rendering./*w  ww.j  av a  2s.co  m*/
 *
 * @param obj      the object to render
 * @param panel   the panel to render into
 * @return      null if successful, otherwise error message
 */
@Override
protected String doRender(Object obj, JPanel panel) {
    Instance inst;
    Instances data;
    InstancesTable table;
    InstancesTableModel model;
    BaseScrollPane scrollPane;
    PlainTextRenderer plain;
    SpreadSheet sheet;
    Row row;
    int i;
    SpreadSheetRenderer sprenderer;

    if (obj instanceof Instances) {
        data = (Instances) obj;
        if (data.numInstances() == 0) {
            sheet = new DefaultSpreadSheet();
            row = sheet.getHeaderRow();
            row.addCell("I").setContentAsString("Index");
            row.addCell("N").setContentAsString("Name");
            row.addCell("T").setContentAsString("Type");
            row.addCell("C").setContentAsString("Class");
            for (i = 0; i < data.numAttributes(); i++) {
                row = sheet.addRow();
                row.addCell("I").setContent(i + 1);
                row.addCell("N").setContentAsString(data.attribute(i).name());
                row.addCell("T").setContentAsString(Attribute.typeToString(data.attribute(i)));
                row.addCell("C").setContent((i == data.classIndex()) ? "true" : "");
            }
            sprenderer = new SpreadSheetRenderer();
            sprenderer.render(sheet, panel);
        } else {
            model = new InstancesTableModel(data);
            model.setShowAttributeIndex(true);
            table = new InstancesTable(model);
            scrollPane = new BaseScrollPane(table);
            panel.add(scrollPane, BorderLayout.CENTER);
        }
    } else {
        inst = (Instance) obj;
        if (inst.dataset() != null) {
            data = new Instances(inst.dataset(), 0);
            data.add((Instance) inst.copy());
            table = new InstancesTable(data);
            scrollPane = new BaseScrollPane(table);
            panel.add(scrollPane, BorderLayout.CENTER);
        } else {
            plain = new PlainTextRenderer();
            plain.render(obj, panel);
        }
    }

    return null;
}

From source file:bme.mace.logicdomain.Evaluation.java

License:Open Source License

/**
 * Evaluates the classifier on a single instance and records the prediction
 * (if the class is nominal)./*w ww .j av  a2s. com*/
 * 
 * @param classifier machine learning classifier
 * @param instance the test instance to be classified
 * @return the prediction made by the clasifier
 * @throws Exception if model could not be evaluated successfully or the data
 *           contains string attributes
 */
public double evaluateModelOnceAndRecordPrediction(List<LibSVM> classifier, List<Double> classifierWeight,
        Instance instance) throws Exception {
    Instance classMissing = (Instance) instance.copy();
    double pred = 0;
    classMissing.setDataset(instance.dataset());
    classMissing.setClassMissing();
    if (m_ClassIsNominal) {
        if (m_Predictions == null) {
            m_Predictions = new FastVector();
        }
        List<double[]> prob = new ArrayList<double[]>();//
        double[] finalProb = new double[instance.numClasses()];
        for (int i = 0; i < classifier.size(); i++) {
            double[] dist = classifier.get(i).distributionForInstance(classMissing);//
            prob.add(dist);
        }
        for (int i = 0; i < finalProb.length; i++) {
            for (int j = 0; j < classifier.size(); j++) {
                finalProb[i] += prob.get(j)[i] * classifierWeight.get(j);
            }
        }
        double sum = 0;
        for (int i = 0; i < finalProb.length; i++) {
            sum += finalProb[i];
        }
        for (int i = 0; i < finalProb.length; i++) {
            finalProb[i] = finalProb[i] / sum;
        }
        pred = Utils.maxIndex(finalProb);
        if (finalProb[(int) pred] <= 0) {
            pred = Instance.missingValue();
        }
        updateStatsForClassifier(finalProb, instance);
        m_Predictions.addElement(new NominalPrediction(instance.classValue(), finalProb, instance.weight()));
    } else {

        pred = classifier.get(0).classifyInstance(classMissing);
        updateStatsForPredictor(pred, instance);
    }
    return pred;
}

From source file:bme.mace.logicdomain.Evaluation.java

License:Open Source License

/**
 * Evaluates the classifier on a single instance.
 * /*from ww  w  . ja v  a2s. c om*/
 * @param classifier machine learning classifier
 * @param instance the test instance to be classified
 * @return the prediction made by the clasifier
 * @throws Exception if model could not be evaluated successfully or the data
 *           contains string attributes
 */
public double evaluateModelOnce(Classifier classifier, Instance instance) throws Exception {

    Instance classMissing = (Instance) instance.copy();
    double pred = 0;
    classMissing.setDataset(instance.dataset());
    classMissing.setClassMissing();
    if (m_ClassIsNominal) {
        double[] dist = classifier.distributionForInstance(classMissing);
        pred = Utils.maxIndex(dist);
        if (dist[(int) pred] <= 0) {
            pred = Instance.missingValue();
        }
        updateStatsForClassifier(dist, instance);
    } else {
        pred = classifier.classifyInstance(classMissing);
        updateStatsForPredictor(pred, instance);
    }
    return pred;
}

From source file:bme.mace.logicdomain.Evaluation.java

License:Open Source License

/**
 * store the prediction made by the classifier as a string
 * //from w  ww .ja  va  2s  .co m
 * @param classifier the classifier to use
 * @param inst the instance to generate text from
 * @param instNum the index in the dataset
 * @param attributesToOutput the indices of the attributes to output
 * @param printDistribution prints the complete distribution for nominal
 *          classes, not just the predicted value
 * @return the prediction as a String
 * @throws Exception if something goes wrong
 * @see #printClassifications(Classifier, Instances, String, int, Range,
 *      boolean)
 */
protected static String predictionText(Classifier classifier, Instance inst, int instNum,
        Range attributesToOutput, boolean printDistribution)

        throws Exception {

    StringBuffer result = new StringBuffer();
    int width = 10;
    int prec = 3;

    Instance withMissing = (Instance) inst.copy();
    withMissing.setDataset(inst.dataset());
    withMissing.setMissing(withMissing.classIndex());
    double predValue = classifier.classifyInstance(withMissing);

    // index
    result.append(Utils.padLeft("" + (instNum + 1), 6));

    if (inst.dataset().classAttribute().isNumeric()) {
        // actual
        if (inst.classIsMissing()) {
            result.append(" " + Utils.padLeft("?", width));
        } else {
            result.append(" " + Utils.doubleToString(inst.classValue(), width, prec));
        }
        // predicted
        if (Instance.isMissingValue(predValue)) {
            result.append(" " + Utils.padLeft("?", width));
        } else {
            result.append(" " + Utils.doubleToString(predValue, width, prec));
        }
        // error
        if (Instance.isMissingValue(predValue) || inst.classIsMissing()) {
            result.append(" " + Utils.padLeft("?", width));
        } else {
            result.append(" " + Utils.doubleToString(predValue - inst.classValue(), width, prec));
        }
    } else {
        // actual
        result.append(" "
                + Utils.padLeft(((int) inst.classValue() + 1) + ":" + inst.toString(inst.classIndex()), width));
        // predicted
        if (Instance.isMissingValue(predValue)) {
            result.append(" " + Utils.padLeft("?", width));
        } else {
            result.append(" " + Utils.padLeft(
                    ((int) predValue + 1) + ":" + inst.dataset().classAttribute().value((int) predValue),
                    width));
        }
        // error?
        if (!Instance.isMissingValue(predValue) && !inst.classIsMissing()
                && ((int) predValue + 1 != (int) inst.classValue() + 1)) {
            result.append(" " + "  +  ");
        } else {
            result.append(" " + "     ");
        }
        // prediction/distribution
        if (printDistribution) {
            if (Instance.isMissingValue(predValue)) {
                result.append(" " + "?");
            } else {
                result.append(" ");
                double[] dist = classifier.distributionForInstance(withMissing);
                for (int n = 0; n < dist.length; n++) {
                    if (n > 0) {
                        result.append(",");
                    }
                    if (n == (int) predValue) {
                        result.append("*");
                    }
                    result.append(Utils.doubleToString(dist[n], prec));
                }
            }
        } else {
            if (Instance.isMissingValue(predValue)) {
                result.append(" " + "?");
            } else {
                result.append(" " + Utils.doubleToString(
                        classifier.distributionForInstance(withMissing)[(int) predValue], prec));
            }
        }
    }

    // attributes
    result.append(" " + attributeValuesString(withMissing, attributesToOutput) + "\n");

    return result.toString();
}

From source file:boostingPL.boosting.AdaBoost.java

License:Open Source License

@Override
public double classifyInstance(Instance inst) throws Exception {
    int classNum = inst.dataset().classAttribute().numValues();
    double[] H = new double[classNum];
    for (int j = 0; j < cweights.length; j++) {
        int classValue = (int) classifiers[j].classifyInstance(inst);
        if (classValue >= 0) {
            H[classValue] += cweights[j];
        }/*from   ww  w . j  av a 2  s  . com*/
    }
    return (double) maxIdx(H);
}

From source file:boostingPL.boosting.AdaBoost.java

License:Open Source License

@Override
public double[] distributionForInstance(Instance inst) throws Exception {
    int classNum = inst.dataset().classAttribute().numValues();
    double[] H = new double[classNum];
    double sum = 0;
    for (int j = 0; j < numIterations; j++) {
        int classValue = (int) classifiers[j].classifyInstance(inst);
        H[classValue] += cweights[j];//from   w ww . ja  v  a 2 s. co m
        sum += cweights[j];
    }

    // normalize
    for (int i = 0; i < H.length; i++) {
        H[i] /= sum;
    }
    return H;
}