Example usage for weka.core Instances attribute

List of usage examples for weka.core Instances attribute

Introduction

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

Prototype

publicAttribute attribute(String name) 

Source Link

Document

Returns an attribute given its name.

Usage

From source file:adams.flow.sink.WekaAttributeSummary.java

License:Open Source License

/**
 * Creates a new display panel for the token.
 *
 * @param token   the token to display in a new panel, can be null
 * @return      the generated panel//from w  w w  . ja  va  2s  .c  om
 */
@Override
public DisplayPanel createDisplayPanel(Token token) {
    AbstractDisplayPanel result;

    result = new AbstractComponentDisplayPanel(getClass().getSimpleName()) {
        private static final long serialVersionUID = 7384093089760722339L;
        protected BaseTabbedPane m_TabbedPane;
        protected AttributeVisualizationPanel m_PanelAtt;

        @Override
        protected void initGUI() {
            super.initGUI();
            setLayout(new BorderLayout());
            m_PanelAtt = new AttributeVisualizationPanel();
            add(m_PanelAtt, BorderLayout.CENTER);
        }

        @Override
        public void display(Token token) {
            Instances inst;
            int[] indices;
            AttributeVisualizationPanel panel;

            inst = (Instances) token.getPayload();
            m_Range.setData(inst);
            indices = m_Range.getIntIndices();

            clearPanel();

            if (indices.length == 1) {
                m_PanelAtt = new AttributeVisualizationPanel();
                m_PanelAtt.setInstances(inst);
                m_PanelAtt.setAttribute(indices[0]);
                m_Panel.add(m_PanelAtt, BorderLayout.CENTER);
            } else if (indices.length > 1) {
                m_TabbedPane = new BaseTabbedPane();
                m_Panel.add(m_TabbedPane, BorderLayout.CENTER);
                for (int index : indices) {
                    panel = new AttributeVisualizationPanel();
                    panel.setInstances(inst);
                    panel.setAttribute(index);
                    m_TabbedPane.addTab(inst.attribute(index).name(), panel);
                }
            }
        }

        @Override
        public void cleanUp() {
        }

        @Override
        public void clearPanel() {
            removeAll();
        }

        @Override
        public JComponent supplyComponent() {
            if (m_TabbedPane != null)
                return m_TabbedPane;
            else
                return m_PanelAtt;
        }
    };

    if (token != null)
        result.display(token);

    return result;
}

From source file:adams.flow.sink.WekaInstancesPlot.java

License:Open Source License

/**
 * Plots the token (the panel and dialog have already been created at
 * this stage)./*from   ww  w. ja va 2s  . co  m*/
 *
 * @param token   the token to display
 */
@Override
protected void display(Token token) {
    PlotData2D plot;
    Instances data;

    try {
        data = (Instances) token.getPayload();
        m_AttributeX.setData(data);
        m_AttributeY.setData(data);
        plot = new PlotData2D(data);
        if ((m_AttributeX.getIntIndex() != -1) && (m_AttributeY.getIntIndex() != -1))
            plot.setPlotName(data.attribute(m_AttributeX.getIntIndex()).name() + " vs "
                    + data.attribute(m_AttributeX.getIntIndex()).name());
        plot.m_displayAllPoints = true;
        m_VisualizePanel.addPlot(plot);
        if (m_AttributeX.getIntIndex() != -1)
            m_VisualizePanel.setXIndex(m_AttributeX.getIntIndex());
        if (m_AttributeY.getIntIndex() != -1)
            m_VisualizePanel.setYIndex(m_AttributeY.getIntIndex());
    } catch (Exception e) {
        handleException("Failed to display token: " + token, e);
    }
}

From source file:adams.flow.sink.WekaInstancesPlot.java

License:Open Source License

/**
 * Creates a new panel for the token.//  w  w  w  .ja  v  a2 s .  c  o  m
 *
 * @param token   the token to display in a new panel, can be null
 * @return      the generated panel
 */
public AbstractDisplayPanel createDisplayPanel(Token token) {
    AbstractDisplayPanel result;
    String name;

    name = "Instances plot";

    result = new AbstractComponentDisplayPanel(name) {
        private static final long serialVersionUID = -7362768698548152899L;
        protected VisualizePanel m_VisualizePanel;

        @Override
        protected void initGUI() {
            super.initGUI();
            setLayout(new BorderLayout());
            m_VisualizePanel = new VisualizePanel();
            add(m_VisualizePanel, BorderLayout.CENTER);
        }

        @Override
        public void display(Token token) {
            PlotData2D plot;
            Instances data;

            try {
                data = (Instances) token.getPayload();
                m_AttributeX.setData(data);
                m_AttributeY.setData(data);
                plot = new PlotData2D(data);
                if ((m_AttributeX.getIntIndex() != -1) && (m_AttributeY.getIntIndex() != -1))
                    plot.setPlotName(data.attribute(m_AttributeX.getIntIndex()).name() + " vs "
                            + data.attribute(m_AttributeX.getIntIndex()).name());
                plot.m_displayAllPoints = true;
                m_VisualizePanel.addPlot(plot);
                if (m_AttributeX.getIntIndex() != -1)
                    m_VisualizePanel.setXIndex(m_AttributeX.getIntIndex());
                if (m_AttributeY.getIntIndex() != -1)
                    m_VisualizePanel.setYIndex(m_AttributeY.getIntIndex());
            } catch (Exception e) {
                handleException("Failed to display token: " + token, e);
            }
        }

        @Override
        public JComponent supplyComponent() {
            return m_VisualizePanel;
        }

        @Override
        public void clearPanel() {
            m_VisualizePanel.removeAllPlots();
        }

        public void cleanUp() {
            m_VisualizePanel.removeAllPlots();
        }
    };

    if (token != null)
        result.display(token);

    return result;
}

From source file:adams.flow.sink.WekaThresholdCurve.java

License:Open Source License

/**
 * Plots the token (the panel and dialog have already been created at
 * this stage)./*from www.j  a  va 2s  .c o  m*/
 *
 * @param token   the token to display
 */
@Override
protected void display(Token token) {
    ThresholdCurve curve;
    Evaluation eval;
    PlotData2D plot;
    boolean[] connectPoints;
    int cp;
    Instances data;
    int[] indices;

    try {
        if (token.getPayload() instanceof WekaEvaluationContainer)
            eval = (Evaluation) ((WekaEvaluationContainer) token.getPayload())
                    .getValue(WekaEvaluationContainer.VALUE_EVALUATION);
        else
            eval = (Evaluation) token.getPayload();
        if (eval.predictions() == null) {
            getLogger().severe("No predictions available from Evaluation object!");
            return;
        }
        m_ClassLabelRange.setData(eval.getHeader().classAttribute());
        indices = m_ClassLabelRange.getIntIndices();
        for (int index : indices) {
            curve = new ThresholdCurve();
            data = curve.getCurve(eval.predictions(), index);
            plot = new PlotData2D(data);
            plot.setPlotName(eval.getHeader().classAttribute().value(index));
            plot.m_displayAllPoints = true;
            connectPoints = new boolean[data.numInstances()];
            for (cp = 1; cp < connectPoints.length; cp++)
                connectPoints[cp] = true;
            plot.setConnectPoints(connectPoints);
            m_VisualizePanel.addPlot(plot);
            if (data.attribute(m_AttributeX.toDisplay()) != null)
                m_VisualizePanel.setXIndex(data.attribute(m_AttributeX.toDisplay()).index());
            if (data.attribute(m_AttributeY.toDisplay()) != null)
                m_VisualizePanel.setYIndex(data.attribute(m_AttributeY.toDisplay()).index());
        }
    } catch (Exception e) {
        handleException("Failed to display token: " + token, e);
    }
}

From source file:adams.flow.sink.WekaThresholdCurve.java

License:Open Source License

/**
 * Creates a new panel for the token./*from w  w w .j a  va  2  s. c  o  m*/
 *
 * @param token   the token to display in a new panel, can be null
 * @return      the generated panel
 */
public AbstractDisplayPanel createDisplayPanel(Token token) {
    AbstractDisplayPanel result;
    String name;

    if (token != null)
        name = "Threshold curve (" + getEvaluation(token).getHeader().relationName() + ")";
    else
        name = "Threshold curve";

    result = new AbstractComponentDisplayPanel(name) {
        private static final long serialVersionUID = -7362768698548152899L;
        protected ThresholdVisualizePanel m_VisualizePanel;

        @Override
        protected void initGUI() {
            super.initGUI();
            setLayout(new BorderLayout());
            m_VisualizePanel = new ThresholdVisualizePanel();
            add(m_VisualizePanel, BorderLayout.CENTER);
        }

        @Override
        public void display(Token token) {
            try {
                Evaluation eval = getEvaluation(token);
                m_ClassLabelRange.setMax(eval.getHeader().classAttribute().numValues());
                int[] indices = m_ClassLabelRange.getIntIndices();
                for (int index : indices) {
                    ThresholdCurve curve = new ThresholdCurve();
                    Instances data = curve.getCurve(eval.predictions(), index);
                    PlotData2D plot = new PlotData2D(data);
                    plot.setPlotName(eval.getHeader().classAttribute().value(index));
                    plot.m_displayAllPoints = true;
                    boolean[] connectPoints = new boolean[data.numInstances()];
                    for (int cp = 1; cp < connectPoints.length; cp++)
                        connectPoints[cp] = true;
                    plot.setConnectPoints(connectPoints);
                    m_VisualizePanel.addPlot(plot);
                    if (data.attribute(m_AttributeX.toDisplay()) != null)
                        m_VisualizePanel.setXIndex(data.attribute(m_AttributeX.toDisplay()).index());
                    if (data.attribute(m_AttributeY.toDisplay()) != null)
                        m_VisualizePanel.setYIndex(data.attribute(m_AttributeY.toDisplay()).index());
                }
            } catch (Exception e) {
                getLogger().log(Level.SEVERE, "Failed to display token: " + token, e);
            }
        }

        @Override
        public JComponent supplyComponent() {
            return m_VisualizePanel;
        }

        @Override
        public void clearPanel() {
            m_VisualizePanel.removeAllPlots();
        }

        public void cleanUp() {
            m_VisualizePanel.removeAllPlots();
        }
    };

    if (token != null)
        result.display(token);

    return result;
}

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

License:Open Source License

/**
 * Executes the flow item./*  w  ww.  j  a  v a2  s . c  o  m*/
 *
 * @return      null if everything is fine, otherwise error message
 */
@Override
protected String doExecute() {
    String result;
    Instances data;
    int[] indices;
    String name;
    boolean useRegExp;

    result = null;

    if (m_InputToken.getPayload() instanceof Instance)
        data = ((Instance) m_InputToken.getPayload()).dataset();
    else
        data = ((Instances) m_InputToken.getPayload());

    m_Range.setMax(data.numAttributes());
    indices = m_Range.getIntIndices();
    useRegExp = !m_RegExp.isEmpty() && !m_RegExp.isMatchAll();
    m_Names.clear();
    for (int index : indices) {
        name = data.attribute(index).name();
        if (useRegExp)
            if (!m_RegExp.isMatch(name))
                continue;
        m_Names.add(name);
    }

    return result;
}

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

License:Open Source License

/**
 * Executes the flow item./*from   w  w  w .j  a  v a 2  s  . c o m*/
 *
 * @return      null if everything is fine, otherwise error message
 */
@Override
protected String doExecute() {
    String result;
    Instances data;
    Instances reduced;
    Instances transformed;
    AttributeSelection eval;
    boolean crossValidate;
    int fold;
    Instances train;
    WekaAttributeSelectionContainer cont;
    SpreadSheet stats;
    int i;
    Row row;
    int[] selected;
    double[][] ranked;
    Range range;
    String rangeStr;
    boolean useReduced;

    result = null;

    try {
        if (m_InputToken.getPayload() instanceof Instances)
            data = (Instances) m_InputToken.getPayload();
        else
            data = (Instances) ((WekaTrainTestSetContainer) m_InputToken.getPayload())
                    .getValue(WekaTrainTestSetContainer.VALUE_TRAIN);

        if (result == null) {
            crossValidate = (m_Folds >= 2);

            // setup evaluation
            eval = new AttributeSelection();
            eval.setEvaluator(m_Evaluator);
            eval.setSearch(m_Search);
            eval.setFolds(m_Folds);
            eval.setSeed((int) m_Seed);
            eval.setXval(crossValidate);

            // select attributes
            if (crossValidate) {
                Random random = new Random(m_Seed);
                data = new Instances(data);
                data.randomize(random);
                if ((data.classIndex() > -1) && data.classAttribute().isNominal()) {
                    if (isLoggingEnabled())
                        getLogger().info("Stratifying instances...");
                    data.stratify(m_Folds);
                }
                for (fold = 0; fold < m_Folds; fold++) {
                    if (isLoggingEnabled())
                        getLogger().info("Creating splits for fold " + (fold + 1) + "...");
                    train = data.trainCV(m_Folds, fold, random);
                    if (isLoggingEnabled())
                        getLogger().info("Selecting attributes using all but fold " + (fold + 1) + "...");
                    eval.selectAttributesCVSplit(train);
                }
            } else {
                eval.SelectAttributes(data);
            }

            // generate reduced/transformed dataset
            reduced = null;
            transformed = null;
            if (!crossValidate) {
                reduced = eval.reduceDimensionality(data);
                if (m_Evaluator instanceof AttributeTransformer)
                    transformed = ((AttributeTransformer) m_Evaluator).transformedData(data);
            }

            // generated stats
            stats = null;
            if (!crossValidate) {
                stats = new DefaultSpreadSheet();
                row = stats.getHeaderRow();

                useReduced = false;
                if (m_Search instanceof RankedOutputSearch) {
                    i = reduced.numAttributes();
                    if (reduced.classIndex() > -1)
                        i--;
                    ranked = eval.rankedAttributes();
                    useReduced = (ranked.length == i);
                }

                if (useReduced) {
                    for (i = 0; i < reduced.numAttributes(); i++)
                        row.addCell("" + i).setContent(reduced.attribute(i).name());
                    row = stats.addRow();
                    for (i = 0; i < reduced.numAttributes(); i++)
                        row.addCell(i).setContent(0.0);
                } else {
                    for (i = 0; i < data.numAttributes(); i++)
                        row.addCell("" + i).setContent(data.attribute(i).name());
                    row = stats.addRow();
                    for (i = 0; i < data.numAttributes(); i++)
                        row.addCell(i).setContent(0.0);
                }

                if (m_Search instanceof RankedOutputSearch) {
                    ranked = eval.rankedAttributes();
                    for (i = 0; i < ranked.length; i++)
                        row.getCell((int) ranked[i][0]).setContent(ranked[i][1]);
                } else {
                    selected = eval.selectedAttributes();
                    for (i = 0; i < selected.length; i++)
                        row.getCell(selected[i]).setContent(1.0);
                }
            }

            // selected attributes
            rangeStr = null;
            if (!crossValidate) {
                range = new Range();
                range.setIndices(eval.selectedAttributes());
                rangeStr = range.getRange();
            }

            // setup container
            if (crossValidate)
                cont = new WekaAttributeSelectionContainer(data, reduced, transformed, eval, m_Seed, m_Folds);
            else
                cont = new WekaAttributeSelectionContainer(data, reduced, transformed, eval, stats, rangeStr);
            m_OutputToken = new Token(cont);
        }
    } catch (Exception e) {
        m_OutputToken = null;
        result = handleException("Failed to process data:", e);
    }

    return result;
}

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

License:Open Source License

/**
 * Prompts the user to select attributes.
 * /*from   w  w w . j a va  2 s. com*/
 * @param inst   the data to present
 * @param preSelected   the indices of the attributes to use by default
 * @return      the list of selected attributes to keep, null if cancelled
 */
protected List<Integer> selectAttributes(Instances inst, List<Integer> preSelected) {
    ArrayList<Integer> result;
    DefaultTableModel model;
    BaseTable table;
    String[][] names;
    int i;
    int n;
    ApprovalDialog dialog;
    JPanel panelAll;
    JPanel panelOptions;
    BaseCheckBox checkBoxInvert;
    BaseTextArea textMessage;
    Range range;
    int[][] segments;
    int numAtts;
    String msg;

    result = new ArrayList<>();

    msg = getVariables().expand(m_Message);
    numAtts = inst.numAttributes();
    if (inst.classIndex() > -1)
        numAtts--;
    names = new String[numAtts][1];
    n = 0;
    for (i = 0; i < inst.numAttributes(); i++) {
        if (inst.classIndex() == i)
            continue;
        names[n][0] = inst.attribute(i).name();
        n++;
    }
    model = new DefaultTableModel(names, new String[] { "Attribute" });

    range = new Range();
    range.setMax(numAtts);
    range.setIndices(Utils.toIntArray(preSelected));
    segments = range.getIntSegments();
    table = new BaseTable(model);
    table.setAutoResizeMode(BaseTable.AUTO_RESIZE_OFF);
    table.setOptimalColumnWidth();
    table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
    for (int[] segment : segments)
        table.getSelectionModel().addSelectionInterval(segment[0], segment[1]);

    panelAll = new JPanel(new BorderLayout());
    panelAll.add(new BaseScrollPane(table), BorderLayout.CENTER);
    if (msg.trim().length() > 0) {
        textMessage = new BaseTextArea(msg.split("\n").length + 1, 40);
        textMessage.setText(msg);
        panelAll.add(new BaseScrollPane(textMessage), BorderLayout.NORTH);
    }
    panelOptions = new JPanel(new FlowLayout(FlowLayout.LEFT));
    checkBoxInvert = new BaseCheckBox("Remove selected attributes rather than keep them");
    panelOptions.add(checkBoxInvert);
    panelAll.add(panelOptions, BorderLayout.SOUTH);
    dialog = new ApprovalDialog(null, ModalityType.DOCUMENT_MODAL);
    dialog.setTitle("Choose attributes");
    dialog.getContentPane().add(panelAll, BorderLayout.CENTER);
    registerWindow(dialog, dialog.getTitle());
    dialog.pack();
    dialog.setLocationRelativeTo(getActualParentComponent());
    dialog.setVisible(true);
    deregisterWindow(dialog);

    if (dialog.getOption() != ApprovalDialog.APPROVE_OPTION)
        return null;

    if (checkBoxInvert.isSelected()) {
        range.setIndices(table.getSelectedRows());
        range.setInverted(true);
        result.addAll(Utils.toList(range.getIntIndices()));
    } else {
        result.addAll(Utils.toList(table.getSelectedRows()));
    }

    return result;
}

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

License:Open Source License

/**
 * Returns the pre-selected indices./*from  ww  w  .jav a 2s .  com*/
 * 
 * @param inst   the dataset to work on
 * @return      the indices
 */
protected List<Integer> getPreSelectedIndices(Instances inst) {
    List<Integer> result;
    int i;

    result = new ArrayList<>();
    for (i = 0; i < inst.numAttributes(); i++) {
        if (inst.classIndex() == i)
            continue;
        if (m_PreSelection.isMatch(inst.attribute(i).name()))
            result.add(i);
    }

    return result;
}

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

License:Open Source License

/**
 * Executes the flow item./*  w w  w  . j  a v  a 2 s  .  co m*/
 *
 * @return      null if everything is fine, otherwise error message
 */
@Override
protected String doExecute() {
    String result;
    Object o;
    weka.core.Instances inst;
    boolean isInstances;
    List<Attribute> atts;
    int i;

    result = null;

    // dataset
    o = m_InputToken.getPayload();
    isInstances = false;
    inst = null;
    if (o instanceof weka.core.Instances) {
        inst = (weka.core.Instances) o;
        inst = new weka.core.Instances(inst);
        isInstances = true;
    } else if (o instanceof adams.data.instance.Instance) {
        inst = ((adams.data.instance.Instance) o).getDatasetHeader();
    } else if (o instanceof weka.core.Instance) {
        inst = ((weka.core.Instance) o).dataset();
    } else {
        result = "Cannot handle object of type " + o.getClass().getName() + "!";
    }

    if (result == null) {
        if (m_Unset) {
            inst.setClassIndex(-1);
        } else {
            // determine the attributes that fit the regular expression
            atts = new ArrayList<Attribute>();
            for (i = 0; i < inst.numAttributes(); i++) {
                if (m_RegexName.isEmpty() || m_RegexName.isMatch(inst.attribute(i).name()))
                    atts.add(inst.attribute(i));
            }

            // class index
            m_ClassIndex.setMax(atts.size());
            if (m_Override || (inst.classIndex() == -1))
                inst.setClassIndex(atts.get(m_ClassIndex.getIntIndex()).index());
        }

        // output
        if (isInstances)
            m_OutputToken = new Token(inst);
        else
            m_OutputToken = new Token(o);

        updateProvenance(m_OutputToken);
    }

    return result;
}