Example usage for weka.core Instance copy

List of usage examples for weka.core Instance copy

Introduction

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

Prototype

Object copy();

Source Link

Document

This method produces a shallow copy of an object.

Usage

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

License:Open Source License

/**
 * Performs the actual export.//from   w w w  .  j  a va 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  .  ja v a2 s .c  om
 *
 * @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  w w.java2 s .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.
 * //  ww w  .j  a  v  a 2s  . 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
 * // ww w.j  av  a  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:cotraining.copy.Evaluation_D.java

License:Open Source License

/**
 * Evaluates the classifier on a single instance and records the
 * prediction (if the class is nominal).
 *
 * @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
 *//* w  w  w.j av a2  s .c  om*/
public double evaluateModelOnceAndRecordPrediction(Classifier classifier, 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();
        }
        double[] dist = classifier.distributionForInstance(classMissing);
        pred = Utils.maxIndex(dist);
        if (dist[(int) pred] <= 0) {
            pred = Instance.missingValue();
        }
        updateStatsForClassifier(dist, instance);
        m_Predictions.addElement(new NominalPrediction(instance.classValue(), dist, instance.weight()));
    } else {
        pred = classifier.classifyInstance(classMissing);
        updateStatsForPredictor(pred, instance);
    }
    return pred;
}

From source file:cotraining.copy.Evaluation_D.java

License:Open Source License

/**
 * store the prediction made by the classifier as a string
 * /*from w w  w  . j a v  a 2s  . com*/
 * @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:data.generation.target.utils.PrincipalComponents.java

License:Open Source License

/**
 * Transform an instance in original (unormalized) format. Convert back
 * to the original space if requested.// w  w  w.ja  v a  2s. com
 * @param instance an instance in the original (unormalized) format
 * @return a transformed instance
 * @throws Exception if instance cant be transformed
 */
public Instance convertInstance(Instance instance) throws Exception {

    if (m_eigenvalues == null) {
        throw new Exception("convertInstance: Principal components not " + "built yet");
    }

    double[] newVals = new double[m_outputNumAtts];
    Instance tempInst = (Instance) instance.copy();
    if (!instance.dataset().equalHeaders(m_trainHeader)) {
        throw new Exception("Can't convert instance: header's don't match: " + "PrincipalComponents\n"
                + "Can't convert instance: header's don't match.");
    }

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

    /*if (m_normalize) {
      m_normalizeFilter.input(tempInst);
      m_normalizeFilter.batchFinished();
      tempInst = m_normalizeFilter.output();
    }*/

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

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

    if (!m_center) {
        m_standardizeFilter.input(tempInst);
        m_standardizeFilter.batchFinished();
        tempInst = m_standardizeFilter.output();
    } else {
        m_centerFilter.input(tempInst);
        m_centerFilter.batchFinished();
        tempInst = m_centerFilter.output();
    }

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

    double cumulative = 0;
    for (int i = m_numAttribs - 1; i >= 0; i--) {
        double tempval = 0.0;
        for (int j = 0; j < m_numAttribs; j++) {
            tempval += (m_eigenvectors[j][m_sortedEigens[i]] * tempInst.value(j));
        }
        newVals[m_numAttribs - i - 1] = tempval;
        cumulative += m_eigenvalues[m_sortedEigens[i]];
        if ((cumulative / m_sumOfEigenValues) >= m_coverVariance) {
            break;
        }
    }

    if (!m_transBackToOriginal) {
        if (instance instanceof SparseInstance) {
            return new SparseInstance(instance.weight(), newVals);
        } else {
            return new Instance(instance.weight(), newVals);
        }
    } else {
        if (instance instanceof SparseInstance) {
            return convertInstanceToOriginal(new SparseInstance(instance.weight(), newVals));
        } else {
            return convertInstanceToOriginal(new Instance(instance.weight(), newVals));
        }
    }
}

From source file:distributedRedditAnalyser.OzaBoost.java

License:Open Source License

@Override
public void trainOnInstanceImpl(Instance inst) {
    try {//www  . j av a2 s.com
        lock.acquire();
        //Get a new classifier
        Classifier newClassifier = ((Classifier) getPreparedClassOption(this.baseLearnerOption)).copy();
        ensemble.add(new ClassifierInstance(newClassifier));

        //If we have too many classifiers
        while (ensemble.size() > ensembleSizeOption.getValue())
            ensemble.pollFirst();

        double lambda_d = 1.0;
        for (ClassifierInstance c : ensemble) {
            double k = this.pureBoostOption.isSet() ? lambda_d
                    : MiscUtils.poisson(lambda_d, this.classifierRandom);
            if (k > 0.0) {
                Instance weightedInst = (Instance) inst.copy();
                weightedInst.setWeight(inst.weight() * k);
                c.getClassifier().trainOnInstance(weightedInst);
            }
            if (c.getClassifier().correctlyClassifies(inst)) {
                c.setScms(c.getScms() + lambda_d);
                lambda_d *= this.trainingWeightSeenByModel / (2 * c.getScms());
            } else {
                c.setSwms(c.getSwms() + lambda_d);
                lambda_d *= this.trainingWeightSeenByModel / (2 * c.getSwms());
            }
        }
    } catch (InterruptedException e) {
        e.printStackTrace();
    } finally {
        lock.release();
    }
}

From source file:fantail.algorithms.RankingByPairwiseComparison.java

License:Open Source License

@Override
public double[] recommendRanking(Instance testInst) throws Exception {
    Instances tempData = new Instances(testInst.dataset(), 0);
    tempData.add((Instance) testInst.copy());
    // remove the relation att
    tempData.setClassIndex(-1);/*w  w w  .j  a v a  2s. c  o  m*/
    tempData.deleteAttributeAt(tempData.numAttributes() - 1);
    tempData = Filter.useFilter(tempData, m_Add);
    tempData.setClassIndex(tempData.numAttributes() - 1);
    double predRanking[] = new double[m_NumLabels];
    for (int i = 0; i < predRanking.length; i++) {
        predRanking[i] = m_NumLabels - 1;
    }
    for (int i = 0; i < m_Classifiers.size(); i++) {
        double predIndex = m_Classifiers.get(i).classifyInstance(tempData.instance(0));
        String algoPair = m_AlgoPairs.get(i);
        String[] parts = algoPair.split("\\|");
        int trueIndex = Integer.parseInt(parts[(int) predIndex]);
        predRanking[trueIndex] -= 1;
    }
    predRanking = Tools.doubleArrayToRanking(predRanking);
    return predRanking;
}