Regression

Linear regression

Least squares has a closed form, so with rational data the coefficients, fitted values, residuals and R² come out as exact fractions. Only the inference on top of them (p-values, interval ends) needs the certified distributions.

A line through the data

// hours of study and exam score for ten students
const hours = [1, 2, 2, 3, 4, 5, 5, 6, 7, 8];
const score = [52, 55, 61, 60, 68, 70, 74, 75, 83, 86];
import { linearModel, show } from "@ratmath/stats";

const m = linearModel(hours, score);
String(m);         // "y = 22847/481 + 2338/481·x  (n = 10, R² = 1366561/1412216)"
m.coefficients;    // [22847/481, 2338/481]: about 47.50 and 4.861
m.variance;        // 9131/1924: s², the residual variance on n − p = 8 degrees of freedom
m.table();         // estimate, standard error, t and p-value for each coefficient
m.interval("x");   // slope between 4.1364 and 5.5850 (95%)
m.fTest();         // F test of the whole regression

With a design matrix XX (a column of ones for the intercept, then one column per predictor) and responses yy, least squares minimises ∥y−Xβ∥2\lVert y - X\beta \rVert^2. The minimiser solves the normal equations

X⊤X β^=X⊤y. X^\top X\, \hat\beta = X^\top y.

The package forms X⊤XX^\top X exactly and inverts it by Gauss–Jordan elimination over the rationals, so β^\hat\beta, the fitted values y^=Xβ^\hat y = X\hat\beta and the residuals e=y−y^e = y - \hat y are exact. So are the sums of squares SSE=∑ei2SSE = \sum e_i^2, SST=∑(yi−yˉ)2SST = \sum (y_i - \bar y)^2, R2=1−SSE/SSTR^2 = 1 - SSE/SST and the residual variance s2=SSE/(n−p)s^2 = SSE/(n-p). If one column is a linear combination of the others X⊤XX^\top X is singular; the fit refuses with code "collinear" and names the column that breaks the rank.

Inference on the coefficients

Under the usual model, y=Xβ+εy = X\beta + \varepsilon with independent N(0,σ2)N(0, \sigma^2) errors, β^\hat\beta is normal with covariance σ2(X⊤X)−1\sigma^2 (X^\top X)^{-1}. Replacing σ2\sigma^2 by s2s^2 gives, for each coefficient,

tj=β^j−bs[(X⊤X)−1]jj∼tn−p. t_j = \frac{\hat\beta_j - b}{s\sqrt{[(X^\top X)^{-1}]_{jj}}} \sim t_{n-p}.

As with the t tests, tj2t_j^2 is exact and the p-value comes from F(1,n−p)F(1, n-p) at that exact argument. The overall F test compares the model with the intercept alone: F=SSR/(p−1)SSE/(n−p)F = \frac{SSR/(p-1)}{SSE/(n-p)}, an exact fraction.

Predicting

m.predict(6);                                   // 36875/481 ≈ 76.66
m.predictionInterval(6);                        // the mean score at 6 hours: [74.6532, 78.6732]
m.predictionInterval(6, { kind: "new" });       // one new student: [71.2524, 82.0740]

At a new point x0x_0 (with its leading 1), the fitted mean x0⊤β^x_0^\top\hat\beta has standard error sh0s\sqrt{h_0} with h0=x0⊤(X⊤X)−1x0h_0 = x_0^\top (X^\top X)^{-1} x_0. A single new observation adds its own noise, so its interval uses s1+h0s\sqrt{1 + h_0} and is always wider: it never shrinks to zero however much data there is.

Leverage and influence

m.leverage;               // the diagonal of the hat matrix, exact: 157/481, 101/481, …, 5/13
m.standardizedResiduals();// eᵢ / (s√(1 − hᵢ))
m.cooksDistance;          // the third student (2 hours, 61 points) has the most influence: 0.506

The hat matrix H=X(X⊤X)−1X⊤H = X(X^\top X)^{-1}X^\top maps yy to y^\hat y; its diagonal entries hih_i, the leverages, lie in [0,1][0, 1], sum to pp, and measure how far point ii sits from the others in predictor space. Cook's distance

Di=ei2p s2⋅hi(1−hi)2 D_i = \frac{e_i^2}{p\, s^2} \cdot \frac{h_i}{(1 - h_i)^2}

measures how far all the fitted values move when point ii is left out; the test suite checks this formula against refitting without each point. Both are exact here.

Several predictors, and curves

const house = linearModel({ size: [50, 70, 80, 100, 120, 60, 90, 110], rooms: [2, 3, 3, 4, 4, 2, 3, 5] },
                          [150, 200, 230, 270, 330, 165, 250, 300]);
String(house);   // "y = 8405/472 + 1231/472·size − 95/118·rooms  (n = 8, R² = 526772/529525)"
house.predict({ size: 85, rooms: 3 });   // 27975/118
// rooms adds nothing once size is known: p = 0.8667

const q2 = polyFit([0, 1, 2, 3, 4, 5, 6], [1.2, 1.9, 4.8, 9.6, 16.5, 25.4, 36.1], 2);
String(q2);      // "y = 241/210 − 5/28·x + 421/420·x^2  (…)"
compareModels(q2, polyFit([0, 1, 2, 3, 4, 5, 6], [1.2, 1.9, 4.8, 9.6, 16.5, 25.4, 36.1], 3));
                 // F = 7.56, p = 0.070769: the cubic term is not needed at 5%

A polynomial fit is linear regression on the columns x,x2,…,xdx, x^2, \dots, x^d. Two nested models, the smaller one's columns a subset of the larger one's, are compared by

F=(SSEsmall−SSEbig)/(pbig−psmall)SSEbig/(n−pbig), F = \frac{(SSE_{\text{small}} - SSE_{\text{big}})/(p_{\text{big}} - p_{\text{small}})}{SSE_{\text{big}}/(n - p_{\text{big}})},

which has the F(pbig−psmall, n−pbig)F(p_{\text{big}} - p_{\text{small}},\ n - p_{\text{big}}) distribution when the extra terms are zero. compareModels checks the nesting exactly before it computes anything.

Try itEdit the code and run it with @ratmath/stats and Core's Rational in scope. The last line's value is shown; PRINT(…) adds lines, TEX(…) typesets math.
Ctrl/⌘ + Enter runs