001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.commons.math3.stat.regression;
018
019import org.apache.commons.math3.exception.MathIllegalArgumentException;
020import org.apache.commons.math3.linear.Array2DRowRealMatrix;
021import org.apache.commons.math3.linear.LUDecomposition;
022import org.apache.commons.math3.linear.QRDecomposition;
023import org.apache.commons.math3.linear.RealMatrix;
024import org.apache.commons.math3.linear.RealVector;
025import org.apache.commons.math3.stat.StatUtils;
026import org.apache.commons.math3.stat.descriptive.moment.SecondMoment;
027
028/**
029 * <p>Implements ordinary least squares (OLS) to estimate the parameters of a
030 * multiple linear regression model.</p>
031 *
032 * <p>The regression coefficients, <code>b</code>, satisfy the normal equations:
033 * <pre><code> X<sup>T</sup> X b = X<sup>T</sup> y </code></pre></p>
034 *
035 * <p>To solve the normal equations, this implementation uses QR decomposition
036 * of the <code>X</code> matrix. (See {@link QRDecomposition} for details on the
037 * decomposition algorithm.) The <code>X</code> matrix, also known as the <i>design matrix,</i>
038 * has rows corresponding to sample observations and columns corresponding to independent
039 * variables.  When the model is estimated using an intercept term (i.e. when
040 * {@link #isNoIntercept() isNoIntercept} is false as it is by default), the <code>X</code>
041 * matrix includes an initial column identically equal to 1.  We solve the normal equations
042 * as follows:
043 * <pre><code> X<sup>T</sup>X b = X<sup>T</sup> y
044 * (QR)<sup>T</sup> (QR) b = (QR)<sup>T</sup>y
045 * R<sup>T</sup> (Q<sup>T</sup>Q) R b = R<sup>T</sup> Q<sup>T</sup> y
046 * R<sup>T</sup> R b = R<sup>T</sup> Q<sup>T</sup> y
047 * (R<sup>T</sup>)<sup>-1</sup> R<sup>T</sup> R b = (R<sup>T</sup>)<sup>-1</sup> R<sup>T</sup> Q<sup>T</sup> y
048 * R b = Q<sup>T</sup> y </code></pre></p>
049 *
050 * <p>Given <code>Q</code> and <code>R</code>, the last equation is solved by back-substitution.</p>
051 *
052 * @since 2.0
053 */
054public class OLSMultipleLinearRegression extends AbstractMultipleLinearRegression {
055
056    /** Cached QR decomposition of X matrix */
057    private QRDecomposition qr = null;
058
059    /** Singularity threshold for QR decomposition */
060    private final double threshold;
061
062    /**
063     * Create an empty OLSMultipleLinearRegression instance.
064     */
065    public OLSMultipleLinearRegression() {
066        this(0d);
067    }
068
069    /**
070     * Create an empty OLSMultipleLinearRegression instance, using the given
071     * singularity threshold for the QR decomposition.
072     *
073     * @param threshold the singularity threshold
074     * @since 3.3
075     */
076    public OLSMultipleLinearRegression(final double threshold) {
077        this.threshold = threshold;
078    }
079
080    /**
081     * Loads model x and y sample data, overriding any previous sample.
082     *
083     * Computes and caches QR decomposition of the X matrix.
084     * @param y the [n,1] array representing the y sample
085     * @param x the [n,k] array representing the x sample
086     * @throws MathIllegalArgumentException if the x and y array data are not
087     *             compatible for the regression
088     */
089    public void newSampleData(double[] y, double[][] x) throws MathIllegalArgumentException {
090        validateSampleData(x, y);
091        newYSampleData(y);
092        newXSampleData(x);
093    }
094
095    /**
096     * {@inheritDoc}
097     * <p>This implementation computes and caches the QR decomposition of the X matrix.</p>
098     */
099    @Override
100    public void newSampleData(double[] data, int nobs, int nvars) {
101        super.newSampleData(data, nobs, nvars);
102        qr = new QRDecomposition(getX(), threshold);
103    }
104
105    /**
106     * <p>Compute the "hat" matrix.
107     * </p>
108     * <p>The hat matrix is defined in terms of the design matrix X
109     *  by X(X<sup>T</sup>X)<sup>-1</sup>X<sup>T</sup>
110     * </p>
111     * <p>The implementation here uses the QR decomposition to compute the
112     * hat matrix as Q I<sub>p</sub>Q<sup>T</sup> where I<sub>p</sub> is the
113     * p-dimensional identity matrix augmented by 0's.  This computational
114     * formula is from "The Hat Matrix in Regression and ANOVA",
115     * David C. Hoaglin and Roy E. Welsch,
116     * <i>The American Statistician</i>, Vol. 32, No. 1 (Feb., 1978), pp. 17-22.
117     * </p>
118     * <p>Data for the model must have been successfully loaded using one of
119     * the {@code newSampleData} methods before invoking this method; otherwise
120     * a {@code NullPointerException} will be thrown.</p>
121     *
122     * @return the hat matrix
123     * @throws NullPointerException unless method {@code newSampleData} has been
124     * called beforehand.
125     */
126    public RealMatrix calculateHat() {
127        // Create augmented identity matrix
128        RealMatrix Q = qr.getQ();
129        final int p = qr.getR().getColumnDimension();
130        final int n = Q.getColumnDimension();
131        // No try-catch or advertised NotStrictlyPositiveException - NPE above if n < 3
132        Array2DRowRealMatrix augI = new Array2DRowRealMatrix(n, n);
133        double[][] augIData = augI.getDataRef();
134        for (int i = 0; i < n; i++) {
135            for (int j =0; j < n; j++) {
136                if (i == j && i < p) {
137                    augIData[i][j] = 1d;
138                } else {
139                    augIData[i][j] = 0d;
140                }
141            }
142        }
143
144        // Compute and return Hat matrix
145        // No DME advertised - args valid if we get here
146        return Q.multiply(augI).multiply(Q.transpose());
147    }
148
149    /**
150     * <p>Returns the sum of squared deviations of Y from its mean.</p>
151     *
152     * <p>If the model has no intercept term, <code>0</code> is used for the
153     * mean of Y - i.e., what is returned is the sum of the squared Y values.</p>
154     *
155     * <p>The value returned by this method is the SSTO value used in
156     * the {@link #calculateRSquared() R-squared} computation.</p>
157     *
158     * @return SSTO - the total sum of squares
159     * @throws MathIllegalArgumentException if the sample has not been set or does
160     * not contain at least 3 observations
161     * @see #isNoIntercept()
162     * @since 2.2
163     */
164    public double calculateTotalSumOfSquares() throws MathIllegalArgumentException {
165        if (isNoIntercept()) {
166            return StatUtils.sumSq(getY().toArray());
167        } else {
168            return new SecondMoment().evaluate(getY().toArray());
169        }
170    }
171
172    /**
173     * Returns the sum of squared residuals.
174     *
175     * @return residual sum of squares
176     * @since 2.2
177     */
178    public double calculateResidualSumOfSquares() {
179        final RealVector residuals = calculateResiduals();
180        // No advertised DME, args are valid
181        return residuals.dotProduct(residuals);
182    }
183
184    /**
185     * Returns the R-Squared statistic, defined by the formula <pre>
186     * R<sup>2</sup> = 1 - SSR / SSTO
187     * </pre>
188     * where SSR is the {@link #calculateResidualSumOfSquares() sum of squared residuals}
189     * and SSTO is the {@link #calculateTotalSumOfSquares() total sum of squares}
190     *
191     * @return R-square statistic
192     * @throws MathIllegalArgumentException if the sample has not been set or does
193     * not contain at least 3 observations
194     * @since 2.2
195     */
196    public double calculateRSquared() throws MathIllegalArgumentException {
197        return 1 - calculateResidualSumOfSquares() / calculateTotalSumOfSquares();
198    }
199
200    /**
201     * <p>Returns the adjusted R-squared statistic, defined by the formula <pre>
202     * R<sup>2</sup><sub>adj</sub> = 1 - [SSR (n - 1)] / [SSTO (n - p)]
203     * </pre>
204     * where SSR is the {@link #calculateResidualSumOfSquares() sum of squared residuals},
205     * SSTO is the {@link #calculateTotalSumOfSquares() total sum of squares}, n is the number
206     * of observations and p is the number of parameters estimated (including the intercept).</p>
207     *
208     * <p>If the regression is estimated without an intercept term, what is returned is <pre>
209     * <code> 1 - (1 - {@link #calculateRSquared()}) * (n / (n - p)) </code>
210     * </pre></p>
211     *
212     * @return adjusted R-Squared statistic
213     * @throws MathIllegalArgumentException if the sample has not been set or does
214     * not contain at least 3 observations
215     * @see #isNoIntercept()
216     * @since 2.2
217     */
218    public double calculateAdjustedRSquared() throws MathIllegalArgumentException {
219        final double n = getX().getRowDimension();
220        if (isNoIntercept()) {
221            return 1 - (1 - calculateRSquared()) * (n / (n - getX().getColumnDimension()));
222        } else {
223            return 1 - (calculateResidualSumOfSquares() * (n - 1)) /
224                (calculateTotalSumOfSquares() * (n - getX().getColumnDimension()));
225        }
226    }
227
228    /**
229     * {@inheritDoc}
230     * <p>This implementation computes and caches the QR decomposition of the X matrix
231     * once it is successfully loaded.</p>
232     */
233    @Override
234    protected void newXSampleData(double[][] x) {
235        super.newXSampleData(x);
236        qr = new QRDecomposition(getX());
237    }
238
239    /**
240     * Calculates the regression coefficients using OLS.
241     *
242     * <p>Data for the model must have been successfully loaded using one of
243     * the {@code newSampleData} methods before invoking this method; otherwise
244     * a {@code NullPointerException} will be thrown.</p>
245     *
246     * @return beta
247     */
248    @Override
249    protected RealVector calculateBeta() {
250        return qr.getSolver().solve(getY());
251    }
252
253    /**
254     * <p>Calculates the variance-covariance matrix of the regression parameters.
255     * </p>
256     * <p>Var(b) = (X<sup>T</sup>X)<sup>-1</sup>
257     * </p>
258     * <p>Uses QR decomposition to reduce (X<sup>T</sup>X)<sup>-1</sup>
259     * to (R<sup>T</sup>R)<sup>-1</sup>, with only the top p rows of
260     * R included, where p = the length of the beta vector.</p>
261     *
262     * <p>Data for the model must have been successfully loaded using one of
263     * the {@code newSampleData} methods before invoking this method; otherwise
264     * a {@code NullPointerException} will be thrown.</p>
265     *
266     * @return The beta variance-covariance matrix
267     */
268    @Override
269    protected RealMatrix calculateBetaVariance() {
270        int p = getX().getColumnDimension();
271        RealMatrix Raug = qr.getR().getSubMatrix(0, p - 1 , 0, p - 1);
272        RealMatrix Rinv = new LUDecomposition(Raug).getSolver().getInverse();
273        return Rinv.multiply(Rinv.transpose());
274    }
275
276}