Example usage for weka.core Instances numAttributes

List of usage examples for weka.core Instances numAttributes

Introduction

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

Prototype


publicint numAttributes() 

Source Link

Document

Returns the number of attributes.

Usage

From source file:adams.gui.menu.MarginCurve.java

License:Open Source License

/**
 * Launches the functionality of the menu item.
 *//*from   w  w w. j  a  va 2 s .c  o  m*/
@Override
public void launch() {
    File file;
    if (m_Parameters.length == 0) {
        // choose file
        int retVal = m_FileChooser.showOpenDialog(null);
        if (retVal != JFileChooser.APPROVE_OPTION)
            return;
        file = m_FileChooser.getSelectedFile();
    } else {
        file = new PlaceholderFile(m_Parameters[0]).getAbsoluteFile();
        m_FileChooser.setSelectedFile(file);
    }

    // create plot
    Instances result;
    try {
        result = m_FileChooser.getLoader().getDataSet();
    } catch (Exception e) {
        GUIHelper.showErrorMessage(getOwner(),
                "Error loading file '" + file + "':\n" + adams.core.Utils.throwableToString(e));
        return;
    }
    result.setClassIndex(result.numAttributes() - 1);
    VisualizePanel vp = new VisualizePanel();
    PlotData2D plot = new PlotData2D(result);
    plot.m_displayAllPoints = true;
    boolean[] connectPoints = new boolean[result.numInstances()];
    for (int cp = 1; cp < connectPoints.length; cp++)
        connectPoints[cp] = true;
    try {
        plot.setConnectPoints(connectPoints);
        vp.addPlot(plot);
    } catch (Exception e) {
        GUIHelper.showErrorMessage(getOwner(), "Error adding plot:\n" + adams.core.Utils.throwableToString(e));
        return;
    }

    ChildFrame frame = createChildFrame(vp, GUIHelper.getDefaultDialogDimension());
    frame.setTitle(frame.getTitle() + " - " + file);
}

From source file:adams.gui.menu.ROC.java

License:Open Source License

/**
 * Launches the functionality of the menu item.
 *//*from   ww  w.jav  a  2s.co  m*/
@Override
public void launch() {
    File file;
    if (m_Parameters.length == 0) {
        // choose file
        int retVal = m_FileChooser.showOpenDialog(null);
        if (retVal != JFileChooser.APPROVE_OPTION)
            return;
        file = m_FileChooser.getSelectedFile();
    } else {
        file = new PlaceholderFile(m_Parameters[0]).getAbsoluteFile();
        m_FileChooser.setSelectedFile(file);
    }

    // create plot
    Instances result;
    try {
        result = m_FileChooser.getLoader().getDataSet();
    } catch (Exception e) {
        GUIHelper.showErrorMessage(getOwner(),
                "Error loading file '" + file + "':\n" + adams.core.Utils.throwableToString(e));
        return;
    }
    result.setClassIndex(result.numAttributes() - 1);
    ThresholdVisualizePanel vmc = new ThresholdVisualizePanel();
    vmc.setROCString("(Area under ROC = " + Utils.doubleToString(ThresholdCurve.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;
    try {
        tempd.setConnectPoints(cp);
        vmc.addPlot(tempd);
    } catch (Exception e) {
        GUIHelper.showErrorMessage(getOwner(), "Error adding plot:\n" + adams.core.Utils.throwableToString(e));
        return;
    }

    ChildFrame frame = createChildFrame(vmc, GUIHelper.getDefaultDialogDimension());
    frame.setTitle(frame.getTitle() + " - " + file);
}

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

License:Open Source License

/**
 * Returns further inspection values./*from   w  ww .  ja  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.objectrenderer.WekaInstancesRenderer.java

License:Open Source License

/**
 * Performs the actual rendering.//from  w  w w. j  a va2  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:adams.gui.visualization.instances.InstancesColumnComboBox.java

License:Open Source License

/**
 * Updates the content of the combobox.// w w  w  . j a v a2 s  .  c o m
 */
protected synchronized void update() {
    List<ColumnContainer> columns;
    int i;
    Instances data;

    columns = new ArrayList<>();
    data = m_Table.getInstances();
    if (data != null) {
        for (i = 0; i < data.numAttributes(); i++)
            columns.add(new ColumnContainer(data.attribute(i).name(), i));
        Collections.sort(columns);
    }
    setModel(new DefaultComboBoxModel<>(columns.toArray(new ColumnContainer[0])));
}

From source file:adams.gui.visualization.instances.instancestable.AbstractPlotColumn.java

License:Open Source License

/**
 * Hook method for checks before attempting the plot.
 *
 * @param table   the source table//from  w  w w  . ja v a  2s .co m
 * @param data   the instances to use as basis
 * @param column   the column in the instances
 * @return      null if passed, otherwise error message
 */
protected String check(InstancesTable table, Instances data, int column) {
    if (table == null)
        return "No source table available!";
    if (data == null)
        return "No instances available!";
    if (column < 0)
        return "Negative column index!";
    if (column >= data.numAttributes())
        return "Column index too large: " + (column + 1) + " > " + data.numAttributes();
    return null;
}

From source file:adams.gui.visualization.instances.instancestable.AbstractProcessCell.java

License:Open Source License

/**
 * Hook method for checks before attempting processing.
 *
 * @param table   the source table// ww w. j av  a2  s. co  m
 * @param data   the instances to use as basis
 * @param actRow      the row in the instances
 * @param selRow    the selected row in the table
 * @param column   the column in the instances
 * @return      null if passed, otherwise error message
 */
protected String check(InstancesTable table, Instances data, int actRow, int selRow, int column) {
    if (table == null)
        return "No source table available!";
    if (data == null)
        return "No instances available!";
    if (actRow < 0)
        return "Negative row index!";
    if (actRow >= data.numInstances())
        return "Row index too large: " + (actRow + 1) + " > " + data.numInstances();
    if (column < 0)
        return "Negative column index!";
    if (column >= data.numAttributes())
        return "Column index too large: " + (column + 1) + " > " + data.numAttributes();
    return null;
}

From source file:adams.gui.visualization.instances.instancestable.Histogram.java

License:Open Source License

/**
 * Allows the user to generate a plot from either a row or a column.
 *
 * @param data   the instances to use//from w  ww . j  ava 2  s  . c o  m
 * @param isColumn   whether to use column or row
 * @param index   the index of the row/column
 */
protected void plot(final InstancesTable table, final Instances data, final boolean isColumn, int index) {
    TDoubleArrayList list;
    HistogramFactory.SetupDialog setup;
    HistogramFactory.Dialog dialog;
    int i;
    ArrayHistogram last;
    int col;
    int row;
    Object value;

    // let user customize histogram
    if (GUIHelper.getParentDialog(table) != null)
        setup = HistogramFactory.getSetupDialog(GUIHelper.getParentDialog(table), ModalityType.DOCUMENT_MODAL);
    else
        setup = HistogramFactory.getSetupDialog(GUIHelper.getParentFrame(table), true);
    setup.setDefaultCloseOperation(HistogramFactory.SetupDialog.DISPOSE_ON_CLOSE);
    setup.setTitle("Histogram setup");
    last = (ArrayHistogram) table.getLastSetup(getClass(), true, !isColumn);
    if (last == null)
        last = new ArrayHistogram();
    setup.setCurrent(last);
    setup.setLocationRelativeTo(GUIHelper.getParentComponent(table));
    setup.setVisible(true);
    if (setup.getResult() != GenericObjectEditorDialog.APPROVE_OPTION)
        return;
    last = (ArrayHistogram) setup.getCurrent();
    table.addLastSetup(getClass(), true, !isColumn, last);

    // get data from instances
    list = new TDoubleArrayList();
    if (isColumn) {
        col = index + 1;
        for (i = 0; i < table.getRowCount(); i++) {
            value = table.getValueAt(i, col);
            if ((value != null) && (Utils.isDouble(value.toString())))
                list.add(Utils.toDouble(value.toString()));
        }
    } else {
        row = index;
        for (i = 0; i < data.numAttributes(); i++) {
            if (data.attribute(i).isNumeric() && !data.instance(row).isMissing(i))
                list.add(data.instance(row).value(i));
        }
    }

    // calculate histogram
    last.clear();

    // display histogram
    if (GUIHelper.getParentDialog(table) != null)
        dialog = HistogramFactory.getDialog(GUIHelper.getParentDialog(table), ModalityType.MODELESS);
    else
        dialog = HistogramFactory.getDialog(GUIHelper.getParentFrame(table), false);
    dialog.setDefaultCloseOperation(HistogramFactory.Dialog.DISPOSE_ON_CLOSE);
    if (isColumn)
        dialog.add(last, list.toArray(), "Column " + (index + 1) + "/" + data.attribute(index).name());
    else
        dialog.add(last, list.toArray(), "Row " + (index + 1));
    dialog.setLocationRelativeTo(GUIHelper.getParentComponent(table));
    dialog.setVisible(true);
}

From source file:adams.gui.visualization.instances.instancestable.JFreeChart.java

License:Open Source License

/**
 * Allows the user to generate a plot from either a row or a column.
 *
 * @param data   the instances to use/*from   w  w w .j a  v  a  2 s . c o  m*/
 * @param isColumn   whether the to use column or row
 * @param index   the index of the row/column
 */
protected void plot(final InstancesTable table, final Instances data, final boolean isColumn, int index) {
    final List<Double> list;
    List<Double> tmp;
    GenericObjectEditorDialog setup;
    int i;
    final String title;
    SwingWorker worker;
    adams.flow.sink.JFreeChartPlot last;
    int numPoints;
    String newPoints;
    int col;
    int row;
    Object value;
    final SpreadSheet sheet;
    Row srow;
    boolean sorted;
    boolean asc;

    numPoints = isColumn ? data.numInstances() : data.numAttributes();
    if (numPoints > MAX_POINTS) {
        newPoints = GUIHelper.showInputDialog(null,
                "More than " + MAX_POINTS + " data points to plot - enter sample size:", "" + numPoints);
        if (newPoints == null)
            return;
        if (!Utils.isInteger(newPoints))
            return;
        if (Integer.parseInt(newPoints) != numPoints)
            numPoints = Integer.parseInt(newPoints);
        else
            numPoints = -1;
    } else {
        numPoints = -1;
    }

    // let user customize plot
    if (GUIHelper.getParentDialog(table) != null)
        setup = new GenericObjectEditorDialog(GUIHelper.getParentDialog(table), ModalityType.DOCUMENT_MODAL);
    else
        setup = new GenericObjectEditorDialog(GUIHelper.getParentFrame(table), true);
    setup.setDefaultCloseOperation(GenericObjectEditorDialog.DISPOSE_ON_CLOSE);
    setup.getGOEEditor().setClassType(Actor.class);
    setup.getGOEEditor().setCanChangeClassInDialog(false);
    last = (adams.flow.sink.JFreeChartPlot) table.getLastSetup(getClass(), true, !isColumn);
    if (last == null)
        last = new adams.flow.sink.JFreeChartPlot();
    setup.setCurrent(last);
    setup.setLocationRelativeTo(GUIHelper.getParentComponent(table));
    setup.setVisible(true);
    if (setup.getResult() != GenericObjectEditorDialog.APPROVE_OPTION)
        return;
    last = (adams.flow.sink.JFreeChartPlot) setup.getCurrent();
    table.addLastSetup(getClass(), true, !isColumn, last);

    // get data from instances
    tmp = new ArrayList<>();
    sorted = false;
    asc = table.isAscending();
    if (isColumn) {
        col = index + 1;
        sorted = (table.getSortColumn() == col);
        for (i = 0; i < table.getRowCount(); i++) {
            value = table.getValueAt(i, col);
            if ((value != null) && (Utils.isDouble(value.toString())))
                tmp.add(Utils.toDouble(value.toString()));
        }
    } else {
        row = index;
        for (i = 0; i < data.numAttributes(); i++) {
            if (data.attribute(i).isNumeric() && !data.instance(row).isMissing(i))
                tmp.add(data.instance(row).value(i));
        }
    }

    if (numPoints > -1) {
        numPoints = Math.min(numPoints, tmp.size());
        Collections.shuffle(tmp, new Random(1));
        list = tmp.subList(0, numPoints);
        if (sorted) {
            Collections.sort(list);
            if (!asc)
                Collections.reverse(list);
        }
    } else {
        list = tmp;
    }

    // create new spreadsheet
    sheet = new DefaultSpreadSheet();
    sheet.getHeaderRow().addCell("x").setContentAsString(isColumn ? "Row" : "Column");
    sheet.getHeaderRow().addCell("y")
            .setContentAsString(isColumn ? data.attribute(index).name() : ("Row " + (index + 1)));
    for (i = 0; i < list.size(); i++) {
        srow = sheet.addRow();
        srow.addCell("x").setContent((double) i + 1.0);
        srow.addCell("y").setContent(list.get(i));
    }

    // generate plot
    if (isColumn)
        title = "Column " + (index + 1) + "/" + data.attribute(index).name();
    else
        title = "Row " + (index + 1);
    last.getChart().setTitle(sheet.getColumnName(1));

    worker = new SwingWorker() {
        @Override
        protected Object doInBackground() throws Exception {
            Flow flow = new Flow();
            flow.setDefaultCloseOperation(BaseFrame.DISPOSE_ON_CLOSE);

            StorageValue sv = new StorageValue();
            sv.setStorageName(new StorageName("values"));
            flow.add(sv);

            Object last = table.getLastSetup(JFreeChart.this.getClass(), true, !isColumn);
            adams.flow.sink.JFreeChartPlot plot = (adams.flow.sink.JFreeChartPlot) ((adams.flow.sink.JFreeChartPlot) last)
                    .shallowCopy();
            plot.setShortTitle(true);
            plot.setName(title);
            plot.setX(-2);
            plot.setY(-2);
            flow.add(plot);

            flow.setUp();
            flow.getStorage().put(new StorageName("values"), sheet);
            flow.execute();
            flow.wrapUp();
            return null;
        }
    };
    worker.execute();
}

From source file:adams.gui.visualization.instances.instancestable.SimplePlot.java

License:Open Source License

/**
 * Allows the user to generate a plot from either a row or a column.
 *
 * @param data   the instances to use/*from   w w w.  j  av a  2 s . c  o m*/
 * @param isColumn   whether the to use column or row
 * @param index   the index of the row/column
 */
protected void plot(final InstancesTable table, final Instances data, final boolean isColumn, int index) {
    final List<Double> list;
    List<Double> tmp;
    GenericObjectEditorDialog setup;
    int i;
    final String title;
    SwingWorker worker;
    adams.flow.sink.SimplePlot last;
    int numPoints;
    String newPoints;
    int col;
    int row;
    Object value;
    boolean sorted;
    boolean asc;

    numPoints = isColumn ? data.numInstances() : data.numAttributes();
    if (numPoints > MAX_POINTS) {
        newPoints = GUIHelper.showInputDialog(null,
                "More than " + MAX_POINTS + " data points to plot - enter sample size:", "" + numPoints);
        if (newPoints == null)
            return;
        if (!Utils.isInteger(newPoints))
            return;
        if (Integer.parseInt(newPoints) != numPoints)
            numPoints = Integer.parseInt(newPoints);
        else
            numPoints = -1;
    } else {
        numPoints = -1;
    }

    // let user customize plot
    if (GUIHelper.getParentDialog(table) != null)
        setup = new GenericObjectEditorDialog(GUIHelper.getParentDialog(table), ModalityType.DOCUMENT_MODAL);
    else
        setup = new GenericObjectEditorDialog(GUIHelper.getParentFrame(table), true);
    setup.setDefaultCloseOperation(GenericObjectEditorDialog.DISPOSE_ON_CLOSE);
    setup.getGOEEditor().setClassType(Actor.class);
    setup.getGOEEditor().setCanChangeClassInDialog(false);
    last = (adams.flow.sink.SimplePlot) table.getLastSetup(getClass(), true, !isColumn);
    if (last == null) {
        last = new adams.flow.sink.SimplePlot();
        last.setNoToolTips(true);
        last.setMouseClickAction(new ViewDataClickAction());
    }
    setup.setCurrent(last);
    setup.setLocationRelativeTo(GUIHelper.getParentComponent(table));
    setup.setVisible(true);
    if (setup.getResult() != GenericObjectEditorDialog.APPROVE_OPTION)
        return;
    last = (adams.flow.sink.SimplePlot) setup.getCurrent();
    table.addLastSetup(getClass(), true, !isColumn, last);

    // get data from instances
    tmp = new ArrayList<>();
    sorted = false;
    asc = table.isAscending();
    if (isColumn) {
        col = index + 1;
        sorted = (table.getSortColumn() == col);
        for (i = 0; i < table.getRowCount(); i++) {
            value = table.getValueAt(i, col);
            if ((value != null) && (Utils.isDouble(value.toString())))
                tmp.add(Utils.toDouble(value.toString()));
        }
    } else {
        row = index;
        for (i = 0; i < data.numAttributes(); i++) {
            if (data.attribute(i).isNumeric() && !data.instance(row).isMissing(i))
                tmp.add(data.instance(row).value(i));
        }
    }

    if (numPoints > -1) {
        numPoints = Math.min(numPoints, tmp.size());
        Collections.shuffle(tmp, new Random(1));
        list = tmp.subList(0, numPoints);
        if (sorted) {
            Collections.sort(list);
            if (!asc)
                Collections.reverse(list);
        }
    } else {
        list = tmp;
    }

    // generate plot
    if (isColumn)
        title = "Column " + (index + 1) + "/" + data.attribute(index).name();
    else
        title = "Row " + (index + 1);

    worker = new SwingWorker() {
        @Override
        protected Object doInBackground() throws Exception {
            Flow flow = new Flow();
            flow.setDefaultCloseOperation(BaseFrame.DISPOSE_ON_CLOSE);

            StorageValue sv = new StorageValue();
            sv.setStorageName(new StorageName("values"));
            flow.add(sv);

            ArrayToSequence a2s = new ArrayToSequence();
            flow.add(a2s);

            MakePlotContainer mpc = new MakePlotContainer();
            mpc.setPlotName(title);
            flow.add(mpc);

            Object last = table.getLastSetup(SimplePlot.this.getClass(), true, !isColumn);
            adams.flow.sink.SimplePlot plot = (adams.flow.sink.SimplePlot) ((adams.flow.sink.SimplePlot) last)
                    .shallowCopy();
            plot.setShortTitle(true);
            plot.setShowSidePanel(false);
            plot.setName(title);
            plot.setX(-2);
            plot.setY(-2);
            flow.add(plot);

            flow.setUp();
            flow.getStorage().put(new StorageName("values"), list.toArray(new Double[list.size()]));
            flow.execute();
            flow.wrapUp();
            return null;
        }
    };
    worker.execute();
}