Example usage for weka.core Instances numInstances

List of usage examples for weka.core Instances numInstances

Introduction

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

Prototype


publicint numInstances() 

Source Link

Document

Returns the number of instances in the dataset.

Usage

From source file:adams.data.instancesanalysis.pls.AbstractMultiClassPLS.java

License:Open Source License

/**
 * Postprocesses the data.//www  .j  a  va2s.co  m
 *
 * @param instances   the data to process
 * @return      the postprocessed data
 */
protected Instances postTransform(Instances instances, Map<String, Object> params) throws Exception {
    int i;
    int n;
    Map<Integer, double[]> classValues;
    double classValue;
    int index;

    classValues = (Map<Integer, double[]>) params.get(PARAM_CLASSVALUES);

    // add the mean to the class again if predictions are to be performed,
    // otherwise restore original class values
    for (i = 0; i < m_ClassAttributeIndices.size(); i++) {
        index = m_ClassAttributeIndices.get(i);
        for (n = 0; n < instances.numInstances(); n++) {
            if (classValues != null) {
                instances.instance(n).setClassValue(classValues.get(index)[n]);
            } else {
                classValue = instances.instance(n).classValue();
                instances.instance(n)
                        .setClassValue(classValue * m_ClassStdDev.get(index) + m_ClassMean.get(index));
            }
        }
    }

    return instances;
}

From source file:adams.data.instancesanalysis.pls.AbstractSingleClassPLS.java

License:Open Source License

/**
 * Postprocesses the data./*from  w w w  . ja v  a  2  s  .c  om*/
 *
 * @param instances   the data to process
 * @return      the postprocessed data
 */
protected Instances postTransform(Instances instances, Map<String, Object> params) throws Exception {
    int i;
    double[] classValues;
    double classValue;

    classValues = (double[]) params.get(PARAM_CLASSVALUES);

    // add the mean to the class again if predictions are to be performed,
    // otherwise restore original class values
    for (i = 0; i < instances.numInstances(); i++) {
        if (classValues != null) {
            instances.instance(i).setClassValue(classValues[i]);
        } else {
            classValue = instances.instance(i).classValue();
            instances.instance(i).setClassValue(classValue * m_ClassStdDev + m_ClassMean);
        }
    }

    return instances;
}

From source file:adams.data.instancesanalysis.pls.PLS1.java

License:Open Source License

/**
 * Performs predictions on the data.//w  w  w. ja va  2s.  c o m
 *
 * @param data   the input data
 * @return      the predicted data
 */
protected Instances predict(Instances data) {
    Instances result;
    Instances tmpInst;
    int i;
    int j;
    Matrix x;
    Matrix X;
    Matrix T;
    Matrix t;

    result = new Instances(getOutputFormat());

    for (i = 0; i < data.numInstances(); i++) {
        // work on each instance
        tmpInst = new Instances(data, 0);
        tmpInst.add((Instance) data.instance(i).copy());
        x = MatrixHelper.getX(tmpInst);
        X = new Matrix(1, getNumComponents());
        T = new Matrix(1, getNumComponents());

        for (j = 0; j < getNumComponents(); j++) {
            MatrixHelper.setVector(x, X, j);
            // 1. step: tj = xj * wj
            t = x.times(MatrixHelper.getVector(m_W, j));
            MatrixHelper.setVector(t, T, j);
            // 2. step: xj+1 = xj - tj*pj^T (tj is 1x1 matrix!)
            x = x.minus(MatrixHelper.getVector(m_P, j).transpose().times(t.get(0, 0)));
        }

        switch (m_PredictionType) {
        case ALL:
            tmpInst = MatrixHelper.toInstances(getOutputFormat(), T, T.times(m_b_hat));
            break;
        case NONE:
        case EXCEPT_CLASS:
            tmpInst = MatrixHelper.toInstances(getOutputFormat(), T, MatrixHelper.getY(tmpInst));
            break;
        default:
            throw new IllegalStateException("Unhandled prediction type: " + m_PredictionType);
        }

        result.add(tmpInst.instance(0));

    }

    return result;
}

From source file:adams.data.instancesanalysis.pls.PLS1.java

License:Open Source License

/**
 * Transforms the data, initializes if necessary.
 *
 * @param data   the data to use/*from ww  w  .ja  va 2 s.  c  o m*/
 */
protected Instances doTransform(Instances data, Map<String, Object> params) throws Exception {
    Matrix X, X_trans;
    Matrix y;
    Matrix W, w;
    Matrix T, t, t_trans;
    Matrix P, p, p_trans;
    double b;
    Matrix b_hat;
    int j;
    Matrix tmp;
    Instances result;

    // initialization
    if (!isInitialized()) {
        // split up data
        X = MatrixHelper.getX(data);
        y = MatrixHelper.getY(data);
        X_trans = X.transpose();

        // init
        W = new Matrix(data.numAttributes() - 1, getNumComponents());
        P = new Matrix(data.numAttributes() - 1, getNumComponents());
        T = new Matrix(data.numInstances(), getNumComponents());
        b_hat = new Matrix(getNumComponents(), 1);

        for (j = 0; j < getNumComponents(); j++) {
            // 1. step: wj
            w = X_trans.times(y);
            MatrixHelper.normalizeVector(w);
            MatrixHelper.setVector(w, W, j);

            // 2. step: tj
            t = X.times(w);
            t_trans = t.transpose();
            MatrixHelper.setVector(t, T, j);

            // 3. step: ^bj
            b = t_trans.times(y).get(0, 0) / t_trans.times(t).get(0, 0);
            b_hat.set(j, 0, b);

            // 4. step: pj
            p = X_trans.times(t).times(1 / t_trans.times(t).get(0, 0));
            p_trans = p.transpose();
            MatrixHelper.setVector(p, P, j);

            // 5. step: Xj+1
            X = X.minus(t.times(p_trans));
            y = y.minus(t.times(b));
        }

        // W*(P^T*W)^-1
        tmp = W.times(((P.transpose()).times(W)).inverse());

        // factor = W*(P^T*W)^-1 * b_hat
        m_r_hat = tmp.times(b_hat);

        // save matrices
        m_P = P;
        m_W = W;
        m_b_hat = b_hat;

        result = predict(data);
    }
    // prediction
    else {
        result = predict(data);
    }

    return result;
}

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

License:Open Source License

/**
 * Plots the token (the panel and dialog have already been created at
 * this stage)./* ww  w.  j  a  v  a  2s  . c  om*/
 *
 * @param token   the token to display
 */
@Override
protected void display(Token token) {
    Evaluation eval;
    Attribute classAtt;
    Attribute classAttToUse;
    int classValue;
    ThresholdCurve tc;
    Instances result;
    ArrayList<String> newNames;
    CostBenefitAnalysis cbAnalysis;
    PlotData2D tempd;
    boolean[] cp;
    int n;

    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;
        }
        classAtt = eval.getHeader().classAttribute();
        m_ClassIndex.setData(classAtt);
        classValue = m_ClassIndex.getIntIndex();
        tc = new ThresholdCurve();
        result = tc.getCurve(eval.predictions(), classValue);

        // Create a dummy class attribute with the chosen
        // class value as index 0 (if necessary).
        classAttToUse = eval.getHeader().classAttribute();
        if (classValue != 0) {
            newNames = new ArrayList<>();
            newNames.add(classAtt.value(classValue));
            for (int k = 0; k < classAtt.numValues(); k++) {
                if (k != classValue)
                    newNames.add(classAtt.value(k));
            }
            classAttToUse = new Attribute(classAtt.name(), newNames);
        }
        // assemble plot data
        tempd = new PlotData2D(result);
        tempd.setPlotName(result.relationName());
        tempd.m_alwaysDisplayPointsOfThisSize = 10;
        // specify which points are connected
        cp = new boolean[result.numInstances()];
        for (n = 1; n < cp.length; n++)
            cp[n] = true;
        tempd.setConnectPoints(cp);
        // add plot
        m_CostBenefitPanel.setCurveData(tempd, classAttToUse);
    } catch (Exception e) {
        handleException("Failed to display token: " + token, e);
    }
}

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

License:Open Source License

/**
 * Plots the token (the panel and dialog have already been created at
 * this stage)./*from w ww  .ja va2s .c  o  m*/
 *
 * @param token   the token to display
 */
@Override
protected void display(Token token) {
    weka.classifiers.evaluation.CostCurve 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 weka.classifiers.evaluation.CostCurve();
            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);
        }
    } catch (Exception e) {
        handleException("Failed to display token: " + token, e);
    }
}

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

License:Open Source License

/**
 * Creates a new panel for the token.// www .j av  a 2s.c om
 *
 * @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 = "Cost curve (" + getEvaluation(token).getHeader().relationName() + ")";
    else
        name = "Cost curve";

    result = new AbstractComponentDisplayPanel(name) {
        private static final long serialVersionUID = -3513994354297811163L;
        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) {
            try {
                Evaluation eval = getEvaluation(token);
                m_ClassLabelRange.setMax(eval.getHeader().classAttribute().numValues());
                int[] indices = m_ClassLabelRange.getIntIndices();
                for (int index : indices) {
                    weka.classifiers.evaluation.CostCurve curve = new weka.classifiers.evaluation.CostCurve();
                    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);
                }
            } 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.sink.WekaMarginCurve.java

License:Open Source License

/**
 * Plots the token (the panel and dialog have already been created at
 * this stage).//www  .  ja  va2  s . co  m
 *
 * @param token   the token to display
 */
@Override
protected void display(Token token) {
    weka.classifiers.evaluation.MarginCurve curve;
    Evaluation eval;
    PlotData2D plot;
    boolean[] connectPoints;
    int cp;
    Instances data;

    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;
        }
        curve = new weka.classifiers.evaluation.MarginCurve();
        data = curve.getCurve(eval.predictions());
        plot = new PlotData2D(data);
        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);
    } catch (Exception e) {
        handleException("Failed to display token: " + token, e);
    }
}

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

License:Open Source License

/**
 * Creates a new panel for the token./*from  www.  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 = "Margin curve (" + getEvaluation(token).getHeader().relationName() + ")";
    else
        name = "Margin curve";

    result = new AbstractComponentDisplayPanel(name) {
        private static final long serialVersionUID = -3513994354297811163L;
        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) {
            try {
                Evaluation eval = getEvaluation(token);
                weka.classifiers.evaluation.MarginCurve curve = new weka.classifiers.evaluation.MarginCurve();
                Instances data = curve.getCurve(eval.predictions());
                PlotData2D plot = new PlotData2D(data);
                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);
            } 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.sink.WekaThresholdCurve.java

License:Open Source License

/**
 * Plots the token (the panel and dialog have already been created at
 * this stage).// w  ww .  jav a 2 s  .  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);
    }
}