Example usage for weka.core Instances relationName

List of usage examples for weka.core Instances relationName

Introduction

In this page you can find the example usage for weka.core Instances relationName.

Prototype


publicString relationName() 

Source Link

Document

Returns the relation's name.

Usage

From source file:meka.gui.dataviewer.DataViewerMainPanel.java

License:Open Source License

/**
 * displays some properties of the instances
 *///from  w  w  w . j  a  v a 2 s.co  m
public void showProperties() {
    DataPanel panel;
    ListSelectorDialog dialog;
    Vector<String> props;
    Instances inst;

    panel = getCurrentPanel();
    if (panel == null) {
        return;
    }

    inst = panel.getInstances();
    if (inst == null) {
        return;
    }
    if (inst.classIndex() < 0) {
        inst.setClassIndex(inst.numAttributes() - 1);
    }

    // get some data
    props = new Vector<String>();
    props.add("Filename: " + panel.getFilename());
    props.add("Relation name: " + inst.relationName());
    props.add("# of instances: " + inst.numInstances());
    props.add("# of attributes: " + inst.numAttributes());
    props.add("Class attribute: " + inst.classAttribute().name());
    props.add("# of class labels: " + inst.numClasses());

    dialog = new ListSelectorDialog(getParentFrame(), new JList(props));
    dialog.showDialog();
}

From source file:meka.gui.explorer.classify.ReevaluateModelOnTestset.java

License:Open Source License

/**
 * Returns the action lister to use in the menu.
 *
 * @param history   the current history/*from   ww  w .j  a v  a 2 s . co m*/
 * @param index     the selected history item
 * @return          the listener
 */
@Override
public ActionListener getActionListener(final ResultHistoryList history, final int index) {
    final MultiLabelClassifier classifier = (MultiLabelClassifier) getClassifier(history, index);
    final Instances header = getHeader(history, index);

    return new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            Runnable run = new Runnable() {
                @Override
                public void run() {
                    ClassifyTab owner = (ClassifyTab) getOwner();
                    Result result;
                    Instances test;
                    owner.startBusy("Reevaluate on test...");
                    try {
                        MLUtils.prepareData(owner.getTestData());
                        test = new Instances(owner.getTestData());
                        test.setClassIndex(owner.getTestData().classIndex());
                        String msg = header.equalHeadersMsg(test);
                        if (msg != null)
                            throw new IllegalArgumentException(
                                    "Model's training set and current test set are not compatible:\n" + msg);
                        owner.log(OptionUtils.toCommandLine(classifier));
                        owner.log("Testset: " + test.relationName());
                        owner.log("Class-index: " + test.classIndex());
                        result = Evaluation.evaluateModel(classifier, test, "0.0", owner.getVOP()); // TODO what threshold to use?
                        owner.addResultToHistory(result, new Object[] { classifier, new Instances(test, 0) },
                                classifier.getClass().getName().replace("meka.classifiers.", ""));
                        owner.finishBusy();
                    } catch (Exception e) {
                        owner.handleException("Reevaluation failed on test set:", e);
                        owner.finishBusy("Reevaluation failed: " + e);
                        JOptionPane.showMessageDialog(owner, "Reevaluation failed:\n" + e, "Error",
                                JOptionPane.ERROR_MESSAGE);
                    }
                }
            };
            ((ClassifyTab) getOwner()).start(run);
        }
    };
}

From source file:meka.gui.explorer.ClassifyTab.java

License:Open Source License

/**
 * Starts the classification.//from w  ww  .j  a  v a2 s  .  co m
 */
protected void startClassification() {
    String type;
    Runnable run;
    final Instances data;

    if (m_ComboBoxExperiment.getSelectedIndex() == -1)
        return;

    data = new Instances(getData());
    if (m_Randomize)
        data.randomize(new Random(m_Seed));
    type = m_ComboBoxExperiment.getSelectedItem().toString();
    run = null;

    switch (type) {
    case TYPE_CROSSVALIDATION:
        run = new Runnable() {
            @Override
            public void run() {
                MultiLabelClassifier classifier;
                Result result;
                startBusy("Cross-validating...");
                try {
                    classifier = (MultiLabelClassifier) m_GenericObjectEditor.getValue();
                    log(OptionUtils.toCommandLine(classifier));
                    log("Dataset: " + data.relationName());
                    log("Class-index: " + data.classIndex());
                    result = Evaluation.cvModel(classifier, data, m_Folds, m_TOP, m_VOP);
                    addResultToHistory(result, new Object[] { classifier, new Instances(data, 0) },
                            classifier.getClass().getName().replace("meka.classifiers.", ""));
                    finishBusy();
                } catch (Exception e) {
                    handleException("Evaluation failed:", e);
                    finishBusy("Evaluation failed: " + e);
                    JOptionPane.showMessageDialog(ClassifyTab.this, "Evaluation failed (CV):\n" + e, "Error",
                            JOptionPane.ERROR_MESSAGE);
                }
            }
        };
        break;

    case TYPE_TRAINTESTSPLIT:
        run = new Runnable() {
            @Override
            public void run() {
                MultiLabelClassifier classifier;
                Result result;
                int trainSize;
                Instances train;
                Instances test;
                startBusy("Train/test split...");
                try {
                    trainSize = (int) (data.numInstances() * m_SplitPercentage / 100.0);
                    train = new Instances(data, 0, trainSize);
                    test = new Instances(data, trainSize, data.numInstances() - trainSize);
                    classifier = (MultiLabelClassifier) m_GenericObjectEditor.getValue();
                    log(OptionUtils.toCommandLine(classifier));
                    log("Dataset: " + train.relationName());
                    log("Class-index: " + train.classIndex());
                    result = Evaluation.evaluateModel(classifier, train, test, m_TOP, m_VOP);
                    addResultToHistory(result, new Object[] { classifier, new Instances(train, 0) },
                            classifier.getClass().getName().replace("meka.classifiers.", ""));
                    finishBusy();
                } catch (Exception e) {
                    handleException("Evaluation failed (train/test split):", e);
                    finishBusy("Evaluation failed: " + e);
                    JOptionPane.showMessageDialog(ClassifyTab.this, "Evaluation failed:\n" + e, "Error",
                            JOptionPane.ERROR_MESSAGE);
                }
            }
        };
        break;

    case TYPE_SUPPLIEDTESTSET:
        run = new Runnable() {
            @Override
            public void run() {
                MultiLabelClassifier classifier;
                Result result;
                int trainSize;
                Instances train;
                Instances test;
                startBusy("Supplied test...");
                try {
                    train = new Instances(data);
                    MLUtils.prepareData(m_TestInstances);
                    test = new Instances(m_TestInstances);
                    test.setClassIndex(data.classIndex());
                    String msg = train.equalHeadersMsg(test);
                    if (msg != null)
                        throw new IllegalArgumentException("Train and test set are not compatible:\n" + msg);
                    classifier = (MultiLabelClassifier) m_GenericObjectEditor.getValue();
                    log(OptionUtils.toCommandLine(classifier));
                    log("Dataset: " + train.relationName());
                    log("Class-index: " + train.classIndex());
                    result = Evaluation.evaluateModel(classifier, train, test, m_TOP, m_VOP);
                    addResultToHistory(result, new Object[] { classifier, new Instances(train, 0) },
                            classifier.getClass().getName().replace("meka.classifiers.", ""));
                    finishBusy();
                } catch (Exception e) {
                    handleException("Evaluation failed (train/test split):", e);
                    finishBusy("Evaluation failed: " + e);
                    JOptionPane.showMessageDialog(ClassifyTab.this, "Evaluation failed:\n" + e, "Error",
                            JOptionPane.ERROR_MESSAGE);
                }
            }
        };
        break;

    case TYPE_BINCREMENTAL:
        run = new Runnable() {
            @Override
            public void run() {
                MultiLabelClassifier classifier;
                Result result;
                startBusy("Incremental...");
                try {
                    classifier = (MultiLabelClassifier) m_GenericObjectEditor.getValue();
                    log(OptionUtils.toCommandLine(classifier));
                    log("Dataset: " + data.relationName());
                    log("Class-index: " + data.classIndex());
                    result = IncrementalEvaluation.evaluateModelBatchWindow(classifier, data, m_Samples, 1.,
                            m_TOP, m_VOP);
                    addResultToHistory(result, new Object[] { classifier, new Instances(data, 0) },
                            classifier.getClass().getName().replace("meka.classifiers.", ""));
                    finishBusy();
                } catch (Exception e) {
                    handleException("Evaluation failed (incremental splits):", e);
                    finishBusy("Evaluation failed: " + e);
                    JOptionPane.showMessageDialog(ClassifyTab.this, "Evaluation failed:\n" + e, "Error",
                            JOptionPane.ERROR_MESSAGE);
                }
            }
        };
        break;

    case TYPE_PREQUENTIAL:
        run = new Runnable() {
            @Override
            public void run() {
                MultiLabelClassifier classifier;
                Result result;
                startBusy("Incremental...");
                try {
                    classifier = (MultiLabelClassifier) m_GenericObjectEditor.getValue();
                    log(OptionUtils.toCommandLine(classifier));
                    log("Dataset: " + data.relationName());
                    log("Class-index: " + data.classIndex());
                    result = IncrementalEvaluation.evaluateModelPrequentialBasic(classifier, data,
                            (data.numInstances() / (m_Samples + 1)), 1., m_TOP, m_VOP);
                    addResultToHistory(result, new Object[] { classifier, new Instances(data, 0) },
                            classifier.getClass().getName().replace("meka.classifiers.", ""));
                    finishBusy();
                } catch (Exception e) {
                    handleException("Evaluation failed (incremental splits):", e);
                    finishBusy("Evaluation failed: " + e);
                    JOptionPane.showMessageDialog(ClassifyTab.this, "Evaluation failed:\n" + e, "Error",
                            JOptionPane.ERROR_MESSAGE);
                }
            }
        };
        break;

    default:
        throw new IllegalStateException("Unhandled evaluation type: " + type);
    }

    start(run);
}

From source file:meka.gui.guichooser.PrecisionRecallCurve.java

License:Open Source License

/**
 * Called by the menu items action listener.
 *///from  www .j av a  2  s.c  o  m
@Override
protected void launch() {
    m_FileChooser = GUIHelper.newConverterFileChooser();
    // choose file
    int retVal = m_FileChooser.showOpenDialog(null);
    if (retVal != JFileChooser.APPROVE_OPTION)
        return;
    File file = m_FileChooser.getSelectedFile();

    // create plot
    Instances data;
    try {
        data = m_FileChooser.getLoader().getDataSet();
    } catch (Exception e) {
        JOptionPane.showMessageDialog(null, "Error loading file '" + file + "':\n" + e, "Error",
                JOptionPane.ERROR_MESSAGE);
        e.printStackTrace();
        return;
    }
    data.setClassIndex(data.numAttributes() - 1);
    ThresholdVisualizePanel vmc = new ThresholdVisualizePanel();
    vmc.setROCString("(Area under PRC = " + Utils.doubleToString(ThresholdCurve.getPRCArea(data), 4) + ")");
    vmc.setName(data.relationName());
    PlotData2D tempd = new PlotData2D(data);
    tempd.setPlotName(data.relationName());
    tempd.m_displayAllPoints = true;
    // specify which points are connected
    boolean[] cp = new boolean[data.numInstances()];
    for (int n = 1; n < cp.length; n++)
        cp[n] = true;
    try {
        tempd.setConnectPoints(cp);
        vmc.addPlot(tempd);
        if (data.attribute(ThresholdCurve.RECALL_NAME) != null)
            vmc.setXIndex(data.attribute(ThresholdCurve.RECALL_NAME).index());
        if (data.attribute(ThresholdCurve.PRECISION_NAME) != null)
            vmc.setYIndex(data.attribute(ThresholdCurve.PRECISION_NAME).index());
    } catch (Exception e) {
        JOptionPane.showMessageDialog(null, "Error adding plot:\n" + e, "Error", JOptionPane.ERROR_MESSAGE);
        e.printStackTrace();
        return;
    }

    MekaFrame frame = new MekaFrame();
    frame.setTitle(getName());
    frame.setDefaultCloseOperation(MekaFrame.DISPOSE_ON_CLOSE);
    frame.getContentPane().setLayout(new BorderLayout());
    frame.getContentPane().add(vmc);
    frame.setSize(800, 600);
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
}

From source file:meka.gui.guichooser.ROC.java

License:Open Source License

/**
 * Called by the menu items action listener.
 *//*from  w  w  w  .j av a  2  s .c o m*/
@Override
protected void launch() {
    m_FileChooser = GUIHelper.newConverterFileChooser();
    // choose file
    int retVal = m_FileChooser.showOpenDialog(null);
    if (retVal != JFileChooser.APPROVE_OPTION)
        return;
    File file = m_FileChooser.getSelectedFile();

    // create plot
    Instances data;
    try {
        data = m_FileChooser.getLoader().getDataSet();
    } catch (Exception e) {
        JOptionPane.showMessageDialog(null, "Error loading file '" + file + "':\n" + e, "Error",
                JOptionPane.ERROR_MESSAGE);
        e.printStackTrace();
        return;
    }
    data.setClassIndex(data.numAttributes() - 1);
    ThresholdVisualizePanel vmc = new ThresholdVisualizePanel();
    vmc.setROCString("(Area under ROC = " + Utils.doubleToString(ThresholdCurve.getROCArea(data), 4) + ")");
    vmc.setName(data.relationName());
    PlotData2D tempd = new PlotData2D(data);
    tempd.setPlotName(data.relationName());
    tempd.m_displayAllPoints = true;
    // specify which points are connected
    boolean[] cp = new boolean[data.numInstances()];
    for (int n = 1; n < cp.length; n++)
        cp[n] = true;
    try {
        tempd.setConnectPoints(cp);
        vmc.addPlot(tempd);
        if (data.attribute(ThresholdCurve.FP_RATE_NAME) != null)
            vmc.setXIndex(data.attribute(ThresholdCurve.FP_RATE_NAME).index());
        if (data.attribute(ThresholdCurve.TP_RATE_NAME) != null)
            vmc.setYIndex(data.attribute(ThresholdCurve.TP_RATE_NAME).index());
    } catch (Exception e) {
        JOptionPane.showMessageDialog(null, "Error adding plot:\n" + e, "Error", JOptionPane.ERROR_MESSAGE);
        e.printStackTrace();
        return;
    }

    MekaFrame frame = new MekaFrame();
    frame.setTitle(getName());
    frame.setDefaultCloseOperation(MekaFrame.DISPOSE_ON_CLOSE);
    frame.getContentPane().setLayout(new BorderLayout());
    frame.getContentPane().add(vmc);
    frame.setSize(800, 600);
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
}

From source file:milk.core.Exemplars.java

License:Open Source License

/**
 * Constructor using the given dataset and set ID index to 
 * the given ID index.  Any instances with class value or ID
 * value missing will be dropped.// w  ww . j  av a 2s  .  co  m
 *
 * @param dataset the instances from which the header 
 * information is to be taken
 * @param idIndex the ID attribute's index 
 * @exception Exception if the class index of the dataset 
 * is not set(i.e. -1) or the data is not a multi-instance data
 */
public Exemplars(Instances dataset, int idIndex) throws Exception {
    if (dataset.classIndex() == -1)
        throw new Exception(" Class Index negative (class not set yet)!");

    m_ClassIndex = dataset.classIndex();
    m_RelationName = dataset.relationName();
    int numAttr = dataset.numAttributes();
    m_Attributes = new Attribute[numAttr];
    for (int i = 0; i < numAttr; i++)
        m_Attributes[i] = dataset.attribute(i);

    m_IdIndex = idIndex;
    Attribute id = m_Attributes[m_IdIndex];
    if ((m_IdIndex > numAttr) || (m_IdIndex < 0) || (!id.isNominal()))
        throw new Exception("ID index is wrong!");

    m_Exemplars = new Vector(id.numValues());

    for (int j = 0; j < dataset.numInstances(); j++) {
        Instance ins = dataset.instance(j);
        add(ins);
    }
}

From source file:miRdup.WekaModule.java

License:Open Source License

public static void rocCurve(Evaluation eval) {
    try {//from   ww w  . ja  v a 2s. co  m
        // generate curve
        ThresholdCurve tc = new ThresholdCurve();
        int classIndex = 0;
        Instances result = tc.getCurve(eval.predictions(), classIndex);
        result.toString();
        // plot curve
        ThresholdVisualizePanel vmc = new ThresholdVisualizePanel();
        vmc.setROCString("(Area under ROC = " + Utils.doubleToString(tc.getROCArea(result), 4) + ")");
        vmc.setName(result.relationName());
        PlotData2D tempd = new PlotData2D(result);
        tempd.setPlotName(result.relationName());
        tempd.addInstanceNumberAttribute();
        // specify which points are connected
        boolean[] cp = new boolean[result.numInstances()];
        for (int n = 1; n < cp.length; n++) {
            cp[n] = true;
        }
        tempd.setConnectPoints(cp);
        // add plot
        vmc.addPlot(tempd);

        //
        result.toString();

        // display curve
        String plotName = vmc.getName();
        final javax.swing.JFrame jf = new javax.swing.JFrame("Weka Classifier Visualize: " + plotName);
        jf.setSize(500, 400);
        jf.getContentPane().setLayout(new BorderLayout());
        jf.getContentPane().add(vmc, BorderLayout.CENTER);
        jf.addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent e) {
                jf.dispose();
            }
        });

        jf.setVisible(true);
        System.out.println("");
    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:mlpoc.MLPOC.java

public static Evaluation crossValidate(String filename) {
    Evaluation eval = null;/*from  ww w .  jav a 2 s.  c  o  m*/
    try {
        BufferedReader br = new BufferedReader(new FileReader(filename));
        // loads data and set class index
        Instances data = new Instances(br);
        br.close();
        /*File csv=new File(filename);
        CSVLoader loader = new CSVLoader();
        loader.setSource(csv);
        Instances data = loader.getDataSet();*/
        data.setClassIndex(data.numAttributes() - 1);

        // classifier
        String[] tmpOptions;
        String classname = "weka.classifiers.trees.J48 -C 0.25";
        tmpOptions = classname.split(" ");
        classname = "weka.classifiers.trees.J48";
        tmpOptions[0] = "";
        Classifier cls = (Classifier) Utils.forName(Classifier.class, classname, tmpOptions);

        // other options
        int seed = 2;
        int folds = 10;

        // randomize data
        Random rand = new Random(seed);
        Instances randData = new Instances(data);
        randData.randomize(rand);
        if (randData.classAttribute().isNominal())
            randData.stratify(folds);

        // perform cross-validation
        eval = new Evaluation(randData);
        for (int n = 0; n < folds; n++) {
            Instances train = randData.trainCV(folds, n);
            Instances test = randData.testCV(folds, n);
            // the above code is used by the StratifiedRemoveFolds filter, the
            // code below by the Explorer/Experimenter:
            // Instances train = randData.trainCV(folds, n, rand);

            // build and evaluate classifier
            Classifier clsCopy = Classifier.makeCopy(cls);
            clsCopy.buildClassifier(train);
            eval.evaluateModel(clsCopy, test);
        }

        // output evaluation
        System.out.println();
        System.out.println("=== Setup ===");
        System.out
                .println("Classifier: " + cls.getClass().getName() + " " + Utils.joinOptions(cls.getOptions()));
        System.out.println("Dataset: " + data.relationName());
        System.out.println("Folds: " + folds);
        System.out.println("Seed: " + seed);
        System.out.println();
        System.out.println(eval.toSummaryString("Summary for testing", true));
        System.out.println("Correctly Classified Instances: " + eval.correct());
        System.out.println("Percentage of Correctly Classified Instances: " + eval.pctCorrect());
        System.out.println("InCorrectly Classified Instances: " + eval.incorrect());
        System.out.println("Percentage of InCorrectly Classified Instances: " + eval.pctIncorrect());

    } catch (Exception ex) {
        System.err.println(ex.getMessage());
    }
    return eval;
}

From source file:moa.classifiers.macros.TACNB.java

License:Open Source License

public void initHeader(Instances dataset) {
    int numLabels = this.numOldLabelsOption.getValue();
    Attribute target = dataset.classAttribute();

    List<String> possibleValues = new ArrayList<String>();
    int n = target.numValues();
    for (int i = 0; i < n; i++) {
        possibleValues.add(target.value(i));
    }/*  w  ww.  j a  va2  s.  c  o m*/

    ArrayList<Attribute> attrs = new ArrayList<Attribute>(numLabels + dataset.numAttributes());
    for (int i = 0; i < numLabels; i++) {
        attrs.add(new Attribute(target.name() + "_" + i, possibleValues));
    }
    for (int i = 0; i < dataset.numAttributes(); i++) {
        attrs.add((Attribute) dataset.attribute(i).copy());
    }
    this.header = new Instances("extended_" + dataset.relationName(), attrs, 0);
    this.header.setClassIndex(numLabels + dataset.classIndex());
}

From source file:moa.classifiers.novelClass.AbstractNovelClassClassifier.java

License:Apache License

final public static Instances augmentInstances(Instances datum) {
    ArrayList<Attribute> attInfo = new ArrayList<>(datum.numAttributes());
    for (int aIdx = 0; aIdx < datum.numAttributes(); aIdx++) {
        Attribute a = datum.attribute(aIdx).copy(datum.attribute(aIdx).name());
        if ((aIdx == datum.classIndex()) && (a.indexOfValue(NOVEL_LABEL_STR) < 0)) { // only if we don't already have these
            List<String> values = new ArrayList<>(a.numValues() + 2);
            for (int i = 0; i < a.numValues(); ++i) {
                values.add(a.value(i));/*from  w w  w. ja v a2 s .  c  om*/
            }
            values.add(OUTLIER_LABEL_STR);
            values.add(NOVEL_LABEL_STR);
            a = new Attribute(a.name(), values, a.getMetadata());
        }
        attInfo.add(a);
    }
    String relationshipName = NOVEL_CLASS_INSTANCE_RELATIONSHIP_TYPE + "-" + datum.relationName();
    Instances ret = new Instances(relationshipName, attInfo, 1);
    ret.setClassIndex(datum.classIndex());

    return ret;
}