2026-10-19
These notes support the Chapter 3 lecture slides on multiple linear regression (MLR). They do three things that the slides state but do not derive.
Complete derivations. Starting from we derive the normal equations, the unbiasedness of , the ANOVA identity , the distribution of and , their independence, and hence the exact null distribution of the global -statistic. The partial -test and the -test are derived as special cases, and the identity is proved.
A worked example small enough to do by hand. The fuel-use data of the slides (, ) has a whose inverse has a rational determinant (). Every number in the ANOVA table, the coefficient table and the residual diagnostics is computed in full.
A one-to-one check against R. For every
hand-computed quantity the corresponding R command and its output are
displayed, and the two are compared side by side. The companion script
MTH303_Ch3_Hand_vs_R.R reproduces the whole comparison
automatically and reports MATCH or DIFFERENT
for each quantity.
The intended classroom sequence is: derive on the board (§(见「ANOVA 表推导」)), compute by hand in groups (§(见「手工计算例题」)), then run the R script live and watch the two columns agree (§(见「R 验证」)–§(见「教学安排与 R 脚本」)).
The Chapter 3 notes introduce and then use it. This supplement does three things.
It exhibits the whole matrix. For the fuel-use example (, ) all entries of are printed, and then , whose diagonal gives the residual variances.
It proves the properties and checks each one numerically: symmetry, idempotence, , , eigenvalues in , and (which is what bounds leverage between and ).
It rebuilds every diagnostic from alone — leverage, the full residual covariance matrix , standard errors and confidence intervals, standardised and studentised residuals (both by closed form and by actually refitting the model times), Cook’s distance, the ANOVA table, the global and partial -tests, and prediction intervals. A second example with and shows that none of it depends on being small.
The companion script MTH303_Ch3_Hat_Matrix_No_Packages.R
performs all of this. It calls lm() only in blocks
labelled “CHECK”, and never as the source of an answer:
hatvalues(), rstandard(),
rstudent(), cooks.distance(),
vcov(), confint() and predict()
are all re-implemented from first principles and then compared with R’s
own functions. All
comparisons agree to at least
(most to
);
the complete transcript is in
MTH303_Ch3_Hat_Matrix_Output.txt.
With explanatory variables and independent observations, where the errors satisfy and, for inference, . The quantity is the regression function. The parameter is the change in the mean response associated with a one-unit increase in holding all other predictors fixed.
Stacking the equations (见公式) gives Write for the number of regression parameters (intercept plus slopes). In compact form, is the design matrix. In the rest of these notes always contains a column of ones, so the model has an intercept; the last part of §6.13 explains what changes if it does not.
Remark 1 (Full rank). All of the algebra below assumes , i.e. the columns of are linearly independent. This is exactly the condition under which is invertible. It fails if, for example, one predictor is a linear combination of the others, or if a categorical predictor with levels is coded with dummy variables while an intercept is also present (the “dummy-variable trap”).
Definition 2 (Least squares estimator). The least squares estimator minimises the residual sum of squares
Theorem 3 (Normal equations). If then has the unique minimiser and solves the normal equations .
Proof. Expand the quadratic form: We need two matrix-calculus facts, both obtained by writing the expression out in components and differentiating with respect to each : (For the second: , and of that is , which is the -th entry of .) Applying these to (见公式) with symmetric gives the gradient Setting this to zero gives the normal equations . Because , is positive definite and hence invertible, so the unique stationary point is (见公式). Finally, the Hessian is positive definite, so (见公式) is a minimum (indeed the unique global minimum, since is a strictly convex quadratic). ◻
Remark 4 (The component form of the first-order conditions). Writing the normal equations out row by row gives the familiar system where are the residuals and . In matrix form this is the single statement Equation (见公式) is the reason the ANOVA decomposition works, so it deserves to be highlighted.
Definition 5 (Fitted values, residuals, hat matrix). is called the hat matrix because : it puts the hat on .
Proposition 6 (Properties of ). The matrix is symmetric and idempotent: and . Consequently and is also symmetric and idempotent, . Moreover and hence .
Proof. Symmetry: , because and hence its inverse are symmetric. Idempotence: Then , and . Finally, for any idempotent matrix ; and because is the orthogonal projector onto the column space of . Hence . ◻
Proposition 7 (Two consequences of the normal equations). With , and
Proof. by the normal equations. The first column of is , so the first entry of is ; and . For (见公式), and the two pieces are orthogonal, so . ◻
Theorem 8 (Unbiasedness and covariance). Under with and , Moreover, if then
Proof. First note that with , and . Hence . For the covariance, using , more concisely Finally, is a fixed linear transformation of the normal vector , so it is normal with the mean and covariance just computed. ◻
Remark 9 (Reading the covariance matrix). The -th diagonal element of is , so the standard error of is estimated by where is defined and justified in §3.2. Off-diagonal elements are covariances, .
This is the core of the chapter. We build the ANOVA table in four logically separate steps, because it is important to see what is pure algebra and what needs the normal model:
Algebra (§3.1): the identity , which holds for the least squares fit regardless of any distributional assumption.
Unbiasedness (§3.2): , which also needs only (见公式) and not normality.
Distributions (§3.3): under normality, , under , and the two are independent.
The test (§3.4): the ratio therefore has an distribution, which is the ANOVA -test.
Definition 10 (The three sums of squares). The total sum of squares measures the variation of the response about its mean before regression; is what is left over after regression; is the part the regression has accounted for.
Theorem 11 (ANOVA decomposition). For the least squares fit of a model with an intercept, and all three quantities are non-negative.
Proof. The starting point is the elementary telescoping identity, valid for every : Note carefully that , because and is a column of , so and therefore . Now square (见公式) and sum over : The cross term vanishes: using and from Proposition 6 (equivalently, (见公式)). Hence . Non-negativity is clear from the squared-sum definitions. ◻
Remark 12 (The geometric content). In matrix form the decomposition is orthogonal projection of onto two orthogonal subspaces: is the projection onto the column space of (the “explained” part) and is the projection onto its orthogonal complement (the “unexplained” part). The identity is Pythagoras’ theorem in , after centring. This is why (见公式) and are the only two facts needed.
Remark 13 (Two useful alternative forms). Using the normal equations , and, subtracting (见公式) from (见公式) and using ŷᵀŷ = yᵀy − RSS from (见公式), Formulae (见公式) and (见公式) are the two versions students should be able to reproduce; the worked example of §6 checks that they agree.
The ANOVA table divides each sum of squares by its degrees of freedom. We now justify the choice of denominator for the error line.
Lemma 14 (Expected residual sum of squares). Under with and ,
Proof. Since (because ), we have , using symmetry and idempotence of . For a quadratic form in a random vector with mean and covariance , (This follows by writing and using .) Applying it with , , , because by Proposition 6. ◻
Corollary 15 (The ANOVA table is built from unbiased
quantities). Define
Then
:
the error mean square is an unbiased estimator of the error variance.
Equivalently,
is the “residual standard error” reported by summary() in
R. Also, under
one has
.
Proof. The first claim is Lemma 14 divided by . For the second, under the regression function is the constant , so the fitted values converge to and . With (the usual unbiased variance numerator) we get , hence . ◻
Remark 16 (Why the degrees of freedom are what they are). The ANOVA table below divides by , and . The counting rule is:
has df: observations, minus one for the estimated mean .
has df: observations, minus for the estimated parameters . Algebraically, .
has df: the leftover , the number of slopes being tested. Algebraically, the centred fitted vector lives in a -dimensional space.
Degrees of freedom therefore also add: .
Now normality enters. The tool is Cochran’s theorem in a form that is easy to verify directly.
Lemma 17 (Distribution of a quadratic form). Let and let be symmetric and idempotent with . Then Moreover, if is symmetric and idempotent with , then and are independent.
Proof sketch. Write the spectral decomposition , with orthogonal and Symmetry plus idempotence forces every eigenvalue to satisfy , so , and (the number of unit eigenvalues). Then a sum of independent squared standard normals, i.e. . If in addition then the columns of belonging to unit eigenvalues of are orthogonal to those belonging to unit eigenvalues of , so the two sums involve disjoint groups of the independent ; independence follows. ◻
Theorem 18 (Distributions behind the ANOVA table). Assume and . Then
Proof. (a) The error line. Put . Because , The matrix is symmetric and idempotent with rank by Proposition 6, so Lemma 17 gives
(b) Independence of (见公式). Since and are linear in , the pair is jointly normal. Joint normality plus zero covariance implies independence, so it suffices to show : Now , so Hence is independent of , and therefore of and of .
(c) The regression line under . Under the true model is , i.e. with . The centred fitted vector is where is the hat matrix of the intercept-only model (it is symmetric and idempotent with , and because is in the column space of ). Put . Then
is symmetric, and idempotent: ;
;
, because and . This is the step where is used: under the regression function is constant, so it is annihilated by the centring.
Therefore , and by Lemma 17.
(d) Independence of (见公式). Here it is easiest to use the decomposition of : and are symmetric idempotent matrices with so Lemma 17 applies and gives . ◻
Corollary 19 (The ANOVA table). Under the normal
linear model with an intercept,
来源 Source 平方和 Sum of squares 自由度 df 均方 Mean square F 值 回归 Regression RegSS = Σᵢ(ŷᵢ − ȳ)² p MSR = RegSS / p MSR / MSE 误差 Error RSS = Σᵢ(yᵢ − ŷᵢ)² n − p − 1 MSE = RSS / (n − p − 1) = s² 总计 Total TSS = Σᵢ(yᵢ − ȳ)² n − 1
Remark 20 (Degrees of freedom in one line). : the degrees of freedom add up exactly as the sums of squares do.
Remark 21 (Why the denominator df of the -test is and not ). The only change from the simple linear regression (SLR) case is that parameters are estimated instead of . Every place where SLR had becomes in MLR. The - and -tables, the formulas for standard errors and confidence intervals, and the definitions are otherwise identical.
A second remark worth making in class: the total line of (见公式) is not what R
prints. anova() in R prints the sequential (Type I)
break-down, one line per predictor, and then the residual line; the
total line is the sum of all the printed sum-of-squares entries. See §7.
Theorem 22 (Global -test). Consider Under , independently of . The test rejects at level when , equivalently when the -value .
Proof. Write and . By Theorem 18, under , By the definition of the distribution as the ratio of two independent chi-square variables divided by their degrees of freedom, The factor cancels, so is a pivot: its null distribution does not depend on the unknown . ◻
Remark 23 (What the global test does and does not tell you). Rejecting says only that some linear combination of the predictors helps to explain . It does not identify which predictors matter: with correlated predictors it is entirely possible for the global to be highly significant while every individual -statistic is insignificant. Conversely a large -value does not prove that the predictors are useless, only that this sample provides no evidence that they are useful.
Definition 24 ( and adjusted ).
is the proportion of the variation of about its mean that the regression accounts for. In MLR, can never decrease when a predictor is added (because can never increase), which is why the adjusted version, which penalises the estimated parameters, is also reported. Neither should be used as the sole criterion for choosing a model; see §5.
Theorem 25 (-statistic). For testing against , with as in (见公式). A confidence interval for is
Proof. By Theorem 8, where , so under By Theorem 18(a), , and is independent of , hence of , hence of . Therefore using the definition of Student’s distribution as a standard normal divided by the square root of an independent chi-square over its degrees of freedom. The confidence interval is the usual inversion of this test. ◻
Sometimes we need to test several slopes jointly, e.g. . Doing this with two separate -tests is wrong: each test controls its own type I error rate, so the chance of at least one false rejection is inflated well above . The correct tool is a single partial -test.
Theorem 26 (Partial -test for nested models). Let the reduced model use the first parameters () and the full model use all parameters, so the models are nested: For the statistic
Proof. Let and be the design matrices of the two models, with hat matrices and ; the columns of are the first columns of , so the column space of is a subspace of that of and .
(a) Algebra. Because and , and because the difference of two nested projections is itself a projection, is symmetric and idempotent with . Also Under the true mean vector satisfies for the vector of the reduced model, so lies in the column space of and therefore . Hence, with , by Lemma 17.
(b) Independence. , so Lemma 17 gives independence of the numerator and .
(c) Conclusion. Dividing the two independent chi-square variables by their degrees of freedom and cancelling gives (见公式). ◻
Corollary 27 (Partial for one predictor is ). The partial -test of against the full model (i.e. and the single omitted predictor is ) is numerically identical to the square of the -statistic of Theorem 25: Both therefore give exactly the same -value.
Proof sketch. Both statistics test the same hypothesis using the same reduction in residual sum of squares: dropping from the full model increases by , i.e. . Substituting into (见公式) with gives . The identity is verified numerically in §6.10. ◻
Remark 28 (Special case: the global test). Setting , the reduced model is the intercept-only model , whose . Then (见公式) becomes exactly (见公式). The global -test is thus the partial -test of “all slopes are zero” – the same theorem, one special case.
The -th fitted value is the -th row of times : . The weight therefore measures how much observation pulls on the -th fitted value.
Definition 29 (Leverage). The leverage of observation is the diagonal element of , where is the -th row of .
Proposition 30 (Properties of leverage). , , and . A widely used rule of thumb flags observation as a high-leverage point if
Proof. Since is idempotent and symmetric, , so , i.e. ; and by Proposition 6. Dividing by gives . ◻
Leverage depends only on the ’s, not on the ’s: a high-leverage point is one whose predictor values are unusual (far from the centre of the -cloud). In the worked example the largest leverage is against the cut-off , so no observation is flagged.
Proposition 31 (The residuals are correlated, and shrunk). Under the normal linear model, . Consequently Every residual has variance smaller than , and the residuals are mutually correlated even when the errors are independent.
Proof. is a linear transformation of the normal vector , so it is normal with mean and covariance using symmetry and idempotence. Reading off diagonal and off-diagonal entries gives (见公式). ◻
Because depends on , raw residuals are not comparable across observations. Two standard remedies:
Definition 32 (Standardised and studentised residuals). where is computed from all observations, and is the residual standard error of the model refitted with observation deleted. is the standardised residual, the studentised (externally studentised) residual.
The studentised version is preferred for detecting outliers, because when is unusually large the ordinary is inflated by that very observation, and the inflation appears in both numerator and denominator of . Computing does not require separate regressions: the exact update formula is and under the model. A common rule of thumb is to examine any observation with (or ) more closely – it is a flag for inspection, not an automatic deletion.
An observation is influential if removing it changes the fitted coefficients substantially. Let denote the fitted values from the model fitted without observation .
Definition 33 (Cook’s distance). The second expression, which needs only , and , is the one used in practice. A common cut-off is .
Outlier, leverage and influence are three different things, and the worked example illustrates all three combinations:
an outlier with small leverage: a large residual at an ordinary ; it moves the fit little but inflates ;
a high-leverage point that is not an outlier: an unusual that lies close to the fitted surface; it does not change the fit much;
an influential point: usually an outlier with high leverage, which both moves the surface and inflates .
Unusual observations should not be deleted automatically. First ask why they are unusual (recording error, a missing predictor, a genuinely different sub-population); then decide whether to correct the data, refit without them as a sensitivity check, extend the model, or use a robust method.
If two predictors are highly correlated, the data cannot separate their effects: the likelihood is nearly flat along the ridge , and the individual slopes are estimated imprecisely even though predictions may be fine.
Definition 34 (Variance inflation factor). Regress on all the other predictors and let be the resulting coefficient of determination. The variance inflation factor of predictor is
Proposition 35 (Interpretation). Var(β_j)=σ^2VIF_j/[(n-1)V̂ar(x_j)], so is exactly the factor by which the variance of is inflated relative to the case where is orthogonal to the other predictors. means no collinearity; values above about (some texts say ) are usually taken as a warning that the individual slopes are poorly determined. Note that is the -th diagonal element of rescaled, and that it involves only the predictors, never the response.
We now do every number in the ANOVA table from first principles. The example is small because it is meant to be reproduced with a calculator and a matrix inverse; the points being illustrated (the decomposition, the degrees of freedom, the -test, the partial -test) are identical in larger problems.
Example 36 (Fuel use, Bowerman & Schafer (1990)). Weekly fuel consumption is to be explained by the average hourly temperature (°F) and the chill index . Data from Example 1 of the slides:
| Observation | Temperature | Chill index | Fuel use | Fitted |
|---|---|---|---|---|
| 1 | 28.0 | 18 | 12.4 | 12.0732583 |
| 2 | 28.0 | 14 | 11.7 | 11.7432784 |
| 3 | 32.5 | 24 | 12.4 | 12.1631658 |
| 4 | 39.0 | 22 | 10.8 | 11.4130857 |
| 5 | 45.9 | 8 | 9.4 | 9.6370603 |
| 6 | 57.8 | 16 | 9.5 | 9.2258550 |
| 7 | 58.1 | 1 | 8.0 | 7.9614262 |
| 8 | 62.5 | 0 | 7.5 | 7.4828702 |
Here , and , so the error degrees of freedom are . The model is
Every entry is one of the raw sums above: the entry is , the entry is , and so on.
We use the adjugate formula .
Expanding along the first row, with cofactors , so A slicker route that avoids the three cofactors: because the first column is the constant vector, the determinant equals times the determinant of the centred cross-product matrix. Writing a direct evaluation gives and indeed . The centred quantities (见公式) are also what is needed for the slope formulas and the partial -test below.
Continuing, The cofactor matrix is symmetric here, so the adjugate equals it: Evaluating the nine quotients (each adjugate entry divided by ) gives
Multiplying the inverse (见公式) by row by row,
If the three products above are computed with the integer adjugate instead of the rounded inverse (见公式), the numerators come out exactly as and dividing by reproduces . Students who use the -decimal inverse (见公式) will instead get , and : the last digit or two moves because of rounding. This is a useful lesson in how many significant figures to carry through an intermediate step.
So the fitted model is Interpretation. Holding the chill index fixed, a one-degree increase in temperature is associated with a decrease of units of fuel use; holding temperature fixed, a one-unit increase in the chill index is associated with an increase of units.
Using the centred sums (见公式) together with the slopes are and then . This route is the one to use in an exam, since it needs only a inverse.
The fitted values are in the last column of the data table. The residuals are
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | |
|---|---|---|---|---|---|---|---|---|
Checkpoint 37 (The checks that must come out exactly right). These are the sanity checks students should perform before trusting any further arithmetic: align* _ie_i&=-610^-130 &&(first normal equation, eq:orth)\\ _ix_i1e_i&=-2.610^-110 &&(second normal equation)\\ _ix_i2e_i&=-910^-120 &&(third normal equation)\\ _iŷ_ie_i&=-6.410^-120 &&(residuals orthogonal to the fit)\\ _iŷ_i&=_iy_i=81.70 &&(so ŷ=y) align* and finally the two identities that make the ANOVA decomposition work, All the tiny non-zero values are floating-point round-off; in exact arithmetic they are zero.
(Here is obtained by adding the column of the table above; the eight terms are , , , , , , and , which sum to .) Three checks:
the “ route” to gives the same answer:
; that is, the two predictors explain of the variation in weekly fuel use.
With , and :
| Source | SS | df | MS | -value | |
|---|---|---|---|---|---|
| Regression | |||||
| Error | |||||
| Total |
where The critical value is . Since we reject decisively: temperature and chill index jointly explain a significant amount of the variation in fuel use.
The adjusted coefficient of determination is
From (见公式), using the diagonal of (见公式): The -statistics and the confidence intervals with are:
| Parameter | Estimate | Std. error | 95% CI | |
|---|---|---|---|---|
| (Temp) | ||||
| (Chill) |
with -values , and respectively. Both slopes are significant at the level. The interval for lies entirely below zero, confirming that temperature has a significantly negative effect once the chill index is controlled for.
Question: is the chill index needed given that temperature is already in the model? That is, test against the full model. Refitting the reduced model gives (from the same raw sums) Then and , so we reject at the level: the chill index adds significantly to the model that already contains temperature.
Checkpoint 38 (The identity ). From Step 7, , and The partial and the -test of the same slope are the same test. Students should verify this on their calculators – it is the quickest possible check that both computations are right.
Remark 39 (A no-refit formula for the partial ). The extra sum of squares from adding to a model that already contains can be written directly from the full-model quantities: which is exactly the difference of (见公式) computed above. This formula is the MLR analogue of the SLR identity .
The leverages are the diagonal entries of : With and the rule (见公式) at , the cut-off is : no observation is a high-leverage point, although observation 6 (, temperature with chill index ) is the most extreme.
| (standardised) | (studentised) | (Cook) | |||
|---|---|---|---|---|---|
| 1 | |||||
| 2 | |||||
| 3 | |||||
| 4 | |||||
| 5 | |||||
| 6 | |||||
| 7 | |||||
| 8 |
(temperature °F, chill , fuel ): Observation 4 is an outlier by the studentised-residual rule () even though its standardised residual is only just over in absolute value – exactly the case that motivates the studentised version. Its leverage is unremarkable, but its Cook distance is the largest in the data set, so it is also the most influential point; reported as a sensitivity check, refitting without observation 4 changes the coefficients noticeably. It should not be deleted automatically: the right classroom conclusion is that it is worth investigating why that particular week behaved as it did.
For a week with temperature °F and chill index , with : and , giving Hence The prediction interval is wider than the confidence interval, as it must be: it includes the variability of a single new observation, , on top of the uncertainty in the estimated mean.
If the model has no intercept, none of the ANOVA table above applies as written. The reason is that is no longer a column of , so the fitted values need not sum to the observed ones and (见公式) fails at the step . The “total” sum of squares then becomes the uncorrected rather than the centred , and the regression sum of squares is no longer a sum of squared deviations from a mean. For the worked example, the no-intercept fit has , which exceeds : the uncorrected total is , and the printed is not comparable with the with-intercept value. This is why statistical software warns about models without an intercept and why the intercept should be retained unless there is a strong substantive reason – and a re-derivation.
The point of this section is that the students should see the two
columns agree. Each hand-computed quantity is followed by the R command
that reproduces it. All R output below was produced by
MTH303_Ch3_Hand_vs_R.R on R 4.4.2.
Fuel <- c(12.4, 11.7, 12.4, 10.8, 9.4, 9.5, 8.0, 7.5)
Temp <- c(28.0, 28.0, 32.5, 39.0, 45.9, 57.8, 58.1, 62.5)
Chill <- c(18, 14, 24, 22, 8, 16, 1, 0)
fit <- lm(Fuel ~ Temp + Chill)
summary(fit)
anova(fit)
Call:
lm(formula = Fuel ~ Temp + Chill)
Residuals:
1 2 3 4 5 6 7 8
0.326742 -0.043278 0.236834 -0.613086 -0.237060 0.274145 0.038574 0.017130
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 13.108737 0.855698 15.3193 0.0000215 ***
Temp -0.090014 0.014077 -6.3942 0.001386 **
Chill 0.082495 0.022003 3.7493 0.013303 *
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
Residual standard error: 0.36708 on 5 degrees of freedom
Multiple R-squared: 0.97363, Adjusted R-squared: 0.96308
F-statistic: 92.303 on 2 and 5 DF, p-value: 0.00011293
> anova(fit)
Analysis of Variance Table
Response: Fuel
Df Sum Sq Mean Sq F value Pr(>F)
Temp 1 22.98082 22.98082 170.5486 0.000046966 ***
Chill 1 1.89420 1.89420 14.0575 0.013303 *
Residuals 5 0.67373 0.13475
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
Remark 40 (How to read R’s anova()
output). R’s anova() is a sequential (Type I)
table: the first line is the reduction in
from fitting Temp alone, the second line is the
additional reduction from adding Chill
after Temp. Hence
matching
(见公式). The residual line is
with
df. R does not print a total line; you construct it as
on
df.
Two further traps worth pointing out in class.
The F value column of anova() does
not test the whole model. Row 2 tests
given Temp, i.e. it is the partial
of §6.10:
.
The global
-test
of
is
and appears on the last line of summary().
The sequential break-down depends on the order of the terms in
the formula. Refitting as lm(Fuel ~ Chill + Temp) gives
different first and second lines but the same
,
the same
and the same fitted model. With
the two lines are the two partial
’s;
with
and correlated predictors the order genuinely matters, and one should
either fix an interpretable order or use Type II/III sums of squares
(car::Anova).
The script prints a line for every quantity. The first column is the value computed by the formulas of §6, the second is R’s value:
TSS hand = 25.548750 R = 25.548750 <-- MATCH
Reg SS hand = 24.875018 R = 24.875018 <-- MATCH
RSS hand = 0.673732 R = 0.673732 <-- MATCH
MSE = s^2 hand = 0.134746 R = 0.134746 <-- MATCH
GLOBAL F (all slopes 0) hand = 92.303086 R = 92.303086 <-- MATCH
R^2 hand = 0.973630 R = 0.973630 <-- MATCH
adjusted R^2 hand = 0.963081 R = 0.963081 <-- MATCH
beta0 hand = 13.108737 R = 13.108737 <-- MATCH
beta1 hand = -0.090014 R = -0.090014 <-- MATCH
beta2 hand = 0.082495 R = 0.082495 <-- MATCH
se(beta0) hand = 0.855698 R = 0.855698 <-- MATCH
se(beta1) hand = 0.014077 R = 0.014077 <-- MATCH
se(beta2) hand = 0.022003 R = 0.022003 <-- MATCH
t(beta1) hand = -6.394229 R = -6.394229 <-- MATCH
t(beta2) hand = 3.749337 R = 3.749337 <-- MATCH
CI lower beta1 hand = -0.126201 R = -0.126201 <-- MATCH
CI upper beta1 hand = -0.053827 R = -0.053827 <-- MATCH
t(beta2)^2 vs partial F hand = 14.057530 R = 14.057530 <-- MATCH
centred-formula partial F hand = 14.057530 R = 14.057530 <-- MATCH
sum h_ii hand = 3.000000 R = 3.000000 <-- MATCH
max |r_std - rstandard| hand = 0.000000 R = 0.000000 <-- MATCH
max |r_stud - rstudent| hand = 0.000000 R = 0.000000 <-- MATCH
max |Cook - cooks.distance| hand = 0.000000 R = 0.000000 <-- MATCH
There is no DIFFERENT line: every hand-computed quantity
reproduces R exactly to the printed precision. That is the pedagogical
payoff – the formula on the board and the black box in R are the same
object.
# global F-test (last line of summary())
summary(fit)$fstatistic # value 92.303086, numdf 2, dendf 5
# partial F-test: full vs reduced model
fit_R <- lm(Fuel ~ Temp)
anova(fit_R, fit)
Analysis of Variance Table
Model 1: Fuel ~ Temp
Model 2: Fuel ~ Temp + Chill
Res.Df RSS Df Sum of Sq F Pr(>F)
1 6 2.567934
2 5 0.673732 1 1.8942 14.0575 0.013303 *
# leverages, standardised / studentised residuals, Cook's distance
hatvalues(fit); rstandard(fit); rstudent(fit); cooks.distance(fit)
# confidence and prediction intervals
predict(fit, newdata = data.frame(Temp = 30, Chill = 10), interval = "confidence")
predict(fit, newdata = data.frame(Temp = 30, Chill = 10), interval = "prediction")
fit lwr upr fit lwr upr
1 11.23327 10.51800 11.94854 1 11.23327 10.04921 12.41733
Write and on the board, then ask what should change with predictors. Answer: only the degrees of freedom.
Follow §3: normal equations telescoping ; then via ; then the chi-square and independence steps; then . Do not skip the two orthogonality facts (见公式): everything hinges on them.
Give the eight data points and the raw sums. Groups compute , then its determinant and inverse, then . Use the centred route (见公式) if time is short.
Sums of squares, then degrees of freedom, then mean squares, then the -statistic and its -value. Finish with the coefficient table and one confidence interval, and insist on the numerical checks listed in the worked example.
Execute MTH303_Ch3_Hand_vs_R.R section by section,
stopping at each MATCH line so that students can compare
with their own numbers. This is the moment the two routes are welded
together.
Show plot(fit) and anova(fit_R, fit), plus
the
identity. Discuss observation 4, which is an outlier and the most
influential point but has unremarkable leverage, against observation 6,
which has the highest leverage yet is not an outlier.
The global -test is the partial -test with . Several -tests are not a substitute for it. Preview collinearity and model selection.
Using instead of . Ask: how many parameters did you estimate? The error df is minus that number.
Confusing
with the sum of the anova() lines. They agree here
only because the model has an intercept and the lines are sequential;
the total must always be checked against
.
Reading the anova() F column as
the global test. It is one predictor at a time.
Reporting as evidence of a good model. With enough predictors regardless of relevance; report and the residual plots.
Testing several slopes with several -tests. Multiplicity inflates the type I error rate; use one partial .
Computing . Wrong: by Proposition 48, which is why standardisation is needed.
Deleting an outlier because it is inconvenient. Diagnose first; report the fit both with and without it.
MTH303_Ch3_Hand_vs_R.R (in this folder) is the script to
project in class. It is organised so that each part first prints the
hand calculation and then R’s own answer:
| Part | Content |
|---|---|
| 0 | the data |
| 1 | , , from the raw sums |
| 2 | by two routes, cofactors, |
| 3 | by three routes (inverse, adjugate, centred formulas) |
| 4 | , , and the orthogonality/Pythagoras checks |
| 5 | the ANOVA decomposition and the assembled ANOVA table |
| 6 | the global -test, critical values, decision |
| 7 | standard errors, -tests, confidence intervals |
| 8 | the partial -test, and |
| 9 | leverage, standardised/studentised residuals, Cook’s distance |
| 10 | point prediction, confidence interval and prediction interval |
| 11 | the whole example in three lines of R |
| 12 | the general case with : global on the Duncan prestige data |
The script ends with a single message: if any line reads
DIFFERENT, there is an arithmetic slip to find. In the
version distributed with these notes, all lines read MATCH
(34 of them).
A second script,
MTH303_Ch3_Exercises_Solutions.R, works
through Exercises 1–8 of §9 in R and
prints the numerical answers, including the ones that need a refit (the
interaction model, the reversed term order, the added high-leverage
point, the no-intercept model). It is a solutions key for the tutor
rather than a classroom script.
Numerical answers to all of the exercises below are produced by the
companion script
MTH303_Ch3_Exercises_Solutions.R.
Check the degrees of freedom. For the fuel data, state the df for , , and verify that they add up. What would they be if the model had been only? If the model had been ?
Verify the identity. Using the residuals in §6, confirm numerically that and , and explain which normal equation each identity comes from.
Reverse the order. Refit the fuel data as
lm(Fuel ~ Chill + Temp). Report anova() for
both orders and explain why the two lines swap but
,
the global
,
the coefficients and the fitted values do not change.
Prove the identity. Show that for a single omitted predictor, , and deduce Corollary 27.
Derive the prediction interval. For a new observation with predictor vector , show that and hence write down the prediction interval. Why is independent of ?
A high-leverage case. Add a ninth observation with temperature °F and chill index , fuel use . Recompute , the leverages, the ANOVA table and the Cook distances. Which quantities changed most, and why? (Answer: its own leverage, , is the largest in the data set, and every standard error grows – from to , for instance – so all confidence intervals widen. The coefficients themselves move only moderately, by roughly , because the new point still lies fairly close to the fitted surface. Leverage is not the same as influence.)
Collinearity. Compute the correlation between temperature and chill index in the fuel data, and the diagonal entries. Now replace the chill index by chill and recompute. Which numbers change, and which do not? Relate your answer to §5.4.
No intercept. Refit the fuel model without an intercept and confirm . Explain why this does not contradict .
, and for symmetric , .
For symmetric and idempotent : all eigenvalues are or ; ; .
For with , , and a fixed matrix of compatible size, .
, so , the sum of the squared entries of .
If and are symmetric idempotent with , then and is independent of (Cochran). This is Lemma 17, and it is the engine of Theorem 18.
If , and , then ; and if additionally with , then .
@p6.1cmp8.9cm@
,
,
,
& response vector, design matrix, parameter vector, error
vector
,
,
& sample size, number of predictors, number of parameters
& least squares estimator
& fitted values;
(hat matrix)
& residual vector
& leverage of observation
& total, regression and residual sums of squares
,
& mean squares;
& global test statistic,
under
& coefficient of determination (never decreases as
grows)
,
& standardised and studentised residuals
& Cook’s distance, cut-off
& variance inflation factor of predictor
Bowerman, B. L. and Schafer, R. L. (1990). Linear Statistical Models: An Applied Approach, 2nd ed. Duxbury. (Source of the fuel-use data.)
Cryer, J. D. and Miller, R. B. (1991). Statistics for Business: Data Analysis and Modeling. PWS-Kent. (Source of the car-type example.)
Duncan, O. D. (1961). A socioeconomic index for all occupations. In Occupations and Social Status. Free Press. (Source of the prestige data used in the demonstration.)
Draper, N. R. and Smith, H. (1998). Applied Regression Analysis, 3rd ed. Wiley. (Chapter 2 for the ANOVA decomposition and its distributional theory.)
Weisberg, S. (2005). Applied Linear Regression, 3rd ed. Wiley. (Chapters 4–5 for diagnostics and leverage.)
Faraway, J. J. (2014). Linear Models with R, 2nd ed. CRC Press. (For the R workflow and the comparison of sums-of-squares types.)
MTH303 Teaching Group (2025). Chapter 3: Multiple Linear Regression (lecture slides) and Tutorial 3. XJTLU.
With and , so puts the hat on : it maps the observed responses to the fitted values. It is an matrix (square, and in general not of full rank), built entirely from the design matrix — does not appear in it at all.
Remark 41 (The geometric content). is the matrix of the orthogonal projection of onto the column space of , ; and is the projection onto the orthogonal complement . So and . This single fact is the source of (the Chapter 3 ANOVA identity) and of the residual orthogonality .
Remark 42 (How to read the entries). Row of gives the weights with which the observations enter the -th fitted value: So measures how strongly observation pulls on the fitted value of observation , and — the leverage — measures how strongly observation pulls on its own fitted value. Entries can be negative: if sits on the opposite side of the -cloud from , then increasing pulls down.
The data are the eight weeks of the Chapter 3 worked example, so that every number below can be matched against the notes: .
| obs 1 | ||||||||
| obs 2 | ||||||||
| obs 3 | ||||||||
| obs 4 | ||||||||
| obs 5 | ||||||||
| obs 6 | ||||||||
| obs 7 | ||||||||
| obs 8 |
Three things to notice immediately.
The matrix is symmetric. Entry and entry are both . This is not an accident; see §12.3.
The diagonal is the largest entry in every row—which is what makes and hence .
Several entries are negative, the largest in magnitude being at position . Week 2 has temperature °F with chill ; week 6 has temperature °F with chill . They sit at opposite ends of the temperature range, so they pull the fit in opposite directions.
The diagonal, in vector form:
| obs | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
|---|---|---|---|---|---|---|---|---|
is the matrix that produces the residuals, . Its entries are off the diagonal and on it:
| obs 1 | ||||||||
| obs 2 | ||||||||
| obs 3 | ||||||||
| obs 4 | ||||||||
| obs 5 | ||||||||
| obs 6 | ||||||||
| obs 7 | ||||||||
| obs 8 |
The diagonal of is the factor in . It is smallest for observation 6 (): the week with the most unusual predictor values has the residual that is most tightly pinned to zero. That is why raw residuals cannot be compared across observations without standardising.
Proposition 43 (The five defining properties). Let be with and . Then
Proof. (见公式): , since and its inverse are symmetric. (见公式): . (见公式): , and . (见公式): for any idempotent matrix, (the eigenvalues are or , so the trace counts the unit eigenvalues); and because is the projector onto . (见公式): . ◻
Proposition 44 (Eigenvalues). has eigenvalues equal to and equal to . Hence : the “total pull” in the matrix is exactly .
Proof. is symmetric, so it has a real spectral decomposition with orthogonal. Idempotence forces for each eigenvalue, so ; and by (见公式), so exactly of them equal . Finally . ◻
--- (a) symmetry: H' = H -------------------------------------------
max |H' - H| max|difference| = 1.554e-15 <-- MATCH
--- (b) idempotence: H H = H (this is what makes it a projection)
max |H H - H| max|difference| = 1.527e-15 <-- MATCH
--- (c) H X = X
max |H X - X| max|difference| = 3.908e-13 <-- MATCH
--- (d) (I - H) is also a projection
max |(I-H)' - (I-H)| max|difference| = 1.554e-15 <-- MATCH
max |(I-H)(I-H) - (I-H)| max|difference| = 1.582e-15 <-- MATCH
max |H (I-H)| max|difference| = 1.588e-15 <-- MATCH
--- (e) traces and ranks: tr(H) = k and tr(I-H) = n-k
tr(H) max|difference| = 2.665e-15 <-- MATCH
tr(I-H) max|difference| = 2.665e-15 <-- MATCH
rank(H) from qr(): 3 rank(X): 3 both equal k = 3
--- (f) eigenvalues of H are 0 or 1, with k of them equal to 1
[1] 1 1 1 0 0 0 0 0
sum of eigenvalues = 3 = tr(H) = k = 3
--- (g) squared entries: h_ii = sum_j h_ij^2
max |h_ii - sum_j h_ij^2| max|difference| = 9.437e-16 <-- MATCH
The “max|difference|” column is ; all values at the level of floating-point round-off. Property (g), , is used in the next section.
Definition 45 (Leverage). , where is the -th row of .
Proposition 46 (Bounds, mean and the rule of thumb). , and . The usual flag for a high-leverage observation is
Proof. Since is idempotent and symmetric, so ; summing the diagonal gives by (见公式), hence . ◻
| obs | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | |
|---|---|---|---|---|---|---|---|---|---|
| Temp | 28.0 | 28.0 | 32.5 | 39.0 | 45.9 | 57.8 | 58.1 | 62.5 | |
| Chill | 18 | 14 | 24 | 22 | 8 | 16 | 1 | 0 | |
| of total |
Here , so the cut-offs are and . The largest leverage is observation 6 at , still below , so no observation is formally high-leverage. Note that observation 6 is also the one with the smallest and therefore the smallest residual variance. Observation 4 — the influential outlier of the Chapter 3 notes — has , below the average : it is unusual in , not in .
Common error 47. Leverage does not depend on . Changing the fuel values changes , the residuals, the ANOVA table and every diagnostic except and . If you want to know whether an observation is unusual in its predictor values, look at ; if you want to know whether it is unusual in its response, look at the residual. Cook’s distance is the combination of the two.
Proposition 48 (Residuals are correlated and shrunk). Under with , so
Proof. Since we have . Then and, using symmetry and idempotence of , Reading off entries gives the stated variances and covariances. ◻
The matrix displayed in §2 is the residual correlation structure, up to the factor . Two consequences that matter in practice:
Even with independent errors, the residuals are not independent. The off-diagonal entries of are , generally non-zero. Any argument that treats as independent is wrong.
The residuals are shrunk, unevenly. , so the average residual variance is . The shrinkage is worst where leverage is highest.
, estimated by replacing with . The whole estimated covariance matrix for the fuel example is whose diagonal entries are , , — the squared standard errors reported by the notes. The off-diagonals are covariances, e.g. , giving .
MSE = s^2 = RSS/(n-k) = 0.1347464 s = 0.3670782
estimate se t p_value CI_low CI_high
(Intercept) 13.10873722 0.85569805 15.31934914 0.0000215019 10.90909535 15.30837909
Temp -0.09001387 0.01407736 -6.39422935 0.0013861048 -0.12620088 -0.05382686
Chill 0.08249497 0.02200255 3.74933734 0.0133028057 0.02593562 0.13905432
t critical value t_{5,0.975} = 2.5705818
--- CHECK against lm() / summary() / confint()
MSE max|difference| = 0.000e+00 <-- MATCH
standard errors max|difference| = 0.000e+00 <-- MATCH
t values max|difference| = 0.000e+00 <-- MATCH
estimated covariance matrix max|difference| = 0.000e+00 <-- MATCH
confidence intervals max|difference| = 0.000e+00 <-- MATCH
Because differs across observations, raw residuals are not comparable. Two standard normalisations: where is the residual standard error of the model refitted with observation deleted. The studentised version answers the objection that when is an outlier, the ordinary is inflated by that same observation and appears in both numerator and denominator of .
Refitting times is legitimate but slow; the following closed forms give the same answers exactly.
Proposition 49 (Delete-one identities). Write for the -th row of . Then Consequently under the model.
Proof sketch. Let be with row removed and let . Using the block-inverse identity for one obtains and substituting this into and simplifying gives (见公式); premultiplying by gives (见公式). For (见公式), the residual sum of squares of the deleted fit is . ◻
The script does both: it refits the model eight times and it evaluates (见公式). The two agree to .
obs e h_ii 1-h_ii r_std s_delete r_stud
1 0.3267417 0.324360 0.675640 1.0828999 0.390894 1.1070583
2 -0.0432784 0.445531 0.554469 -0.1583341 0.409010 -0.1419747
3 0.2368342 0.341802 0.658198 0.7952570 0.404047 0.7610579
4 -0.6130857 0.310660 0.689340 -2.0116193 0.179210 -4.1204154
5 -0.2370603 0.184848 0.815152 -0.7152881 0.397428 -0.6752537
6 0.2741450 0.583833 0.416167 1.1576788 0.384310 1.2102933
7 0.0385738 0.371227 0.628773 0.1325215 0.401749 0.1187395
8 0.0171298 0.437739 0.562261 0.0622334 0.401995 0.0556849
s_(4) = 0.17921047 is much smaller than s = 0.3670782 because observation 4
has the largest residual: leaving it out shrinks the estimated error
variance. That is exactly why the standardised residual of observation 4
is -2.01 while its STUDENTISED residual is -4.12.
--- CHECK against lm()
standardised residuals max|difference| = 3.102e-13 <-- MATCH
studentised residuals max|difference| = 2.153e-12 <-- MATCH
Observation 4 is the textbook illustration of why exists. Its standardised residual, , only just trips the rule of thumb ; its studentised residual, , is unambiguous. The whole discrepancy is the factor : the point inflates its own yardstick.
Definition 50 (Cook’s distance). The second form follows from (见公式) and needs only , and . A common cut-off is .
Derivation of the closed form. From (见公式), . Therefore using from Proposition 46. Dividing by gives (见公式). ◻
obs h_ii r_stud D_closed D_refit
1 0.3244 1.1071 0.18765834 0.18765834
2 0.4455 -0.1420 0.00671472 0.00671472
3 0.3418 0.7611 0.10947400 0.10947400
4 0.3107 -4.1204 0.60788586 0.60788586
5 0.1848 -0.6753 0.03867384 0.03867384
6 0.5838 1.2103 0.62672445 0.62672445
7 0.3712 0.1187 0.00345618 0.00345618
8 0.4377 0.0557 0.00100509 0.00100509
D (closed form) vs D (definition, refitting) max|difference| = 1.2e-16 <-- MATCH
cut-off 4/(n-k) = 0.8 ; D above the cut-off: none (obs 4 has D = 0.6079)
--- CHECK against lm()
Cook's distance max|difference| = 3.664e-15 <-- MATCH
Observations 4 and 6 dominate, for completely different reasons:
| obs | why (with Cook’s ) | ||
|---|---|---|---|
| 4 | (low) | (large) | unusual in : an outlier whose predictors are ordinary. |
| 6 | (highest) | (moderate) | unusual in : a high-leverage week with an ordinary residual. |
So the largest Cook’s distance here comes from the high-leverage point, not from the outlier — a useful corrective to the reflex that “ finds outliers”. mixes the two: measures the surprise, and measures the leverage with which that surprise is transmitted to the whole fitted surface.
The last column reports the change in each slope when the observation is deleted, computed from the vector form of (见公式): .
obs h_ii r_std r_stud D dbeta1 dbeta2
1 0.324360 1.0828999 1.1070583 0.18765834 -0.013807044 0.0032352536
2 0.445531 -0.1583341 -0.1419747 0.00671472 0.001657329 -0.0013322329
3 0.341802 0.7952570 0.7610579 0.10947400 -0.013499597 0.0188507929
4 0.310660 -2.0116193 -4.1204154 0.60788586 0.032098543 -0.0327313065
5 0.184848 -0.7152881 -0.6752537 0.03867384 -0.006890958 -0.0218525852
6 0.583833 1.1576788 1.2102933 0.62672445 0.025213297 -0.0324417132
7 0.371227 0.1325215 0.1187395 0.00345618 -0.003201931 0.0105017200
8 0.437739 0.0622334 0.0556849 0.00100509 -0.001896437 0.0080162284
Reading across row 4: deleting week 4 would raise the intercept by , raise the temperature slope by (from to ) and lower the chill slope by . Deleting week 6 moves the slopes in the same directions but by comparable amounts — again, one is a -outlier and one an -outlier, and both matter.
Nothing in the ANOVA table needs new machinery; it is all traces and quadratic forms in .
Proposition 51 (Sums of squares as quadratic forms). Under , ; and under , independently of , hence .
Why the ranks are what they are. is symmetric idempotent with , so for . Under the mean vector is , and the centring matrix is symmetric idempotent with trace ; independence follows because . ◻
TSS = sum (y_i - ybar)^2 = 25.54875
Reg SS = sum (y.hat_i - ybar)^2 = 24.87501798
RSS = sum e_i^2 = 0.67373202
Reg SS + RSS = 25.54875 (must equal TSS)
Reg SS: definition vs beta'X'y form max|difference| = 3.553e-15 <-- MATCH
Reg SS: definition vs y.hat'y.hat form max|difference| = 3.553e-15 <-- MATCH
ANOVA: Regression 24.875018 df 2 MS 12.437509 F 92.3031 p 0.00011293
Error 0.673732 df 5 MS 0.134746
Total 25.548750 df 7
partial F = (2.5679337 - 0.673732)/1 / 0.1347464 = 14.057530
t(Chill)^2 = 14.057530 partial F = 14.057530 <-- t^2 = F
y.hat0 = 11.233271 ; x0'(X'X)^-1 x0 = 0.57458892
95% CI mean response [10.518003, 11.948539] ; 95% PI new obs [10.049211, 12.417331]
Small
is not what makes the algebra work. The script repeats everything for
where type is a factor with three levels (bc,
prof, wc). The design matrix is built by
hand: an intercept, two numeric columns, and two dummy columns for
prof and wc (bc is the baseline),
so
and
is
.
levels of 'type': bc prof wc -> baseline = bc , dummies for prof and wc
design matrix X2 is 45 x 5
beta.hat: (Intercept) -0.185028 income 0.597546 education 0.345319
typeprof 16.657513 typewc -14.661133
MSE = 94.948869 s = 9.744171
leverage: min = 0.048603616 mean = 0.11111111 = k/n max = 0.36635189
sum(h_ii) = 5 = k
h_ii > 2k/n = 0.2222 : 9, 16, 17, 19, 21, 27
h_ii > 3k/n = 0.3333 : 16
|r*| > 2 : 6, 28
D_i > 4/(n-k) = 0.1 : 6, 17, 19, 21, 27
--- CHECK against lm()
leverage max|difference| = 2.220e-16 <-- MATCH
standardised residuals max|difference| = 2.787e-14 <-- MATCH
studentised residuals max|difference| = 2.853e-14 <-- MATCH
Cook's distance max|difference| = 3.664e-15 <-- MATCH
The mean leverage is exactly
and
,
as Proposition 46 requires, even though the two dummy
columns are
variables rather than measurements. Two observations exceed
or not: only observation 16 (conductor) exceeds
.
The twelve largest off-diagonal entries of :
| occupation | |||
|---|---|---|---|
| 19 | store.manager | 17 contractor | |
| 23 | insurance.agent | 9 reporter | |
| 21 | bookkeeper | 24 store.clerk | |
| 6 | minister | 27 RR.engineer | |
| 16 | conductor | 22 mail.carrier | |
| 21 | bookkeeper | 9 reporter |
Positive entries pair occupations with similar predictor profiles (store manager and contractor, bookkeeper and store clerk, conductor and mail carrier); the negative entry pairs a minister with a railway engineer, which sit at opposite ends of the income/education space. This is the mechanism behind the warning in §12.3: adding a very unusual observation does not merely fail to help the fit at the other end of the data, it actively pulls it the wrong way.

image() — no packages.The complete script is
MTH303_Ch3_Hat_Matrix_No_Packages.R. The essential extracts
follow; each is three or four lines because
does all the work.
## --- the design matrix, built by hand (no model.matrix) -------------------
X <- cbind("(Intercept)" = rep(1, n), Temp = Temp, Chill = Chill)
y <- matrix(Fuel, ncol = 1)
XtX <- t(X) %*% X
XtXinv <- solve(XtX) # (X'X)^-1
beta <- XtXinv %*% t(X) %*% y # least squares estimate
## --- THE HAT MATRIX, ALL OF IT --------------------------------------------
H <- X %*% XtXinv %*% t(X)
print(round(H, 5)) # all n x n entries
h <- diag(H) # leverage
## --- fitted values and residuals ------------------------------------------
yhat <- H %*% y
e <- y - yhat # same as (diag(n) - H) %*% y
## --- leverage, row by row, straight from the definition -------------------
h_rowwise <- sapply(1:n, function(i)
as.numeric(t(X[i, , drop = FALSE]) %*% XtXinv %*% X[i, , drop = FALSE]))
## --- residual covariance structure ----------------------------------------
ImH <- diag(n) - H # Var(e) = sigma^2 (I - H)
var_e_factor <- diag(ImH) # the 1 - h_ii
## --- MSE, standard errors, t tests, confidence intervals ------------------
k <- ncol(X)
MSE <- as.numeric(t(e) %*% e) / (n - k)
Vb <- MSE * XtXinv # estimated Var(beta.hat)
se <- sqrt(diag(Vb))
tv <- as.numeric(beta) / se
tc <- qt(0.975, n - k)
CI <- cbind(as.numeric(beta) - tc * se, as.numeric(beta) + tc * se)
## --- standardised residual -------------------------------------------------
rstd <- as.numeric(e) / (sqrt(MSE) * sqrt(1 - h))
## --- studentised residual: BY REFITTING n times (no formula, no packages) --
rstu_refit <- sapply(1:n, function(i) {
Xi <- X[-i, , drop = FALSE]; yi <- matrix(y[-i, ], ncol = 1)
bi <- solve(t(Xi) %*% Xi) %*% t(Xi) %*% yi # refit without obs i
ei <- yi - Xi %*% bi
s_i <- sqrt(as.numeric(t(ei) %*% ei) / (n - k - 1))
e[i] / (s_i * sqrt(1 - h[i]))
})
## --- ... and the closed-form delete-one version ----------------------------
s_i <- sqrt((as.numeric(t(e) %*% e) - as.numeric(e)^2 / (1 - h)) / (n - k - 1))
rstu <- as.numeric(e) / (s_i * sqrt(1 - h))
## --- Cook's distance: definition (refit) and closed form -------------------
D_def <- sapply(1:n, function(i) {
Xi <- X[-i, , drop = FALSE]; yi <- matrix(y[-i, ], ncol = 1)
bi <- solve(t(Xi) %*% Xi) %*% t(Xi) %*% yi
sum((yhat - X %*% bi)^2) / (k * MSE)
})
D <- (as.numeric(e)^2 / (k * MSE)) * h / (1 - h)^2
## --- delete-one change in the coefficients ---------------------------------
dbeta <- sapply(1:n, function(i)
(XtXinv %*% matrix(X[i, ], ncol = 1) * as.numeric(e[i])) / (1 - h[i]))
## --- ANOVA, global F, partial F, prediction -------------------------------
ybar <- mean(y)
TSS <- as.numeric(t(y - ybar) %*% (y - ybar))
RegSS <- as.numeric(t(yhat - ybar) %*% (yhat - ybar))
RSS <- as.numeric(t(e) %*% e)
Fstat <- (RegSS / (k - 1)) / (RSS / (n - k))
x0 <- matrix(c(1, 30, 10), ncol = 1)
se_mean <- sqrt(MSE * as.numeric(t(x0) %*% XtXinv %*% x0))
se_pred <- sqrt(MSE * (1 + as.numeric(t(x0) %*% XtXinv %*% x0)))
## --- heat map, base graphics ----------------------------------------------
pal <- hcl.colors(64, "Blues 3", rev = TRUE) # dark = large
image(1:n, 1:n, t(H[n:1, ]), col = pal, zlim = c(0, max(abs(H))))
Remark 52 (What is deliberately not used).
Nothing in the list above calls hatvalues,
rstandard, rstudent,
cooks.distance, influence, vcov,
confint, predict, anova or
summary. Those appear only in the “CHECK against
lm()” blocks, where they serve as an independent audit of
the hand-built quantities. If you are teaching, keep that order: build
first, check second.
| Quantity | Formula |
|---|---|
| Hat matrix | |
| Fitted values | |
| Residuals | |
| Leverage | |
| Leverage bounds | , , |
| Residual covariance | , so |
| Coefficient covariance | , estimated by |
| Standard error | |
| Standardised residual | |
| Studentised residual | , |
| Delete-one fitted values | |
| Delete-one coefficients | |
| Cook’s distance | , cut-off |
| Sums of squares | , |
| Total pull |
| File | Contents |
|---|---|
MTH303_Ch3_Hat_Matrix_No_Packages.R |
The script: 14 parts, every diagnostic rebuilt from |
MTH303_Ch3_Hat_Matrix_Output.txt |
Its complete output ( lines, successful checks) |
hat_matrix_heatmap.png |
The two heat maps, produced by the script |
MTH303_Ch3_Hat_Matrix_Handout.pdf |
This document |
MTH303_Ch3_MLR_Teaching_Notes.pdf |
The Chapter 3 notes this supplements |
This bilingual teaching page was assembled by DeepSeek 4.1 Flash from the course LaTeX sources; the technical derivations are reproduced verbatim. 中文导读层由 DeepSeek 4.1 Flash 撰写,技术推导部分保留原始英文内容。