AbstractMultipleLinearRegression.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 org.apache.commons.math3.exception.DimensionMismatchException;
  19. import org.apache.commons.math3.exception.InsufficientDataException;
  20. import org.apache.commons.math3.exception.MathIllegalArgumentException;
  21. import org.apache.commons.math3.exception.NoDataException;
  22. import org.apache.commons.math3.exception.NullArgumentException;
  23. import org.apache.commons.math3.exception.util.LocalizedFormats;
  24. import org.apache.commons.math3.linear.NonSquareMatrixException;
  25. import org.apache.commons.math3.linear.RealMatrix;
  26. import org.apache.commons.math3.linear.Array2DRowRealMatrix;
  27. import org.apache.commons.math3.linear.RealVector;
  28. import org.apache.commons.math3.linear.ArrayRealVector;
  29. import org.apache.commons.math3.stat.descriptive.moment.Variance;
  30. import org.apache.commons.math3.util.FastMath;

  31. /**
  32.  * Abstract base class for implementations of MultipleLinearRegression.
  33.  * @since 2.0
  34.  */
  35. public abstract class AbstractMultipleLinearRegression implements
  36.         MultipleLinearRegression {

  37.     /** X sample data. */
  38.     private RealMatrix xMatrix;

  39.     /** Y sample data. */
  40.     private RealVector yVector;

  41.     /** Whether or not the regression model includes an intercept.  True means no intercept. */
  42.     private boolean noIntercept = false;

  43.     /**
  44.      * @return the X sample data.
  45.      */
  46.     protected RealMatrix getX() {
  47.         return xMatrix;
  48.     }

  49.     /**
  50.      * @return the Y sample data.
  51.      */
  52.     protected RealVector getY() {
  53.         return yVector;
  54.     }

  55.     /**
  56.      * @return true if the model has no intercept term; false otherwise
  57.      * @since 2.2
  58.      */
  59.     public boolean isNoIntercept() {
  60.         return noIntercept;
  61.     }

  62.     /**
  63.      * @param noIntercept true means the model is to be estimated without an intercept term
  64.      * @since 2.2
  65.      */
  66.     public void setNoIntercept(boolean noIntercept) {
  67.         this.noIntercept = noIntercept;
  68.     }

  69.     /**
  70.      * <p>Loads model x and y sample data from a flat input array, overriding any previous sample.
  71.      * </p>
  72.      * <p>Assumes that rows are concatenated with y values first in each row.  For example, an input
  73.      * <code>data</code> array containing the sequence of values (1, 2, 3, 4, 5, 6, 7, 8, 9) with
  74.      * <code>nobs = 3</code> and <code>nvars = 2</code> creates a regression dataset with two
  75.      * independent variables, as below:
  76.      * <pre>
  77.      *   y   x[0]  x[1]
  78.      *   --------------
  79.      *   1     2     3
  80.      *   4     5     6
  81.      *   7     8     9
  82.      * </pre>
  83.      * </p>
  84.      * <p>Note that there is no need to add an initial unitary column (column of 1's) when
  85.      * specifying a model including an intercept term.  If {@link #isNoIntercept()} is <code>true</code>,
  86.      * the X matrix will be created without an initial column of "1"s; otherwise this column will
  87.      * be added.
  88.      * </p>
  89.      * <p>Throws IllegalArgumentException if any of the following preconditions fail:
  90.      * <ul><li><code>data</code> cannot be null</li>
  91.      * <li><code>data.length = nobs * (nvars + 1)</li>
  92.      * <li><code>nobs > nvars</code></li></ul>
  93.      * </p>
  94.      *
  95.      * @param data input data array
  96.      * @param nobs number of observations (rows)
  97.      * @param nvars number of independent variables (columns, not counting y)
  98.      * @throws NullArgumentException if the data array is null
  99.      * @throws DimensionMismatchException if the length of the data array is not equal
  100.      * to <code>nobs * (nvars + 1)</code>
  101.      * @throws InsufficientDataException if <code>nobs</code> is less than
  102.      * <code>nvars + 1</code>
  103.      */
  104.     public void newSampleData(double[] data, int nobs, int nvars) {
  105.         if (data == null) {
  106.             throw new NullArgumentException();
  107.         }
  108.         if (data.length != nobs * (nvars + 1)) {
  109.             throw new DimensionMismatchException(data.length, nobs * (nvars + 1));
  110.         }
  111.         if (nobs <= nvars) {
  112.             throw new InsufficientDataException(LocalizedFormats.INSUFFICIENT_OBSERVED_POINTS_IN_SAMPLE, nobs, nvars + 1);
  113.         }
  114.         double[] y = new double[nobs];
  115.         final int cols = noIntercept ? nvars: nvars + 1;
  116.         double[][] x = new double[nobs][cols];
  117.         int pointer = 0;
  118.         for (int i = 0; i < nobs; i++) {
  119.             y[i] = data[pointer++];
  120.             if (!noIntercept) {
  121.                 x[i][0] = 1.0d;
  122.             }
  123.             for (int j = noIntercept ? 0 : 1; j < cols; j++) {
  124.                 x[i][j] = data[pointer++];
  125.             }
  126.         }
  127.         this.xMatrix = new Array2DRowRealMatrix(x);
  128.         this.yVector = new ArrayRealVector(y);
  129.     }

  130.     /**
  131.      * Loads new y sample data, overriding any previous data.
  132.      *
  133.      * @param y the array representing the y sample
  134.      * @throws NullArgumentException if y is null
  135.      * @throws NoDataException if y is empty
  136.      */
  137.     protected void newYSampleData(double[] y) {
  138.         if (y == null) {
  139.             throw new NullArgumentException();
  140.         }
  141.         if (y.length == 0) {
  142.             throw new NoDataException();
  143.         }
  144.         this.yVector = new ArrayRealVector(y);
  145.     }

  146.     /**
  147.      * <p>Loads new x sample data, overriding any previous data.
  148.      * </p>
  149.      * The input <code>x</code> array should have one row for each sample
  150.      * observation, with columns corresponding to independent variables.
  151.      * For example, if <pre>
  152.      * <code> x = new double[][] {{1, 2}, {3, 4}, {5, 6}} </code></pre>
  153.      * then <code>setXSampleData(x) </code> results in a model with two independent
  154.      * variables and 3 observations:
  155.      * <pre>
  156.      *   x[0]  x[1]
  157.      *   ----------
  158.      *     1    2
  159.      *     3    4
  160.      *     5    6
  161.      * </pre>
  162.      * </p>
  163.      * <p>Note that there is no need to add an initial unitary column (column of 1's) when
  164.      * specifying a model including an intercept term.
  165.      * </p>
  166.      * @param x the rectangular array representing the x sample
  167.      * @throws NullArgumentException if x is null
  168.      * @throws NoDataException if x is empty
  169.      * @throws DimensionMismatchException if x is not rectangular
  170.      */
  171.     protected void newXSampleData(double[][] x) {
  172.         if (x == null) {
  173.             throw new NullArgumentException();
  174.         }
  175.         if (x.length == 0) {
  176.             throw new NoDataException();
  177.         }
  178.         if (noIntercept) {
  179.             this.xMatrix = new Array2DRowRealMatrix(x, true);
  180.         } else { // Augment design matrix with initial unitary column
  181.             final int nVars = x[0].length;
  182.             final double[][] xAug = new double[x.length][nVars + 1];
  183.             for (int i = 0; i < x.length; i++) {
  184.                 if (x[i].length != nVars) {
  185.                     throw new DimensionMismatchException(x[i].length, nVars);
  186.                 }
  187.                 xAug[i][0] = 1.0d;
  188.                 System.arraycopy(x[i], 0, xAug[i], 1, nVars);
  189.             }
  190.             this.xMatrix = new Array2DRowRealMatrix(xAug, false);
  191.         }
  192.     }

  193.     /**
  194.      * Validates sample data.  Checks that
  195.      * <ul><li>Neither x nor y is null or empty;</li>
  196.      * <li>The length (i.e. number of rows) of x equals the length of y</li>
  197.      * <li>x has at least one more row than it has columns (i.e. there is
  198.      * sufficient data to estimate regression coefficients for each of the
  199.      * columns in x plus an intercept.</li>
  200.      * </ul>
  201.      *
  202.      * @param x the [n,k] array representing the x data
  203.      * @param y the [n,1] array representing the y data
  204.      * @throws NullArgumentException if {@code x} or {@code y} is null
  205.      * @throws DimensionMismatchException if {@code x} and {@code y} do not
  206.      * have the same length
  207.      * @throws NoDataException if {@code x} or {@code y} are zero-length
  208.      * @throws MathIllegalArgumentException if the number of rows of {@code x}
  209.      * is not larger than the number of columns + 1
  210.      */
  211.     protected void validateSampleData(double[][] x, double[] y) throws MathIllegalArgumentException {
  212.         if ((x == null) || (y == null)) {
  213.             throw new NullArgumentException();
  214.         }
  215.         if (x.length != y.length) {
  216.             throw new DimensionMismatchException(y.length, x.length);
  217.         }
  218.         if (x.length == 0) {  // Must be no y data either
  219.             throw new NoDataException();
  220.         }
  221.         if (x[0].length + 1 > x.length) {
  222.             throw new MathIllegalArgumentException(
  223.                     LocalizedFormats.NOT_ENOUGH_DATA_FOR_NUMBER_OF_PREDICTORS,
  224.                     x.length, x[0].length);
  225.         }
  226.     }

  227.     /**
  228.      * Validates that the x data and covariance matrix have the same
  229.      * number of rows and that the covariance matrix is square.
  230.      *
  231.      * @param x the [n,k] array representing the x sample
  232.      * @param covariance the [n,n] array representing the covariance matrix
  233.      * @throws DimensionMismatchException if the number of rows in x is not equal
  234.      * to the number of rows in covariance
  235.      * @throws NonSquareMatrixException if the covariance matrix is not square
  236.      */
  237.     protected void validateCovarianceData(double[][] x, double[][] covariance) {
  238.         if (x.length != covariance.length) {
  239.             throw new DimensionMismatchException(x.length, covariance.length);
  240.         }
  241.         if (covariance.length > 0 && covariance.length != covariance[0].length) {
  242.             throw new NonSquareMatrixException(covariance.length, covariance[0].length);
  243.         }
  244.     }

  245.     /**
  246.      * {@inheritDoc}
  247.      */
  248.     public double[] estimateRegressionParameters() {
  249.         RealVector b = calculateBeta();
  250.         return b.toArray();
  251.     }

  252.     /**
  253.      * {@inheritDoc}
  254.      */
  255.     public double[] estimateResiduals() {
  256.         RealVector b = calculateBeta();
  257.         RealVector e = yVector.subtract(xMatrix.operate(b));
  258.         return e.toArray();
  259.     }

  260.     /**
  261.      * {@inheritDoc}
  262.      */
  263.     public double[][] estimateRegressionParametersVariance() {
  264.         return calculateBetaVariance().getData();
  265.     }

  266.     /**
  267.      * {@inheritDoc}
  268.      */
  269.     public double[] estimateRegressionParametersStandardErrors() {
  270.         double[][] betaVariance = estimateRegressionParametersVariance();
  271.         double sigma = calculateErrorVariance();
  272.         int length = betaVariance[0].length;
  273.         double[] result = new double[length];
  274.         for (int i = 0; i < length; i++) {
  275.             result[i] = FastMath.sqrt(sigma * betaVariance[i][i]);
  276.         }
  277.         return result;
  278.     }

  279.     /**
  280.      * {@inheritDoc}
  281.      */
  282.     public double estimateRegressandVariance() {
  283.         return calculateYVariance();
  284.     }

  285.     /**
  286.      * Estimates the variance of the error.
  287.      *
  288.      * @return estimate of the error variance
  289.      * @since 2.2
  290.      */
  291.     public double estimateErrorVariance() {
  292.         return calculateErrorVariance();

  293.     }

  294.     /**
  295.      * Estimates the standard error of the regression.
  296.      *
  297.      * @return regression standard error
  298.      * @since 2.2
  299.      */
  300.     public double estimateRegressionStandardError() {
  301.         return FastMath.sqrt(estimateErrorVariance());
  302.     }

  303.     /**
  304.      * Calculates the beta of multiple linear regression in matrix notation.
  305.      *
  306.      * @return beta
  307.      */
  308.     protected abstract RealVector calculateBeta();

  309.     /**
  310.      * Calculates the beta variance of multiple linear regression in matrix
  311.      * notation.
  312.      *
  313.      * @return beta variance
  314.      */
  315.     protected abstract RealMatrix calculateBetaVariance();


  316.     /**
  317.      * Calculates the variance of the y values.
  318.      *
  319.      * @return Y variance
  320.      */
  321.     protected double calculateYVariance() {
  322.         return new Variance().evaluate(yVector.toArray());
  323.     }

  324.     /**
  325.      * <p>Calculates the variance of the error term.</p>
  326.      * Uses the formula <pre>
  327.      * var(u) = u &middot; u / (n - k)
  328.      * </pre>
  329.      * where n and k are the row and column dimensions of the design
  330.      * matrix X.
  331.      *
  332.      * @return error variance estimate
  333.      * @since 2.2
  334.      */
  335.     protected double calculateErrorVariance() {
  336.         RealVector residuals = calculateResiduals();
  337.         return residuals.dotProduct(residuals) /
  338.                (xMatrix.getRowDimension() - xMatrix.getColumnDimension());
  339.     }

  340.     /**
  341.      * Calculates the residuals of multiple linear regression in matrix
  342.      * notation.
  343.      *
  344.      * <pre>
  345.      * u = y - X * b
  346.      * </pre>
  347.      *
  348.      * @return The residuals [n,1] matrix
  349.      */
  350.     protected RealVector calculateResiduals() {
  351.         RealVector b = calculateBeta();
  352.         return yVector.subtract(xMatrix.operate(b));
  353.     }

  354. }