RegressionResults.java

  1. /*
  2.  * Licensed to the Apache Software Foundation (ASF) under one or more
  3.  * contributor license agreements.  See the NOTICE file distributed with
  4.  * this work for additional information regarding copyright ownership.
  5.  * The ASF licenses this file to You under the Apache License, Version 2.0
  6.  * (the "License"); you may not use this file except in compliance with
  7.  * the License.  You may obtain a copy of the License at
  8.  *
  9.  *      http://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the License for the specific language governing permissions and
  15.  * limitations under the License.
  16.  */
  17. package org.apache.commons.math3.stat.regression;

  18. import java.io.Serializable;
  19. import java.util.Arrays;
  20. import org.apache.commons.math3.util.FastMath;
  21. import org.apache.commons.math3.util.MathArrays;
  22. import org.apache.commons.math3.exception.OutOfRangeException;

  23. /**
  24.  * Results of a Multiple Linear Regression model fit.
  25.  *
  26.  * @since 3.0
  27.  */
  28. public class RegressionResults implements Serializable {

  29.     /** INDEX of Sum of Squared Errors */
  30.     private static final int SSE_IDX = 0;
  31.     /** INDEX of Sum of Squares of Model */
  32.     private static final int SST_IDX = 1;
  33.     /** INDEX of R-Squared of regression */
  34.     private static final int RSQ_IDX = 2;
  35.     /** INDEX of Mean Squared Error */
  36.     private static final int MSE_IDX = 3;
  37.     /** INDEX of Adjusted R Squared */
  38.     private static final int ADJRSQ_IDX = 4;
  39.     /** UID */
  40.     private static final long serialVersionUID = 1l;
  41.     /** regression slope parameters */
  42.     private final double[] parameters;
  43.     /** variance covariance matrix of parameters */
  44.     private final double[][] varCovData;
  45.     /** boolean flag for variance covariance matrix in symm compressed storage */
  46.     private final boolean isSymmetricVCD;
  47.     /** rank of the solution */
  48.     @SuppressWarnings("unused")
  49.     private final int rank;
  50.     /** number of observations on which results are based */
  51.     private final long nobs;
  52.     /** boolean flag indicator of whether a constant was included*/
  53.     private final boolean containsConstant;
  54.     /** array storing global results, SSE, MSE, RSQ, adjRSQ */
  55.     private final double[] globalFitInfo;

  56.     /**
  57.      *  Set the default constructor to private access
  58.      *  to prevent inadvertent instantiation
  59.      */
  60.     @SuppressWarnings("unused")
  61.     private RegressionResults() {
  62.         this.parameters = null;
  63.         this.varCovData = null;
  64.         this.rank = -1;
  65.         this.nobs = -1;
  66.         this.containsConstant = false;
  67.         this.isSymmetricVCD = false;
  68.         this.globalFitInfo = null;
  69.     }

  70.     /**
  71.      * Constructor for Regression Results.
  72.      *
  73.      * @param parameters a double array with the regression slope estimates
  74.      * @param varcov the variance covariance matrix, stored either in a square matrix
  75.      * or as a compressed
  76.      * @param isSymmetricCompressed a flag which denotes that the variance covariance
  77.      * matrix is in symmetric compressed format
  78.      * @param nobs the number of observations of the regression estimation
  79.      * @param rank the number of independent variables in the regression
  80.      * @param sumy the sum of the independent variable
  81.      * @param sumysq the sum of the squared independent variable
  82.      * @param sse sum of squared errors
  83.      * @param containsConstant true model has constant,  false model does not have constant
  84.      * @param copyData if true a deep copy of all input data is made, if false only references
  85.      * are copied and the RegressionResults become mutable
  86.      */
  87.     public RegressionResults(
  88.             final double[] parameters, final double[][] varcov,
  89.             final boolean isSymmetricCompressed,
  90.             final long nobs, final int rank,
  91.             final double sumy, final double sumysq, final double sse,
  92.             final boolean containsConstant,
  93.             final boolean copyData) {
  94.         if (copyData) {
  95.             this.parameters = MathArrays.copyOf(parameters);
  96.             this.varCovData = new double[varcov.length][];
  97.             for (int i = 0; i < varcov.length; i++) {
  98.                 this.varCovData[i] = MathArrays.copyOf(varcov[i]);
  99.             }
  100.         } else {
  101.             this.parameters = parameters;
  102.             this.varCovData = varcov;
  103.         }
  104.         this.isSymmetricVCD = isSymmetricCompressed;
  105.         this.nobs = nobs;
  106.         this.rank = rank;
  107.         this.containsConstant = containsConstant;
  108.         this.globalFitInfo = new double[5];
  109.         Arrays.fill(this.globalFitInfo, Double.NaN);

  110.         if (rank > 0) {
  111.             this.globalFitInfo[SST_IDX] = containsConstant ?
  112.                     (sumysq - sumy * sumy / nobs) : sumysq;
  113.         }

  114.         this.globalFitInfo[SSE_IDX] = sse;
  115.         this.globalFitInfo[MSE_IDX] = this.globalFitInfo[SSE_IDX] /
  116.                 (nobs - rank);
  117.         this.globalFitInfo[RSQ_IDX] = 1.0 -
  118.                 this.globalFitInfo[SSE_IDX] /
  119.                 this.globalFitInfo[SST_IDX];

  120.         if (!containsConstant) {
  121.             this.globalFitInfo[ADJRSQ_IDX] = 1.0-
  122.                     (1.0 - this.globalFitInfo[RSQ_IDX]) *
  123.                     ( (double) nobs / ( (double) (nobs - rank)));
  124.         } else {
  125.             this.globalFitInfo[ADJRSQ_IDX] = 1.0 - (sse * (nobs - 1.0)) /
  126.                     (globalFitInfo[SST_IDX] * (nobs - rank));
  127.         }
  128.     }

  129.     /**
  130.      * <p>Returns the parameter estimate for the regressor at the given index.</p>
  131.      *
  132.      * <p>A redundant regressor will have its redundancy flag set, as well as
  133.      *  a parameters estimated equal to {@code Double.NaN}</p>
  134.      *
  135.      * @param index Index.
  136.      * @return the parameters estimated for regressor at index.
  137.      * @throws OutOfRangeException if {@code index} is not in the interval
  138.      * {@code [0, number of parameters)}.
  139.      */
  140.     public double getParameterEstimate(int index) throws OutOfRangeException {
  141.         if (parameters == null) {
  142.             return Double.NaN;
  143.         }
  144.         if (index < 0 || index >= this.parameters.length) {
  145.             throw new OutOfRangeException(index, 0, this.parameters.length - 1);
  146.         }
  147.         return this.parameters[index];
  148.     }

  149.     /**
  150.      * <p>Returns a copy of the regression parameters estimates.</p>
  151.      *
  152.      * <p>The parameter estimates are returned in the natural order of the data.</p>
  153.      *
  154.      * <p>A redundant regressor will have its redundancy flag set, as will
  155.      *  a parameter estimate equal to {@code Double.NaN}.</p>
  156.      *
  157.      * @return array of parameter estimates, null if no estimation occurred
  158.      */
  159.     public double[] getParameterEstimates() {
  160.         if (this.parameters == null) {
  161.             return null;
  162.         }
  163.         return MathArrays.copyOf(parameters);
  164.     }

  165.     /**
  166.      * Returns the <a href="http://www.xycoon.com/standerrorb(1).htm">standard
  167.      * error of the parameter estimate at index</a>,
  168.      * usually denoted s(b<sub>index</sub>).
  169.      *
  170.      * @param index Index.
  171.      * @return the standard errors associated with parameters estimated at index.
  172.      * @throws OutOfRangeException if {@code index} is not in the interval
  173.      * {@code [0, number of parameters)}.
  174.      */
  175.     public double getStdErrorOfEstimate(int index) throws OutOfRangeException {
  176.         if (parameters == null) {
  177.             return Double.NaN;
  178.         }
  179.         if (index < 0 || index >= this.parameters.length) {
  180.             throw new OutOfRangeException(index, 0, this.parameters.length - 1);
  181.         }
  182.         double var = this.getVcvElement(index, index);
  183.         if (!Double.isNaN(var) && var > Double.MIN_VALUE) {
  184.             return FastMath.sqrt(var);
  185.         }
  186.         return Double.NaN;
  187.     }

  188.     /**
  189.      * <p>Returns the <a href="http://www.xycoon.com/standerrorb(1).htm">standard
  190.      * error of the parameter estimates</a>,
  191.      * usually denoted s(b<sub>i</sub>).</p>
  192.      *
  193.      * <p>If there are problems with an ill conditioned design matrix then the regressor
  194.      * which is redundant will be assigned <code>Double.NaN</code>. </p>
  195.      *
  196.      * @return an array standard errors associated with parameters estimates,
  197.      *  null if no estimation occurred
  198.      */
  199.     public double[] getStdErrorOfEstimates() {
  200.         if (parameters == null) {
  201.             return null;
  202.         }
  203.         double[] se = new double[this.parameters.length];
  204.         for (int i = 0; i < this.parameters.length; i++) {
  205.             double var = this.getVcvElement(i, i);
  206.             if (!Double.isNaN(var) && var > Double.MIN_VALUE) {
  207.                 se[i] = FastMath.sqrt(var);
  208.                 continue;
  209.             }
  210.             se[i] = Double.NaN;
  211.         }
  212.         return se;
  213.     }

  214.     /**
  215.      * <p>Returns the covariance between regression parameters i and j.</p>
  216.      *
  217.      * <p>If there are problems with an ill conditioned design matrix then the covariance
  218.      * which involves redundant columns will be assigned {@code Double.NaN}. </p>
  219.      *
  220.      * @param i {@code i}th regression parameter.
  221.      * @param j {@code j}th regression parameter.
  222.      * @return the covariance of the parameter estimates.
  223.      * @throws OutOfRangeException if {@code i} or {@code j} is not in the
  224.      * interval {@code [0, number of parameters)}.
  225.      */
  226.     public double getCovarianceOfParameters(int i, int j) throws OutOfRangeException {
  227.         if (parameters == null) {
  228.             return Double.NaN;
  229.         }
  230.         if (i < 0 || i >= this.parameters.length) {
  231.             throw new OutOfRangeException(i, 0, this.parameters.length - 1);
  232.         }
  233.         if (j < 0 || j >= this.parameters.length) {
  234.             throw new OutOfRangeException(j, 0, this.parameters.length - 1);
  235.         }
  236.         return this.getVcvElement(i, j);
  237.     }

  238.     /**
  239.      * <p>Returns the number of parameters estimated in the model.</p>
  240.      *
  241.      * <p>This is the maximum number of regressors, some techniques may drop
  242.      * redundant parameters</p>
  243.      *
  244.      * @return number of regressors, -1 if not estimated
  245.      */
  246.     public int getNumberOfParameters() {
  247.         if (this.parameters == null) {
  248.             return -1;
  249.         }
  250.         return this.parameters.length;
  251.     }

  252.     /**
  253.      * Returns the number of observations added to the regression model.
  254.      *
  255.      * @return Number of observations, -1 if an error condition prevents estimation
  256.      */
  257.     public long getN() {
  258.         return this.nobs;
  259.     }

  260.     /**
  261.      * <p>Returns the sum of squared deviations of the y values about their mean.</p>
  262.      *
  263.      * <p>This is defined as SSTO
  264.      * <a href="http://www.xycoon.com/SumOfSquares.htm">here</a>.</p>
  265.      *
  266.      * <p>If {@code n < 2}, this returns {@code Double.NaN}.</p>
  267.      *
  268.      * @return sum of squared deviations of y values
  269.      */
  270.     public double getTotalSumSquares() {
  271.         return this.globalFitInfo[SST_IDX];
  272.     }

  273.     /**
  274.      * <p>Returns the sum of squared deviations of the predicted y values about
  275.      * their mean (which equals the mean of y).</p>
  276.      *
  277.      * <p>This is usually abbreviated SSR or SSM.  It is defined as SSM
  278.      * <a href="http://www.xycoon.com/SumOfSquares.htm">here</a></p>
  279.      *
  280.      * <p><strong>Preconditions</strong>: <ul>
  281.      * <li>At least two observations (with at least two different x values)
  282.      * must have been added before invoking this method. If this method is
  283.      * invoked before a model can be estimated, <code>Double.NaN</code> is
  284.      * returned.
  285.      * </li></ul></p>
  286.      *
  287.      * @return sum of squared deviations of predicted y values
  288.      */
  289.     public double getRegressionSumSquares() {
  290.         return this.globalFitInfo[SST_IDX] - this.globalFitInfo[SSE_IDX];
  291.     }

  292.     /**
  293.      * <p>Returns the <a href="http://www.xycoon.com/SumOfSquares.htm">
  294.      * sum of squared errors</a> (SSE) associated with the regression
  295.      * model.</p>
  296.      *
  297.      * <p>The return value is constrained to be non-negative - i.e., if due to
  298.      * rounding errors the computational formula returns a negative result,
  299.      * 0 is returned.</p>
  300.      *
  301.      * <p><strong>Preconditions</strong>: <ul>
  302.      * <li>numberOfParameters data pairs
  303.      * must have been added before invoking this method. If this method is
  304.      * invoked before a model can be estimated, <code>Double,NaN</code> is
  305.      * returned.
  306.      * </li></ul></p>
  307.      *
  308.      * @return sum of squared errors associated with the regression model
  309.      */
  310.     public double getErrorSumSquares() {
  311.         return this.globalFitInfo[ SSE_IDX];
  312.     }

  313.     /**
  314.      * <p>Returns the sum of squared errors divided by the degrees of freedom,
  315.      * usually abbreviated MSE.</p>
  316.      *
  317.      * <p>If there are fewer than <strong>numberOfParameters + 1</strong> data pairs in the model,
  318.      * or if there is no variation in <code>x</code>, this returns
  319.      * <code>Double.NaN</code>.</p>
  320.      *
  321.      * @return sum of squared deviations of y values
  322.      */
  323.     public double getMeanSquareError() {
  324.         return this.globalFitInfo[ MSE_IDX];
  325.     }

  326.     /**
  327.      * <p>Returns the <a href="http://www.xycoon.com/coefficient1.htm">
  328.      * coefficient of multiple determination</a>,
  329.      * usually denoted r-square.</p>
  330.      *
  331.      * <p><strong>Preconditions</strong>: <ul>
  332.      * <li>At least numberOfParameters observations (with at least numberOfParameters different x values)
  333.      * must have been added before invoking this method. If this method is
  334.      * invoked before a model can be estimated, {@code Double,NaN} is
  335.      * returned.
  336.      * </li></ul></p>
  337.      *
  338.      * @return r-square, a double in the interval [0, 1]
  339.      */
  340.     public double getRSquared() {
  341.         return this.globalFitInfo[ RSQ_IDX];
  342.     }

  343.     /**
  344.      * <p>Returns the adjusted R-squared statistic, defined by the formula <pre>
  345.      * R<sup>2</sup><sub>adj</sub> = 1 - [SSR (n - 1)] / [SSTO (n - p)]
  346.      * </pre>
  347.      * where SSR is the sum of squared residuals},
  348.      * SSTO is the total sum of squares}, n is the number
  349.      * of observations and p is the number of parameters estimated (including the intercept).</p>
  350.      *
  351.      * <p>If the regression is estimated without an intercept term, what is returned is <pre>
  352.      * <code> 1 - (1 - {@link #getRSquared()} ) * (n / (n - p)) </code>
  353.      * </pre></p>
  354.      *
  355.      * @return adjusted R-Squared statistic
  356.      */
  357.     public double getAdjustedRSquared() {
  358.         return this.globalFitInfo[ ADJRSQ_IDX];
  359.     }

  360.     /**
  361.      * Returns true if the regression model has been computed including an intercept.
  362.      * In this case, the coefficient of the intercept is the first element of the
  363.      * {@link #getParameterEstimates() parameter estimates}.
  364.      * @return true if the model has an intercept term
  365.      */
  366.     public boolean hasIntercept() {
  367.         return this.containsConstant;
  368.     }

  369.     /**
  370.      * Gets the i-jth element of the variance-covariance matrix.
  371.      *
  372.      * @param i first variable index
  373.      * @param j second variable index
  374.      * @return the requested variance-covariance matrix entry
  375.      */
  376.     private double getVcvElement(int i, int j) {
  377.         if (this.isSymmetricVCD) {
  378.             if (this.varCovData.length > 1) {
  379.                 //could be stored in upper or lower triangular
  380.                 if (i == j) {
  381.                     return varCovData[i][i];
  382.                 } else if (i >= varCovData[j].length) {
  383.                     return varCovData[i][j];
  384.                 } else {
  385.                     return varCovData[j][i];
  386.                 }
  387.             } else {//could be in single array
  388.                 if (i > j) {
  389.                     return varCovData[0][(i + 1) * i / 2 + j];
  390.                 } else {
  391.                     return varCovData[0][(j + 1) * j / 2 + i];
  392.                 }
  393.             }
  394.         } else {
  395.             return this.varCovData[i][j];
  396.         }
  397.     }
  398. }