开始之前:期末考什么、怎么用这份材料

这份材料在 Lab Test 网页的基础上扩展而来,只为一件事服务:MATH2831 期末考试(占 55%)拿高分。所有内容都对照 Moodle 上的考试说明、2021 / 2023 Möbius 期末真题、以及 tutorial / lab 原题来写。

期末考试长什么样

项目内容(来自 Moodle Assessments Hub)
占比 / 时长55%,2 小时,4–5 道题,每题标分值,可以任意顺序做
日期Moodle 写"待定",考试周期间,以 myUNSW 考试时间表为准
地点数学与统计学院机房(Linux 电脑),提前 20 分钟到 Chancellors Garden 集合,现场分配机房
形式Möbius 作答,题型同 Assignment 和 Lab Test:R 上机题填 Möbius,证明题写在答题本上
电脑上有的 PDFformula sheet、Lecture Notes、slides、带批注的 slides、lecture R scripts、tutorial / lab 题目和答案
只能带笔、尺子 + 实体学生证 + 手机(只用于 MFA)。不能带计算器、笔记、白纸
考试范围Week 1–10 全部(课程大纲:"covers all material from lectures, tutorials, labs and assignments")

2023 年期末的结构(老师说今年类似):

题分值在哪答2023 考了什么本材料
Q115Möbius比较 mpg~disp 和 log-log 模型的诊断图;SLR 的 F 检验、斜率、CI;哑变量离群点检验第 4、14、16、22 章
Q215Möbiusregsubsets 最优子集 + adjusted R² + PRESS;overall F、嵌套 F、98% 预测区间第 6、7、9、13、22 章
Q315答题本无截距模型的加权最小二乘:推导、期望方差、MLE、乘 √r 变换、特例第 17 章
Q415答题本Cook's D 和 DFFITS 的捷径公式证明第 15 章
🎯 拿分路线
  • R 题(约一半分数):题型非常固定(第 22 章)。把 2021、2023 的 R 题做熟,就是"粘贴数据 → lm → summary / anova / confint / predict / regsubsets / rstudent"这套流程。
  • 证明题(约一半分数):近三年几乎原题重复。第 15 章(影响点)和第 17 章(WLS)两套证明背熟到能默写,再加第 21 章的 2021 Q4(σ̂² 无偏),就覆盖了 2021、2023 的全部证明题。
  • Week 10 新内容(第 18、19 章)往年没考过,但在范围内,可能出一道 R 题。

怎么用这份材料

  1. 左边看网页,右边开 RStudio。在 RStudio 里 File → Open File…,打开 final_study/R/ 里对应章节的 .R 文件。
  2. 每个代码框都真的去运行:代码框左上角的灰色标签(如「ch15 · 15.7」)= 脚本里 # ---- 15.7 那一段。脚本要从开头按顺序运行,因为后面会用到前面的变量。注意:标签编号是脚本段落的编号,和网页小标题(如"15.7 看图找影响点")是两套编号,不一定相同。对照网页上的"Console 输出",确认数字一样。
  3. 橙框"原题"是课程 PDF 和真题里的原题(英文原文)。先自己做,再展开答案。
  4. 紫边框"✍️"是证明:先遮住自己写,再对照。
  5. 每章结束勾选"我已经学完",左上角显示进度(只存在这台电脑的浏览器里,和 Lab Test 网页的进度分开)。

章节和优先级

第 0–12 章是 Lab Test 网页原有的内容(Week 1–7),已经学过的复习即可;标"新"的是期末新增的。★★★ 必学,★★ 强烈建议,★ 有时间再看。

章内容状态优先级
0–2RStudio、分布、检验与置信区间Lab Test 已学复习 ★
3–7SLR、矩阵形式、MLR 推断、ANOVA 与 F 检验家族Lab Test 已学复习 ★★★(R 题天天用)
8–10杠杆、模型选择、残差诊断Lab Test 已学复习 ★★
13regsubsets、验证集、K 折 CV、LASSO新★★★
14残差的性质、哑变量离群点检验新★★★
15影响点:Cook's D、DFFITS、DFBETAS、COVRATIO + 证明新★★★
16变换、比较诊断图、多项式回归新★★★
17WLS / GLS + 证明新★★★
18分类变量、交互项新 · Week 10★★
19非满秩、单因素模型、一般线性假设新 · Week 10★★
20Logistic 回归(可能考)新 · Lab 10★
11Week 1–7 证明模板 + 39 道判断题Lab Test 已学复习 ★★
21期末证明题地图 + 2021 Q4、2020 Q1/Q3 + 24 道新判断题新★★★
25诊断图图鉴:四张图"坏了"分别长什么样(模拟数据可视化)新★★★
222023、2021 期末 R 题逐题精讲新★★★
262023 期末完整解答(4 题逐小问,R 输出全部核对)新★★★
272021 期末完整解答(6 题逐小问 + 原图)新★★★
242020 期末完整解答(4 题逐小问 + 原图)新★★★
282019 期末完整解答(4 题,纸笔考试,含 Gauss–Markov、logistic)新★★
292014 期末完整解答(7 题,基础题为主)新★
23两套模拟期末(2 小时 × 2)新★★★
12Lab Test 三套模拟(Week 1–7 练手)Lab Test 已学★
⚠️ 不考,不用学
slides 上写着 not examinable 的:multicollinearity(VIF)、added variable plots、partial residual plots、预测变量的非线性变换、Box-Tidwell、Box-Cox、effects coding。Logistic 回归不确定(第 20 章,优先级最低)。

考前一周 / 考前一天

第 0 章 · RStudio 零基础

本章目标
学完你能:打开 RStudio → 运行一行代码 → 把考题给的数据粘贴进去做成一张表 → 拟合第一个模型。
配套脚本:R/ch00_rstudio_basics.R 考试关联:Q2 的第一步就是粘贴数据,错了后面全错。

0.1 RStudio 是什么?四个窗格

R 是一门做统计的语言,RStudio 是写 R 的"编辑器"。打个比方:R 是发动机,RStudio 是方向盘和仪表盘。你的电脑上 RStudio 装在 D:\RStudio,双击 rstudio.exe(或开始菜单里搜 RStudio)打开。考场是 Linux 电脑,但 RStudio 界面完全一样。

打开后你会看到四块区域(第一次打开可能只有三块,按 Ctrl+Shift+N 新建一个脚本,左上角就会出现):

① 左上:脚本编辑器(Source) 在这里写代码、保存成 .R 文件 光标放在某行,按 Ctrl+Enter 运行这一行 选中多行再按 Ctrl+Enter = 运行选中部分 我们的 ch00…ch12.R 文件就在这里打开 ② 左下:Console(控制台) 代码在这里真正运行,结果也显示在这里 也可以直接在 > 后面打字,按 Enter 运行 出现 + 号 = 括号没写完,按 Esc 取消 ③ 右上:Environment 你创建过的变量都列在这里 点表格名可以像 Excel 一样查看 ④ 右下:Plots / Help / Files 画的图出现在 Plots 标签 ?lm 的帮助页面出现在 Help 标签 点 Zoom 可以把图放大
💡 唯一要记住的快捷键
Ctrl + Enter:运行光标所在行(或选中的几行)。
另外两个好用的:Alt + - 打出赋值符号 <-;Ctrl + L 清空 Console。
🖥️ RStudio 跟做:打开本章脚本
File → Open File… → 找到 C:\Users\Cestbon\Desktop\MATHLAB\final_study\R\ch00_rstudio_basics.R 打开。
如果中文注释显示成乱码:File → Reopen with Encoding… → 选 UTF-8。

0.2 把 R 当计算器,然后给结果起名字

把光标放在脚本第 0.1 节第一行 1 + 1,按 Ctrl+Enter,Console 会出现 [1] 2。前面的 [1] 只是"这是第 1 个数"的编号,不用管。

Rch00 · 0.1–0.2
2^3          # 2 的 3 次方
sqrt(16)     # 开平方
log(100)     # 注意:R 的 log 是自然对数 ln
a <- 5       # 把 5 存进名字 a 里,"<-" 读作"赋值给"
b <- 3
a + b
Console 输出
[1] 8
[1] 4
[1] 4.60517
[1] 8

运行 a <- 5 之后,看右上角 Environment,a 出现了。之后写 a 就等于写 5。# 后面的内容是注释,R 会忽略。

0.3 向量:一串数

统计永远在处理"一串数"(比如 15 个植物的锌含量)。R 用 c()(combine)把数串起来,叫向量:

Rch00 · 0.3
x <- c(2, 4, 6, 8, 10)
length(x)    # 有几个数 -> 5
mean(x)      # 平均数 -> 6
var(x)       # 样本方差(分母 n-1) -> 10
x - mean(x)  # 每个数都减去平均数(R 会自动对每个元素做)
x[2]         # 取第 2 个 -> 4
Console 输出
[1] 5
[1] 6
[1] 10
[1] -4 -2  0  2  4
[1] 4

注意 x - mean(x):R 自动把每个数都减了 6。后面算 Sxx = sum((x - mean(x))^2) 就靠这个特性。

0.4 data.frame:一张表 —— 考试 Q2 的第一步

回归要用好几列数据(响应变量 + 预测变量),把几个等长的向量并排放就是 data.frame(数据框),可以理解成 Excel 表:每一列是一个变量,每一行是一个观测。

2025 年考题 Part I 是这样给数据的(原题截图里的格式):

Budget=c(151,7,153,56,32,196,205,141,65,73,60,53,57,49,44,257,83,37,41,37,39,36,30,19,27,...)
Opening=c(58.11,17.21,17.71,8.37,16.85,35.95,47.98,75.92,54.56,20.31,8.57,144.30,...)
Theatres=c(3764,2853,3177,2805,2441,3635,3420,3853,3465,3573,2125,4033,3372,2736,...)
Ratings=c(7.6,7.1,4.7,6.9,6.9,6.1,6.5,8.2,7.2,6.6,7.4,5.0,6.2,7.1,6.2,7.5,4.4,6.0,...)
USRevenue=c(285.6,57.6,133.6,28.1,44.0,88.0,170.2,258.8,248.7,54.5,37.4,296.8,...)
Movies=data.frame(USRevenue, Budget, Opening, Theatres, Ratings)

做法:把这几行整段复制,粘贴到你的脚本里(或直接粘贴到 Console),运行。然后一定要检查:

Rch00 · 0.4
Budget    <- c(151, 7, 153, 56, 32)
Opening   <- c(58.11, 17.21, 17.71, 8.37, 16.85)
USRevenue <- c(285.6, 57.6, 133.6, 28.1, 44.0)
lengths(list(USRevenue, Budget, Opening))   # 先检查每个向量的长度!(拼表之前)
Movies <- data.frame(USRevenue, Budget, Opening)

Movies             # 看整张表
dim(Movies)        # 几行几列:行数就是样本量 n
names(Movies)      # 列名(后面写模型要用,大小写必须一模一样)
Movies$Budget      # 用 $ 取出一列
Console 输出
[1] 5 5 5
  USRevenue Budget Opening
1     285.6    151   58.11
2      57.6      7   17.21
3     133.6    153   17.71
4      28.1     56    8.37
5      44.0     32   16.85
[1] 5 3
[1] "USRevenue" "Budget"    "Opening"
[1] 151   7 153  56  32
⚠️ 考场必做检查
题目会写 "each vector below should contain 43 elements"。粘贴后、拼 data.frame 之前,立刻运行 lengths(list(向量1, 向量2, ...)),确认每个都是 43(拼完之后再查就晚了:长度不一样时 data.frame 要么报错,要么会偷偷把短的向量循环补齐)。拼完再用 dim(数据框名) 确认行数。复制时漏掉最后几个数是最常见的丢分方式(Möbius 网页上的长行很容易没选全)。

0.5 读数据文件(平时练习用)

tutorial / lab 的题目用的是 cheese.txt 这类文件,已经放在 MATHLAB/datasets/ 里。读文件之前要先告诉 R "去哪个文件夹找",这叫工作目录(working directory):

Rch00 · 0.5
setwd("C:/Users/Cestbon/Desktop/MATHLAB/datasets")   # 注意用 / 不是 \
getwd()                                              # 确认一下
cheese <- read.table("cheese.txt", header = TRUE)    # .txt 用 read.table,header=TRUE:第一行是列名
head(cheese)                                         # 看前 6 行
zinc <- read.csv("zinc.csv")                         # .csv 用 read.csv
Console 输出
  taste Acetic   H2S Lactic
1  12.3  4.543 3.135   0.86
2  20.9  5.159 5.043   1.53
3  39.0  5.366 5.438   1.57
4  47.9  5.759 7.496   1.81
5   5.6  4.663 3.807   0.99
6  25.9  5.697 7.601   1.09

也可以用菜单:Session → Set Working Directory → Choose Directory…。考试时数据是粘贴的,或者用 R 自带的数据集,一般不需要读文件。

0.6 R 自带的数据集(2025 Part II 用的 trees)

Rch00 · 0.6
head(trees)    # 不用读文件,直接能用
dim(trees)     # 31 棵树,3 列
?trees         # 打开帮助:每一列是什么意思
Console 输出
  Girth Height Volume
1   8.3     70   10.3
2   8.6     65   10.3
3   8.8     63   10.2
4  10.5     72   16.4
5  10.7     81   18.8
6  10.8     83   19.7
[1] 31  3

其他常见内置数据集:cars、mtcars、stackloss、swiss、women、LifeCycleSavings。第 12 章的模拟题会用到。

0.7 画图 + 第一个线性模型

Rch00 · 0.7–0.8
plot(Volume ~ Height, data = trees)       # 散点图:y ~ x
model <- lm(Volume ~ Height, data = trees) # lm = linear model:Volume 由 Height 解释
summary(model)                             # 模型的"体检报告"(第 3 章逐行讲)
abline(model, col = "red")                 # 把拟合直线画上去

y ~ x 这个"波浪号"读作 "y 由 x 来解释"。左边永远是响应变量(被预测的),右边是预测变量。多个预测变量用 + 连接:lm(USRevenue ~ Budget + Opening + Theatres + Ratings, data = Movies);全部列都当预测变量可以简写成 lm(USRevenue ~ ., data = Movies)。

0.8 Möbius 填答案:数字怎么复制

题目一般要求 "Report all numbers to at least two decimal places. For p-values, paste them exactly as shown in the R output."

Rch00 · 0.9
round(pi, 4)            # 3.1416
print(pi, digits = 10)  # 3.141592654
0.000000017294          # R 自动显示为 1.7294e-08

0.9 常见报错,一眼认出来

你看到原因怎么办
Error: object 'Movie' not found名字拼错,或者定义它的那行还没运行检查大小写;先运行定义的那一行
Error: unexpected input用了中文逗号 , 或中文括号 ()切换英文输入法重新打
Console 一直出现 +括号或引号没配对,R 在等你写完按 Esc,检查括号
cannot open file 'cheese.txt'工作目录不对先 setwd(...)
arguments imply differing number of rows拼 data.frame 时向量长度不一样粘贴漏了数,重新复制
✅ 本章检查清单
  • 能打开 RStudio,用 Ctrl+Enter 运行脚本里的一行
  • 能把几个 c(...) 拼成 data.frame,并用 lengths(list(...)) / dim 检查
  • 会 lm(y ~ x1 + x2, data = 表名) 和 summary()

第 1 章 · 随机变量与四大分布

本章目标
弄懂"分布"是什么;认识整门课只会用到的四个分布:正态、卡方 χ²、t、F;会用 R 的 pnorm / pt / pf / qt 算概率和临界值。
配套脚本:R/ch01_distributions.R 考试关联:每一个 p 值、每一个 "null distribution: F4,38" 都来自这里。

1.1 随机变量、期望、方差(用大白话)

随机变量就是"结果还没出来的数"。比如明天随机抽一棵树量它的体积 Y:在量之前,Y 可能是很多值,每个值有不同的可能性。分布就是"每个值有多大可能"的完整描述,画出来就是一条曲线(密度曲线):曲线越高的地方,越容易出现。

整门课的证明题都靠下面几条运算规则(a,ba, b 是普通常数):

E(aX+bY)=a E(X)+b E(Y)E(aX + bY) = a\,E(X) + b\,E(Y) Var(aX)=a2 Var(X),Var(aX+bY)=a2Var(X)+b2Var(Y)+2ab Cov(X,Y)\mathrm{Var}(aX) = a^2\,\mathrm{Var}(X), \qquad \mathrm{Var}(aX + bY) = a^2\mathrm{Var}(X) + b^2\mathrm{Var}(Y) + 2ab\,\mathrm{Cov}(X,Y) Cov(X,X)=Var(X),Cov(aX+bY,Z)=a Cov(X,Z)+b Cov(Y,Z)\mathrm{Cov}(X, X) = \mathrm{Var}(X), \qquad \mathrm{Cov}(aX + bY, Z) = a\,\mathrm{Cov}(X,Z) + b\,\mathrm{Cov}(Y,Z)

记忆方法:常数可以提出来,提出来的时候方差/协方差里要平方(或者两边各提一次)。第 5 章会把它们升级成矩阵版本 Cov(AY)=A Cov(Y)A⊤\mathrm{Cov}(AY) = A\,\mathrm{Cov}(Y)A^\top,那是 2025 年证明题 (a)。

🖥️ RStudio 跟做:ch01 第 1.1 节
用 10 万个随机数"模拟"验证规则:X∼N(2,1)X \sim N(2,1),Y∼N(5,9)Y \sim N(5,9) 独立,a=3,b=−2a=3, b=-2。理论上 E(3X−2Y)=6−10=−4E(3X - 2Y) = 6 - 10 = -4,Var=9×1+4×9=45\mathrm{Var} = 9 \times 1 + 4 \times 9 = 45。
Rch01 · 1.1(模拟验证,可跳过)
set.seed(2831)
X <- rnorm(100000, mean = 2, sd = 1)
Y <- rnorm(100000, mean = 5, sd = 3)
mean(3 * X - 2 * Y)   # 约 -4
var(3 * X - 2 * Y)    # 约 45
Console 输出
[1] -4.025731
[1] 45.02488
📄 原题 · Tutorial Week 1 Q1–Q2
1. Show that the expectation operator E is linear. That is, for any a, b ∈ ℝ and random variables X and Y, E(aX + bY) = aE(X) + bE(Y).
2. (a) For a ∈ ℝ, Var(aX) = a²Var(X). (b) Show that Cov(X, X) = Var(X) and if X and Y are independent, then Cov(X, Y) = 0. (c) Var(aX + bY) = a²Var(X) + b²Var(Y) + 2abCov(X, Y).
证明思路(第 11 章会系统练)

Var(aX):

Var(aX)=E[(aX−E(aX))2]=E[(aX−aEX)2]=E[a2(X−EX)2]=a2E[(X−EX)2]=a2Var(X)\mathrm{Var}(aX) = E[(aX - E(aX))^2] = E[(aX - aEX)^2] = E[a^2(X-EX)^2] = a^2 E[(X-EX)^2] = a^2\mathrm{Var}(X)

每一步只用了"期望是线性的"。

独立 ⇒ Cov = 0:Cov(X,Y)=E(XY)−E(X)E(Y)\mathrm{Cov}(X,Y) = E(XY) - E(X)E(Y),独立时 E(XY)=E(X)E(Y)E(XY) = E(X)E(Y),所以等于 0。

Var(aX+bY):把 Var(aX+bY)=Cov(aX+bY,aX+bY)\mathrm{Var}(aX+bY) = \mathrm{Cov}(aX+bY, aX+bY) 用双线性展开成四项:a2Cov(X,X)+ab Cov(X,Y)+ba Cov(Y,X)+b2Cov(Y,Y)a^2\mathrm{Cov}(X,X) + ab\,\mathrm{Cov}(X,Y) + ba\,\mathrm{Cov}(Y,X) + b^2\mathrm{Cov}(Y,Y)。

1.2 正态分布 N(μ, σ²)

钟形曲线。两个参数:中心 μ\mu(均值)和宽度 σ\sigma(标准差)。Z∼N(0,1)Z \sim N(0,1) 叫标准正态。任何正态都能变成标准正态:Z=(Y−μ)/σZ = (Y - \mu)/\sigma。

为什么重要?线性模型假设误差 εi∼N(0,σ2)\varepsilon_i \sim N(0, \sigma^2)。由此可以推出估计量 b0,b1b_0, b_1 也是正态的 —— 这是所有检验的出发点。

R 的四个函数(所有分布都是同一套命名):

前缀意思正态t卡方F
d密度:曲线高度(画图用)dnormdtdchisqdf
p左边面积 P(X≤x)P(X \le x)pnormptpchisqpf
q分位数:左边面积为 p 的那个 xqnormqtqchisqqf
r随机数rnormrtrchisqrf
Rch01 · 1.2
pnorm(1.96)               # P(Z <= 1.96) = 0.975:左边面积
1 - pnorm(1.96)           # 右边面积 0.025
qnorm(0.975)              # 反过来:哪个数左边有 97.5%? -> 1.96
Console 输出
[1] 0.9750021
[1] 0.0249979
[1] 1.959964
💡 "p" 永远给左边面积
想要右边面积(p 值几乎都是右边)就用 1 - p...(),或者加参数 lower.tail = FALSE。p 值非常小(比如 1e-10)时用 lower.tail = FALSE 更精确。

1.3 卡方分布 χ²(k):k 个标准正态的平方和

如果 Z1,…,ZkZ_1, \dots, Z_k 独立且都是 N(0,1)N(0,1),那么 V=Z12+⋯+Zk2∼χk2V = Z_1^2 + \cdots + Z_k^2 \sim \chi^2_k。kk 叫自由度。它永远 ≥ 0,均值 = kk,右偏。

在回归里它出现在:(n−p)σ^2σ2=SSresσ2∼χn−p2\dfrac{(n-p)\hat\sigma^2}{\sigma^2} = \dfrac{\text{SSres}}{\sigma^2} \sim \chi^2_{n-p}。直觉:残差平方和就是"一堆正态的平方加起来"。

Rch01 · 1.3(模拟演示,可跳过)
k <- 5
Z <- matrix(rnorm(100000 * k), ncol = k)
V <- rowSums(Z^2)                              # 每行 5 个标准正态的平方和
hist(V, breaks = 80, freq = FALSE)
curve(dchisq(x, df = k), add = TRUE, col = "red", lwd = 2)   # 红线和直方图完全重合
mean(V)                                        # 约 5 = k

1.4 t 分布 t(k):正态除以"估计出来的标准差"

定义:Z∼N(0,1)Z \sim N(0,1) 和 V∼χk2V \sim \chi^2_k 独立,则

T=ZV/k∼tk.T = \frac{Z}{\sqrt{V/k}} \sim t_k .

为什么要它?如果知道真实的 σ\sigma,b1−β1σ/Sxx\dfrac{b_1 - \beta_1}{\sigma/\sqrt{S_{xx}}} 是标准正态。但 σ\sigma 不知道,只能用估计值 σ^\hat\sigma 代替。代替之后多了一份"估计 σ 的不确定性",分布就从正态变成 t:形状一样是钟形,但尾巴更厚(极端值更容易出现)。自由度越大,越接近正态。

Rch01 · 1.4
qt(0.975, df = 4)     # 2.776:自由度小,临界值比 1.96 大很多
qt(0.975, df = 100)   # 1.984:自由度大,接近 1.96
Console 输出
[1] 2.776445
[1] 1.983972

1.5 F 分布 F(d₁, d₂):两个卡方(各自除以自由度)之比

F=V1/d1V2/d2∼Fd1,d2,V1∼χd12, V2∼χd22 独立F = \frac{V_1 / d_1}{V_2 / d_2} \sim F_{d_1, d_2}, \qquad V_1 \sim \chi^2_{d_1},\ V_2 \sim \chi^2_{d_2} \text{ 独立}

有两个自由度:分子 d1d_1、分母 d2d_2,顺序不能反。F 永远 ≥ 0。在回归里:F=MSregMSresF = \dfrac{\text{MSreg}}{\text{MSres}},"模型解释的变异"除以"没解释的变异"。F 越大,模型越有用,所以 F 检验永远只看右尾。

一个超重要的关系:如果 T∼tkT \sim t_k,那么 T2∼F1,kT^2 \sim F_{1,k}。这就是为什么简单线性回归里 F = t²(第 4 章)。

Rch01 · 1.5
1 - pf(3.10, 3, 20)    # F(3,20) 中 3.10 右边的面积 ≈ 0.05
qt(0.975, 13)^2        # t 临界值的平方
qf(0.95, 1, 13)        # 等于 F(1,13) 的临界值
Console 输出
[1] 0.04992453
[1] 4.667193
[1] 4.667193

玩法:选 t 分布,把自由度从 1 拖到 60,看尾巴怎么变薄;拖动"观测到的统计量",看红色面积(p 值)怎么变小;切换到 F 分布,注意它只有右尾。

1.6 考试最常用的四行 p 值代码(背下来)

场景R 代码
t 检验,双侧(partial t、β = 0 检验)2 * (1 - pt(abs(t), df))
F 检验(overall F、比较模型、sequential F)1 - pf(F, df1, df2) 或 pf(F, df1, df2, lower.tail = FALSE)
t 临界值(置信区间用)qt(1 - alpha/2, df),例如 95% → qt(0.975, df),97% → qt(0.985, df)
F 临界值qf(1 - alpha, df1, df2)
Rch01 · 1.6(数字来自 2025 真题答案)
2 * (1 - pt(abs(2.118391), 38))       # 2025 (c) 的 p 值 0.04073866
pf(30.32171, 4, 38, lower.tail = FALSE)   # 2025 (a) 的 p 值 2.311e-11
Console 输出
[1] 0.04073866
[1] 2.311451e-11

看,两个数和 2025 年官方答案完全一样。实际考试时 summary 会直接给出这些 p 值,你只需复制;但理解它们怎么来的,判断题和"写出 null distribution"就不会错。

1.7 样本均值和样本方差的分布(Tutorial Week 1 Q7)

设 Y1,…,YnY_1, \dots, Y_n 独立同分布 N(μ,σ2)N(\mu, \sigma^2),Yˉ=1n∑Yi\bar Y = \frac1n\sum Y_i,S2=1n−1∑(Yi−Yˉ)2S^2 = \frac{1}{n-1}\sum (Y_i - \bar Y)^2。四个关键结论:

  1. Yˉ∼N(μ,σ2/n)\bar Y \sim N(\mu, \sigma^2/n)(平均值更集中,方差缩小 n 倍)
  2. (n−1)S2/σ2∼χn−12(n-1)S^2/\sigma^2 \sim \chi^2_{n-1}(少了 1 个自由度,因为用 Yˉ\bar Y 代替了 μ\mu)
  3. Yˉ\bar Y 和 S2S^2 独立
  4. Yˉ−μS/n∼tn−1\dfrac{\bar Y - \mu}{S/\sqrt n} \sim t_{n-1}(= 正态 / √(卡方/自由度),正好是 t 的定义)

回归里完全是同一个套路,只是 n−1n-1 换成 n−pn-p(pp = 参数个数):bj−βjse^(bj)∼tn−p\dfrac{b_j - \beta_j}{\widehat{\mathrm{se}}(b_j)} \sim t_{n-p}。

📄 原题 · Tutorial Week 1 Q7 (a)(d)(e)
Let Y₁, …, Yₙ be independent random variables each with distribution N(μ, σ²). (a) What is the distribution of Ȳ? (d) What is the distribution of (n − 1)S²/σ²? (e) What is the distribution of (Ȳ − μ)/(S/√n)?
答案
(a) N(μ,σ2/n)N(\mu, \sigma^2/n);(d) χn−12\chi^2_{n-1};(e) tn−1t_{n-1},因为它 = (Yˉ−μ)/(σ/n)[(n−1)S2/σ2]/(n−1)\dfrac{(\bar Y-\mu)/(\sigma/\sqrt n)}{\sqrt{[(n-1)S^2/\sigma^2]/(n-1)}},分子是 N(0,1),分母是 √(χ²/自由度),且两者独立。
Rch01 · 1.7:模拟验证 Var(Ȳ) = σ²/n(可跳过)
mu <- 10; sigma <- 2; n <- 8
sims <- replicate(20000, { y <- rnorm(n, mu, sigma); c(mean(y), var(y)) })
var(sims[1, ])        # 约 0.5 = 4/8
Console 输出
[1] 0.5012749
✅ 本章检查清单
  • 能用一句话说出 χ²、t、F 分别是怎么构造的
  • 知道 t 检验看两侧、F 检验只看右侧
  • 会写 2*(1-pt(abs(t), df)) 和 1-pf(F, d1, d2)
  • 知道 T∼tk⇒T2∼F1,kT \sim t_k \Rightarrow T^2 \sim F_{1,k}

第 2 章 · 假设检验与置信区间

本章目标
掌握一个万能模板:H0/H1 → 检验统计量 → 它在 H0 下的分布 → p 值 → 结论。后面的 t 检验、F 检验、离群点检验全是这个模板换个统计量。
配套脚本:R/ch02_tests_ci.R 考试关联:2025 年 Q2(a) 要求 "Type your conclusion in plain language",这一章教你怎么写。

2.1 假设检验 = 法庭审判

把检验想成法庭:

2.2 万能五步模板

  1. 写假设:H0:θ=θ0H_0: \theta = \theta_0 vs H1:θ≠θ0H_1: \theta \neq \theta_0
  2. 检验统计量:大多数情况是 T=估计值−假设值标准误T = \dfrac{\text{估计值} - \text{假设值}}{\text{标准误}}
  3. 零分布(null distribution):H0 为真时统计量服从什么分布,比如 tn−pt_{n-p} 或 Fq,n−pF_{q, n-p}。考试会让你从下拉框里选。
  4. p 值:t 检验 p=P(∣T∣≥∣tobs∣)p = P(|T| \ge |t_{obs}|);F 检验 p=P(F≥fobs)p = P(F \ge f_{obs})
  5. 结论:p < α → reject H0;用题目的语言解释
🖥️ RStudio 跟做:ch02 第 2.1 节(热身例子)
某饮料宣称平均含糖 10 克,抽了 8 瓶。检验 H0:μ=10H_0: \mu = 10 vs H1:μ≠10H_1: \mu \ne 10。
Rch02 · 2.1

sugar <- c(10.8, 9.6, 11.2, 10.9, 10.4, 11.5, 10.1, 10.7)
n <- length(sugar)
t_obs <- (mean(sugar) - 10) / (sd(sugar) / sqrt(n))   # (估计 - 假设值) / 标准误

t_obs
2 * (1 - pt(abs(t_obs), df = n - 1))                   # 双侧 p 值
Console 输出
[1] 3.02829
[1] 0.01916076

p = 0.019 < 0.05 → 拒绝 H0:有证据表明平均含糖量不是 10 克。

2.3 结论怎么写(英文模板,直接背)

📝 考试结论模板

拒绝时:"The p-value is 2.311e-11, which is smaller than α = 0.05, so we reject H0. There is strong evidence that at least one of the predictors is linearly related to the response."

不拒绝时:"The p-value is 0.3749 > 0.05, so we do not reject H0. There is no significant evidence that the coefficients of QUES and LEGAL are different from zero, i.e. the smaller model is adequate."

三要素:① 写出 p 值和 α 的比较 ② reject / do not reject H0 ③ 用题目里的变量名翻译成人话。2025 年官方示范答案只写了 "p-value = 2.311e-11 is smaller than alpha so we reject the null hypothesis",所以前两要素是必须的,第三个加上更稳。

2.4 拒绝域:和 p 值等价的另一种说法

也可以先算出临界值,看统计量是否"越界":双侧 t 检验在 ∣tobs∣>tα/2; df|t_{obs}| > t_{\alpha/2;\,df} 时拒绝。

Rch02 · 2.2

crit <- qt(1 - 0.05 / 2, df = 7)   # 临界值

crit
abs(t_obs) > crit                  # TRUE:落在拒绝域
Console 输出
[1] 2.364624
[1] TRUE

"p < α" 和 "|t| > 临界值" 永远同时成立或同时不成立。在第 1 章的分布演示里:红线越过绿线 ⇔ 红色面积 < 0.05。

2.5 置信区间:估计 ± 临界值 × 标准误

100(1−α)% CI=θ^±tα/2; df×se(θ^)\text{100}(1-\alpha)\% \text{ CI} = \hat\theta \pm t_{\alpha/2;\,df} \times \mathrm{se}(\hat\theta)
Rch02 · 2.3

mean(sugar) + c(-1, 1) * qt(0.975, 7) * sd(sugar) / sqrt(n)
Console 输出
[1] 10.14245 11.15755

区间和检验的关系:95% CI 不包含 10 ⇔ 5% 水平的双侧检验拒绝 H0:μ=10H_0: \mu = 10。回归里也一样:系数的 95% CI 不包含 0 ⇔ partial t 检验 p < 0.05。

每点一次"再抽 100 个样本",就像重新做 100 次实验。大约 95 个区间会盖住真值。"95%"描述的是方法的可靠程度,不是"真值有 95% 概率在这个区间里"。(这句话可能出判断题。)

2.6 单侧检验(了解即可)

H1:μ>10H_1: \mu > 10 时只看右尾:1 - pt(t_obs, df_t);H1:μ<10H_1: \mu < 10 时只看左尾:pt(t_obs, df)。R 的 summary 给出的都是双侧 p 值。题目没说的话,默认双侧。

⚠️ 易错点
  • 不拒绝 H0 ≠ H0 是对的。写 "there is no significant evidence that…",不要写 "we accept H0 / prove H0"。
  • p 值不是"H0 为真的概率"。
  • F 检验没有"双侧",p 值就是右尾面积。
✅ 本章检查清单
  • 能说出五步模板
  • 会写英文结论三要素
  • 知道 CI 不含 0 ⇔ 检验显著

第 3 章 · 简单线性回归:模型、最小二乘、读懂 summary

本章目标
知道线性模型在说什么;理解"最小二乘";能在 summary() 的输出里指出每一个数是什么。
配套脚本:R/ch03_slr_least_squares.R 原题:Lab Week 2 Q1、Q3 考试关联:Q2 所有小题都是从 summary / anova 里读数。

3.1 模型在说什么

我们观察到 n 对数据 (xi,yi)(x_i, y_i)。简单线性回归(simple linear regression, SLR)假设:

yi=β0+β1xi+εi,i=1,…,ny_i = \beta_0 + \beta_1 x_i + \varepsilon_i, \qquad i = 1, \dots, n

模型假设(第 10 章会教你怎么检查,Lab 2 Q1(f) 问过):

  1. 误差互不相关(uncorrelated)
  2. 误差均值为 0 ⇒ y 的均值和 x 是线性关系
  3. 误差方差都相同 Var(εi)=σ2\mathrm{Var}(\varepsilon_i) = \sigma^2(constant variance)
  4. (做检验时还需要)误差服从正态分布 εi∼N(0,σ2)\varepsilon_i \sim N(0, \sigma^2)

真实的 β0,β1,σ2\beta_0, \beta_1, \sigma^2 我们永远看不到,只能用数据估计:估计值写成 b0,b1,σ^2b_0, b_1, \hat\sigma^2(有的书写 β^0,β^1\hat\beta_0, \hat\beta_1)。

3.2 最小二乘:画一条"离所有点最近"的线

对任何一条线 y=b0+b1xy = b_0 + b_1 x,每个点到线的竖直距离叫残差 ei=yi−(b0+b1xi)e_i = y_i - (b_0 + b_1 x_i)。最小二乘(least squares)就是选 b0,b1b_0, b_1 让

S(b0,b1)=∑i=1n(yi−b0−b1xi)2S(b_0, b_1) = \sum_{i=1}^n (y_i - b_0 - b_1 x_i)^2

最小。为什么平方?正负残差不会抵消,而且数学上好算(可以求导)。

自己拖两个滑块,试着让 SSres 尽量小,再点"跳到最小二乘答案"对比。你会发现怎么调都不可能比答案更小 —— 这就是"最小"二乘。

求导得到公式(Week 1 讲义的推导)

对 b0,b1b_0, b_1 分别求偏导并令其为 0,得到两个正规方程(normal equations):

∑i(yi−b0−b1xi)=0,∑ixi(yi−b0−b1xi)=0\sum_{i}(y_i - b_0 - b_1x_i) = 0, \qquad \sum_i x_i(y_i - b_0 - b_1x_i) = 0

也就是"残差之和 = 0"和"残差与 x 的乘积之和 = 0"。解出来:

b1=SxySxx,b0=yˉ−b1xˉb_1 = \frac{S_{xy}}{S_{xx}}, \qquad b_0 = \bar y - b_1 \bar x

其中

Sxx=∑i(xi−xˉ)2=∑xi2−(∑xi)2n,Sxy=∑i(xi−xˉ)(yi−yˉ)=∑xiyi−(∑xi)(∑yi)n,Syy=∑i(yi−yˉ)2S_{xx} = \sum_i (x_i - \bar x)^2 = \sum x_i^2 - \frac{(\sum x_i)^2}{n}, \quad S_{xy} = \sum_i (x_i-\bar x)(y_i - \bar y) = \sum x_iy_i - \frac{(\sum x_i)(\sum y_i)}{n}, \quad S_{yy} = \sum_i (y_i - \bar y)^2

(Tutorial Week 1 Q3 就是证明这两个等号。)误差方差的估计:

σ^2=1n−2∑iei2=SSresn−2=Syy−b12Sxxn−2\hat\sigma^2 = \frac{1}{n-2}\sum_i e_i^2 = \frac{\text{SSres}}{n-2} = \frac{S_{yy} - b_1^2 S_{xx}}{n-2}

分母是 n−2n-2 而不是 nn:因为估计了 2 个参数,"用掉"了 2 个自由度。这样 σ^2\hat\sigma^2 才是无偏的(Tutorial Week 3 Q1)。

3.3 Lab Week 2 Q1:第一次完整地跑一个回归

📄 原题 · Lab Week 2 Q1 (a)(b)(c)
The earnings per share (EPS) for Wendy's International for the years 1977 through 1985 are shown in the table below (Coded Year 1–9; EPS 0.27, 0.42, 0.39, 0.50, 0.57, 0.64, 0.76, 0.93, 1.03).
(a) After entering the data in R, produce a scatterplot which graphs EPS against the coded year.
(b) Use R to fit a simple linear regression model with EPS as the response and (coded) year as the predictor. Add the fitted line to the scatterplot.
(c) Identify on the R output the least squares estimates of the intercept and slope and the estimate of the error standard deviation. Also, what is the coefficient of determination (R²)?
Rch03 · 3.1–3.2
year <- 1:9                       # 1:9 就是 c(1,2,...,9)
EPS  <- c(0.27, 0.42, 0.39, 0.50, 0.57, 0.64, 0.76, 0.93, 1.03)
wendys <- data.frame(year, EPS)
plot(EPS ~ year, data = wendys, pch = 19)       # (a)
wendys_mod <- lm(EPS ~ year, data = wendys)     # (b) 拟合
abline(wendys_mod, col = "red")                 #     画线
summary(wendys_mod)                             # (c)
Console 输出
Call:
lm(formula = EPS ~ year, data = wendys)

Residuals:
     Min       1Q   Median       3Q      Max
-0.06306 -0.04056 -0.02139  0.04528  0.08028

Coefficients:
            Estimate Std. Error t value Pr(>|t|)
(Intercept) 0.158056   0.039709    3.98  0.00532 **
year        0.090833   0.007057   12.87 3.97e-06 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 0.05466 on 7 degrees of freedom
Multiple R-squared:  0.9595,	Adjusted R-squared:  0.9537
F-statistic: 165.7 on 1 and 7 DF,  p-value: 3.965e-06

3.4 summary 输出逐行解剖(考试 Q2 天天用)

输出里的位置含义符号本例
Call:你拟合的是哪个模型EPS ~ year
Residuals:残差的五数概括(最小、四分位、中位、最大)eie_i大致对称就好
(Intercept) 行 Estimate截距估计b0b_00.158056
year 行 Estimate斜率估计:year 每 +1,EPS 平均 +0.0908b1b_10.090833
Std. Error 列估计值的标准误(估计有多不准)se(bj)\mathrm{se}(b_j)0.007057
t value 列检验 H0:βj=0H_0: \beta_j = 0 的 t 统计量 = Estimate / Std. Errortt12.87
Pr(>|t|) 列上面那个检验的双侧 p 值p3.97e-06
星号 ***p 值的快速标记:*** < 0.001,** < 0.01,* < 0.05,. < 0.1
Residual standard error误差标准差的估计 σ^\hat\sigma(注意是 σ 不是 σ²!)σ^\hat\sigma0.05466
on 7 degrees of freedom残差自由度 n−pn - p(这里 9 − 2)n−pn-p7
Multiple R-squared模型解释了 y 的多少比例的变异R2R^20.9595
Adjusted R-squared考虑了参数个数的 R²(第 6 章)Rˉ2\bar R^20.9537
F-statistic … on 1 and 7 DF, p-valueoverall F 检验:H0H_0: 所有斜率 = 0;分布 Fp−1, n−pF_{p-1,\,n-p}F165.7, F(1,7)
💡 用代码把数取出来(要更多小数位时)
Rch03 · 3.2
wendys_sum <- summary(wendys_mod)
wendys_sum$coefficients          # 整张系数表,小数位更多
wendys_sum$coefficients[2, 1]    # 第 2 行第 1 列 = b1
wendys_sum$sigma                 # sigma-hat
wendys_sum$r.squared             # R^2
wendys_sum$fstatistic            # F 值和两个自由度
coef(wendys_mod)                 # 只要系数
Console 输出
              Estimate  Std. Error  t value     Pr(>|t|)
(Intercept) 0.15805556 0.039709455  3.98030 5.321858e-03
year        0.09083333 0.007056555 12.87219 3.965299e-06
[1] 0.09083333
[1] 0.05465984
[1] 0.9594657
   value    numdf    dendf
165.6933   1.0000   7.0000
(Intercept)        year
 0.15805556  0.09083333

3.5 用公式手算一遍(对照 lm)

Rch03 · 3.3
x <- wendys$year; y <- wendys$EPS; n <- length(y)
Sxx <- sum((x - mean(x))^2)
Sxy <- sum((x - mean(x)) * (y - mean(y)))
b1 <- Sxy / Sxx
b0 <- mean(y) - b1 * mean(x)
sigma_hat <- sqrt(sum((y - b0 - b1 * x)^2) / (n - 2))
c(b0, b1, sigma_hat)          # 和 summary 一模一样
Console 输出
[1] 0.15805556 0.09083333 0.05465984
Rch03 · 3.4:拟合值与残差
fitted(wendys_mod)              # y-hat_i
residuals(wendys_mod)           # e_i = y_i - y-hat_i
sum(residuals(wendys_mod))      # 有截距时 = 0(显示成 1e-18 这种就是 0)
Console 输出
        1         2         3         4         5         6         7         8         9
0.2488889 0.3397222 0.4305556 0.5213889 0.6122222 0.7030556 0.7938889 0.8847222 0.9755556
          1           2           3           4           5           6           7           8           9
 0.02111111  0.08027778 -0.04055556 -0.02138889 -0.04222222 -0.06305556 -0.03388889  0.04527778  0.05444444
[1] 3.469447e-18

3.6 Lab Week 2 Q3:只给"求和"也能算

📄 原题 · Lab Week 2 Q3 (b)–(f)
The number of deaths caused by firearms in Australia (rate per 100,000), 1983–1997, response rate (y), predictor coded year cyear (years since 1982).
(b) If Σxᵢ = 120.0, Σyᵢ = 54.4, Σxᵢ² = 1240.0, Σyᵢ² = 204.588 and Σxᵢyᵢ = 392.61, find the least squares estimates of the slope and intercept and the estimated error variance.
(c) Confirm your answers in part b) by entering the data into R… (d) Is there strong evidence that the rate of deaths shows some kind of linear trend? (e) Give an estimate of how much the mean response changes for a one unit change in the predictor. (f) What proportion of variation in the response is explained by the predictor?
先自己算 (b),再看答案

n = 15。Sxx=1240−1202/15=280S_{xx} = 1240 - 120^2/15 = 280;Sxy=392.61−120×54.4/15=−42.59S_{xy} = 392.61 - 120 \times 54.4/15 = -42.59;Syy=204.588−54.42/15=7.2949S_{yy} = 204.588 - 54.4^2/15 = 7.2949。

b1=−42.59/280=−0.1521b_1 = -42.59/280 = -0.1521;b0=54.4/15−(−0.1521)(120/15)=4.8435b_0 = 54.4/15 - (-0.1521)(120/15) = 4.8435;σ^2=(Syy−b12Sxx)/13=0.0630\hat\sigma^2 = (S_{yy} - b_1^2 S_{xx})/13 = 0.0630。

Rch03 · 3.6
n <- 15
Sxx <- 1240.0 - 120.0^2 / n
Syy <- 204.588 - 54.4^2 / n
Sxy <- 392.61 - 120.0 * 54.4 / n
b1 <- Sxy / Sxx;  b0 <- 54.4 / n - b1 * 120.0 / n
sigma2 <- (Syy - b1^2 * Sxx) / (n - 2)
round(c(b0 = b0, b1 = b1, sigma2 = sigma2), 4)

firearms <- read.csv("firearms.csv")            # 记得先 setwd 到 datasets
firearms$cyear <- firearms$year - 1982          # 新建一列 coded year
summary(lm(rate ~ cyear, data = firearms))      # (c) 验证
Console 输出
     b0      b1  sigma2
 4.8435 -0.1521  0.0630

Coefficients:
            Estimate Std. Error t value Pr(>|t|)
(Intercept)   4.8435     0.1364   35.52 2.48e-14 ***
cyear        -0.1521     0.0150  -10.14 1.53e-07 ***
Residual standard error: 0.251 on 13 degrees of freedom
Multiple R-squared:  0.8878,	Adjusted R-squared:  0.8792
F-statistic: 102.9 on 1 and 13 DF,  p-value: 1.527e-07

(d) cyear 的 p 值 = 1.53e-07 < 0.05 → strong evidence of a linear (decreasing) trend。(e) 每过一年,平均死亡率下降 0.1521(每 10 万人)。(f) R2=0.8878R^2 = 0.8878:88.78% 的变异被 cyear 解释。(注意 0.2512=0.06300.251^2 = 0.0630,和手算的 σ^2\hat\sigma^2 对上了。)

⚠️ 易错点
  • Residual standard error 是 σ^\hat\sigma,题目问 "error variance" 要平方。
  • lm(y ~ x) 左边是响应变量。题目说 "EPS as the response" → EPS 在左边。
  • 新建变量写成 数据框$新列名 <- ...,否则 lm(..., data = 数据框) 找不到它。
✅ 本章检查清单
  • 能写出 SLR 模型和 4 个假设
  • 会 b1=Sxy/Sxxb_1 = S_{xy}/S_{xx}、b0=yˉ−b1xˉb_0 = \bar y - b_1\bar x、σ^2=SSres/(n−2)\hat\sigma^2 = \text{SSres}/(n-2)
  • 能在 summary 里指出 b0,b1b_0, b_1、se、t、p、σ^\hat\sigma、R2R^2、F

第 4 章 · SLR 的推断:t 检验、置信区间、ANOVA、预测区间

本章目标
会检验"x 和 y 有没有关系";会给系数和预测做区间;看懂 ANOVA 表;分清均值的置信区间和预测区间(2025 年考了 97% PI)。
配套脚本:R/ch04_slr_inference.R 主例子:zinc 数据(讲义 Week 2) 原题:Lab Week 2 Q1(d)(e)(f)、Q2

4.1 估计量的分布(为什么能做检验)

在正态假设下(Week 2 讲义 "Distribution theory"):

b1∼N ⁣(β1,σ2Sxx),b0∼N ⁣(β0,σ2(1n+xˉ2Sxx)),(n−2)σ^2σ2∼χn−22b_1 \sim N\!\left(\beta_1, \frac{\sigma^2}{S_{xx}}\right), \qquad b_0 \sim N\!\left(\beta_0, \sigma^2\Big(\frac1n + \frac{\bar x^2}{S_{xx}}\Big)\right), \qquad \frac{(n-2)\hat\sigma^2}{\sigma^2} \sim \chi^2_{n-2}

而且 σ^2\hat\sigma^2 和 (b0,b1)(b_0, b_1) 独立。把 σ 换成 σ^\hat\sigma,得到(正态 / √(卡方/自由度) = t):

b1−β1σ^/Sxx∼tn−2\frac{b_1 - \beta_1}{\hat\sigma/\sqrt{S_{xx}}} \sim t_{n-2}

分母 σ^/Sxx\hat\sigma/\sqrt{S_{xx}} 就是 summary 里的 Std. Error,记作 se(b1)\mathrm{se}(b_1)。

Tutorial Week 1 Q5、Q6 让你证明 Var(b0)\mathrm{Var}(b_0) 和 Cov(b0,b1)=−σ2xˉ/Sxx\mathrm{Cov}(b_0, b_1) = -\sigma^2\bar x/S_{xx},第 11 章有完整证明。

4.2 检验 H0: β₁ = 0("有没有线性关系")

t=b1−0se(b1)∼H0tn−2,p=2P(Tn−2≥∣t∣)t = \frac{b_1 - 0}{\mathrm{se}(b_1)} \overset{H_0}{\sim} t_{n-2}, \qquad p = 2P(T_{n-2} \ge |t|)
Rch04 · 开头 + 4.1

setwd("C:/Users/Cestbon/Desktop/MATHLAB/datasets")
zinc <- read.csv("zinc.csv")
model_zinc <- lm(plant ~ sediment, data = zinc)
summary(model_zinc)
Console 输出
Coefficients:
            Estimate Std. Error t value Pr(>|t|)
(Intercept) -14.9307    12.5759  -1.187    0.256
sediment      0.8566     0.1531   5.596 8.69e-05 ***
---
Residual standard error: 10.15 on 13 degrees of freedom
Multiple R-squared:  0.7066,	Adjusted R-squared:  0.684
F-statistic: 31.31 on 1 and 13 DF,  p-value: 8.69e-05

t=0.8566/0.1531=5.596t = 0.8566/0.1531 = 5.596,自由度 15−2=1315 - 2 = 13,p=8.69×10−5p = 8.69\times10^{-5} < 0.05 → 有很强的证据说明 sediment 和 plant 有线性关系。验证:

Rch04 · 4.1

2 * (1 - pt(5.595527, df = 13))
Console 输出
[1] 8.690339e-05

4.3 β₁ 的置信区间

b1±tα/2; n−2 se(b1)b_1 \pm t_{\alpha/2;\,n-2}\ \mathrm{se}(b_1)
Rch04 · 4.2

0.8565889 + c(-1, 1) * qt(0.975, 13) * 0.1530846   # 手算

confint(model_zinc)                                 # 一行搞定(默认 95%)

confint(model_zinc, level = 0.99)                   # 99%
Console 输出
[1] 0.5258698 1.1873080
                  2.5 %    97.5 %
(Intercept) -42.0992085 12.237748
sediment      0.5258698  1.187308
                  0.5 %    99.5 %
(Intercept) -52.8126677 22.951207
sediment      0.3954559  1.317722

解释:"With 95% confidence, the mean plant zinc increases by between 0.526 and 1.187 for a one-unit increase in sediment zinc." 区间不含 0,和 t 检验结论一致。

4.4 ANOVA:把总变异拆成两块

基本恒等式(fundamental identity):每个点有 yi−yˉ=(y^i−yˉ)+(yi−y^i)y_i - \bar y = (\hat y_i - \bar y) + (y_i - \hat y_i)。平方再求和,交叉项正好是 0:

∑(yi−yˉ)2⏟SStotal=∑(y^i−yˉ)2⏟SSreg:模型解释的+∑(yi−y^i)2⏟SSres:没解释的\underbrace{\sum (y_i - \bar y)^2}_{\text{SStotal}} = \underbrace{\sum(\hat y_i - \bar y)^2}_{\text{SSreg:模型解释的}} + \underbrace{\sum (y_i - \hat y_i)^2}_{\text{SSres:没解释的}}

ANOVA 表就是把这个分解排成表格(p = 参数个数,SLR 里 p = 2):

SourceDfSum SqMean SqF value
Regression(R 里显示为变量名)p−1p-1SSregMSreg = SSreg/(p−1)F = MSreg/MSres
Residualsn−pn-pSSresMSres = SSres/(n−p) = σ^2\hat\sigma^2
Total(R 不显示)n−1n-1SStotal
Rch04 · 4.3

anova(model_zinc)
Console 输出
Analysis of Variance Table

Response: plant
          Df Sum Sq Mean Sq F value   Pr(>F)
sediment   1 3224.7  3224.7   31.31 8.69e-05 ***
Residuals 13 1338.9   103.0

记住两条:Mean Sq = Sum Sq / Df;F = 这一行的 Mean Sq / Residuals 的 Mean Sq。Residuals 的 Mean Sq 就是 σ^2\hat\sigma^2(10.152=103.010.15^2 = 103.0)。第 7 章"补全 ANOVA 表"全靠这两条。

4.5 R²,以及 F = t²

R2=SSregSStotal=1−SSresSStotal=3224.74563.5=0.7066R^2 = \frac{\text{SSreg}}{\text{SStotal}} = 1 - \frac{\text{SSres}}{\text{SStotal}} = \frac{3224.7}{4563.5} = 0.7066

在 SLR 里,F 检验 (H0:β1=0H_0: \beta_1 = 0) 和 t 检验是同一个检验:F=t2F = t^2,p 值完全相同(5.5962=31.315.596^2 = 31.31,p 都是 8.69e-05)。这是因为 tk2∼F1,kt_{k}^2 \sim F_{1,k}。多元回归里不再成立:overall F 检验的是所有斜率一起是否为 0。

📄 原题 · Lab Week 2 Q1 (d)(e)
(d) Identify on the R output the p-values for testing the hypotheses β₀ = 0 and β₁ = 0 using the t-statistic discussed in lectures.
(e) Identify an F-statistic in summary output for testing H0: β₁ = 0 and verify that this statistic is the square of the t-statistic which was used for testing the same hypothesis.
答案
(d) β₀: p = 0.00532;β₁: p = 3.97e-06(在 Pr(>|t|) 列)。(e) F = 165.7,t2=12.872192=165.69t^2 = 12.87219^2 = 165.69。
Rch04 · 4.5

year <- 1:9
EPS  <- c(0.27, 0.42, 0.39, 0.50, 0.57, 0.64, 0.76, 0.93, 1.03)
wendys_sum <- summary(lm(EPS ~ year))
c(t_squared = wendys_sum$coefficients[2, 3]^2, F = unname(wendys_sum$fstatistic[1]))
Console 输出
t_squared         F
 165.6933  165.6933

4.6 预测:均值的置信区间 vs 新观测的预测区间(必考)

给一个新的 x0x_0,点预测都是 y^0=b0+b1x0\hat y_0 = b_0 + b_1 x_0。但有两种问法:

Confidence interval for the mean responsePrediction interval for a new response
问的是所有 x=x0x = x_0 的个体的平均 y 在哪里一个新个体的 y 会落在哪里
公式y^0±tα/2;n−2 σ^1n+(x0−xˉ)2Sxx\hat y_0 \pm t_{\alpha/2;n-2}\,\hat\sigma\sqrt{\dfrac1n + \dfrac{(x_0-\bar x)^2}{S_{xx}}}y^0±tα/2;n−2 σ^1+1n+(x0−xˉ)2Sxx\hat y_0 \pm t_{\alpha/2;n-2}\,\hat\sigma\sqrt{\mathbf{1} + \dfrac1n + \dfrac{(x_0-\bar x)^2}{S_{xx}}}
Rinterval = "confidence"interval = "prediction"
宽窄窄;n → ∞ 时宽度 → 0永远更宽(多了新个体自己的误差 σ²,那个"1")

关键词识别:题目说 "mean …" → confidence;说 "a new movie / a new observation / predict the revenue of …" → prediction。2025 年原题:"Obtain a 97% prediction interval for the USRevenue"。

Rch04 · 4.6

new <- data.frame(sediment = 70)       # 列名必须和模型里的一模一样!

predict(model_zinc, new)                                                   # 点预测

predict(model_zinc, new, interval = "confidence", level = 0.99)            # 均值 CI

predict(model_zinc, new, interval = "prediction", level = 0.99)            # 新值 PI
Console 输出
       1
45.03049
       fit      lwr      upr
1 45.03049 35.80737 54.25361
       fit      lwr      upr
1 45.03049 13.09945 76.96154

输出三列:fit = 点预测,lwr = 下界,upr = 上界。Möbius 里 "enter lower and then upper bound" 就填 lwr 和 upr。

⚠️ predict 的三个坑
  • newdata 必须是 data.frame(...),列名和建模时完全一致(大小写也要一样)。
  • 多元回归时每一个预测变量都要给值(第 6 章)。
  • level = 0.97 写小数,不是 97。

4.7 Bonferroni:同时给多个参数做区间

分别做两个 95% 区间,"两个同时都对"的把握不到 95%。Bonferroni 的办法:k 个区间,每个用 1−α/k1 - \alpha/k 的水平,那么同时成立的概率至少 1−α1-\alpha。

Rch04 · 4.7

confint(model_zinc, level = 1 - 0.05 / 2)    # beta0 和 beta1 的"至少 95%"联合区间
Console 输出
                 1.25 %   98.75 %
(Intercept) -46.7808106 16.919350
sediment      0.4688811  1.244297

4.8 Lab Week 2 Q2(Forbes)

📄 原题 · Lab Week 2 Q2
The table below shows the personal savings rate and investment income tax liability for eight different countries. (a) Produce a scatterplot of Personal Savings Rate versus Investment Income Tax Liability. Do you think a simple linear regression model is appropriate? (b) Do you think there is any relationship between Personal Savings Rate and Investment Income Tax Liability? Justify your answer by referring to the p-value for an appropriate hypothesis test on the R regression output.
答案

(b) tax 的 partial t 检验 p = 0.0175 < 0.05(b₁ = −0.293),有证据表明存在负的线性关系:税越高,储蓄率越低。((a) 只有 8 个点,散点图大致线性,可以用但样本很小。)

Rch04 · 4.8

forbes <- read.table("forbes.txt", header = TRUE, sep = ",")   # 这个文件用逗号分隔

forbes_mod <- lm(save ~ tax, data = forbes)
summary(forbes_mod)
Console 输出
Coefficients:
            Estimate Std. Error t value Pr(>|t|)
(Intercept) 21.18094    2.53142   8.367 0.000158 ***
tax         -0.29293    0.09023  -3.247 0.017543 *
---
Residual standard error: 3.881 on 6 degrees of freedom
Multiple R-squared:  0.6372,	Adjusted R-squared:  0.5768
F-statistic: 10.54 on 1 and 6 DF,  p-value: 0.01754
✅ 本章检查清单
  • 会从 summary 读出 β₁ 的 t 和 p,并写结论
  • 会 confint(model, level = …)
  • 会读 ANOVA 表:Mean Sq = Sum Sq/Df,F = MS/MSres
  • 分清 confidence 和 prediction,会 predict(model, data.frame(...), interval = "prediction", level = 0.97)

第 5 章 · 矩阵形式的一般线性模型

本章目标
把模型写成 y=Xβ+εy = X\beta + \varepsilon;理解 b=(X⊤X)−1X⊤yb = (X^\top X)^{-1}X^\top y 和帽子矩阵 HH;掌握随机向量的期望/协方差规则。这是 Q1 证明题(15 分)的全部地基,也是判断题 "tr(H) = p" 的来源。
配套脚本:R/ch05_matrix_glm.R 原题:Lab Week 4 Q1、Tutorial Week 3 Q5–Q7

5.1 矩阵速成(只学要用的)

矩阵就是一个数字方阵,"n×pn \times p" 表示 n 行 p 列。向量是只有一列的矩阵(n×1n \times 1)。

操作写法意思R
转置A⊤A^\top行变列、列变行;(AB)⊤=B⊤A⊤(AB)^\top = B^\top A^\top(顺序反过来!)t(A)
矩阵乘法ABABA 的列数 = B 的行数才能乘;一般 AB≠BAAB \ne BAA %*% B
单位矩阵II对角线是 1,其余 0;AI=IA=AAI = IA = Adiag(n)
逆矩阵A−1A^{-1}AA−1=IAA^{-1} = I,只有方阵(且满秩)才有solve(A)
迹 tracetr(A)\mathrm{tr}(A)对角线元素之和;tr(AB)=tr(BA)\mathrm{tr}(AB) = \mathrm{tr}(BA)(循环性,超常用)sum(diag(A))
对称A⊤=AA^\top = A关于对角线对称
幂等AA=AAA = A乘自己还是自己(投影矩阵的特征)
Rch05 · 5.1

A <- matrix(c(1, 2, 3,
              4, 5, 6), nrow = 2, byrow = TRUE)    # byrow = TRUE:按行填

B <- matrix(c(1, 0,
              2, 1,
              0, 3), nrow = 3, byrow = TRUE)
A %*% B          # 矩阵乘法

t(A)             # 转置

M <- matrix(c(2, 1, 1, 3), 2, byrow = TRUE)
solve(M)         # 逆矩阵

sum(diag(M))     # 迹 = 2 + 3 = 5
Console 输出
     [,1] [,2]
[1,]    5   11
[2,]   14   23
     [,1] [,2]
[1,]    1    4
[2,]    2    5
[3,]    3    6
     [,1] [,2]
[1,]  0.6 -0.2
[2,] -0.2  0.4
[1] 5

5.2 一般线性模型 y = Xβ + ε

有 k 个预测变量时,yi=β0+β1xi1+⋯+βkxik+εiy_i = \beta_0 + \beta_1x_{i1} + \cdots + \beta_k x_{ik} + \varepsilon_i。把 n 个方程摞起来:

(y1y2⋮yn)⏟y (n×1)=(1x11⋯x1k1x21⋯x2k⋮⋮1xn1⋯xnk)⏟X (n×p)(β0β1⋮βk)⏟β (p×1)+(ε1ε2⋮εn)⏟ε\underbrace{\begin{pmatrix} y_1 \\ y_2 \\ \vdots \\ y_n\end{pmatrix}}_{y\ (n\times1)} = \underbrace{\begin{pmatrix} 1 & x_{11} & \cdots & x_{1k} \\ 1 & x_{21} & \cdots & x_{2k} \\ \vdots & & & \vdots \\ 1 & x_{n1} & \cdots & x_{nk}\end{pmatrix}}_{X\ (n\times p)} \underbrace{\begin{pmatrix}\beta_0 \\ \beta_1 \\ \vdots \\ \beta_k\end{pmatrix}}_{\beta\ (p\times1)} + \underbrace{\begin{pmatrix}\varepsilon_1 \\ \varepsilon_2 \\ \vdots \\ \varepsilon_n\end{pmatrix}}_{\varepsilon}

SLR 就是 p=2p = 2 的特例:X 有两列,(1, xix_i)。

5.3 最小二乘的矩阵解

最小化 S(β)=(y−Xβ)⊤(y−Xβ)S(\beta) = (y - X\beta)^\top(y - X\beta)。展开:y⊤y−2β⊤X⊤y+β⊤X⊤Xβy^\top y - 2\beta^\top X^\top y + \beta^\top X^\top X\beta。对 β 求导(讲义里的向量求导引理:∂(β⊤a)/∂β=a\partial(\beta^\top a)/\partial\beta = a,∂(β⊤Aβ)/∂β=2Aβ\partial(\beta^\top A\beta)/\partial\beta = 2A\beta,A 对称):

∂S∂β=−2X⊤y+2X⊤Xβ=0⟹X⊤X b=X⊤y⟹b=(X⊤X)−1X⊤y\frac{\partial S}{\partial \beta} = -2X^\top y + 2X^\top X\beta = 0 \quad\Longrightarrow\quad X^\top X\, b = X^\top y \quad\Longrightarrow\quad \boxed{b = (X^\top X)^{-1}X^\top y}
📄 原题 · Lab Week 4 Q1 (a)(b)
(a) Build a linear model from scratch (without using macro commands like 'lm') and use the function 'solve' to compute the least squares estimates, that is, solve the matrix equation (XᵀX)b = Xᵀy for the appropriately constructed (15×2) design matrix X.
(b) Compute σ̂² using the two formulas discussed in lectures: σ̂² = (Syy − b₁²Sxx)/(n − 2) and σ̂² = yᵀ(I − X(XᵀX)⁻¹Xᵀ)y/(n − 2). Verify that they give the same numerical answer.
Rch05 · 5.2–5.3

setwd("C:/Users/Cestbon/Desktop/MATHLAB/datasets")
firearms <- read.csv("firearms.csv")
firearms$Cyear <- firearms$year - 1982
x <- firearms$Cyear;  y <- firearms$rate
X <- cbind(1, x)                    # cbind = column bind:第一列 1,第二列 x

dim(X)                              # 15 x 2

b <- solve(t(X) %*% X, t(X) %*% y)  # 解 (X^T X) b = X^T y

b
n <- nrow(X); p <- ncol(X)
H <- X %*% solve(t(X) %*% X) %*% t(X)
as.numeric(t(y) %*% (diag(n) - H) %*% y) / (n - p)   # 第二个公式
Console 输出
[1] 15  2
        [,1]
   4.8435238
x -0.1521071
[1] 0.06297616

和第 3 章 lm 的结果(4.8435, −0.1521, 0.0630)完全一样。model.matrix(模型) 可以直接拿到 lm 用的 X。

5.4 帽子矩阵 H:给 y 戴上帽子

拟合值 y^=Xb=X(X⊤X)−1X⊤y\hat y = Xb = X(X^\top X)^{-1}X^\top y。中间那一坨叫帽子矩阵:

H=X(X⊤X)−1X⊤,y^=Hy,e=y−y^=(I−H)yH = X(X^\top X)^{-1}X^\top, \qquad \hat y = Hy, \qquad e = y - \hat y = (I - H)y

几何意义:XbXb(不管 b 取什么)组成一个"平面"(X 的列空间)。最小二乘就是在这个平面上找离 yy 最近的点,也就是把 yy 垂直投影到平面上。HH 就是投影操作。

H 的性质(证明题和判断题天天考,必须会证):

性质一行证明
对称 H⊤=HH^\top = HH⊤=(X(X⊤X)−1X⊤)⊤=X[(X⊤X)−1]⊤X⊤=X(X⊤X)−1X⊤H^\top = (X(X^\top X)^{-1}X^\top)^\top = X[(X^\top X)^{-1}]^\top X^\top = X(X^\top X)^{-1}X^\top(X⊤XX^\top X 对称,它的逆也对称)
幂等 HH=HHH = HX(X⊤X)−1X⊤X(X⊤X)−1⏟=IX⊤=HX(X^\top X)^{-1}\underbrace{X^\top X(X^\top X)^{-1}}_{=I}X^\top = H
HX=XHX = XX(X⊤X)−1X⊤X=XX(X^\top X)^{-1}X^\top X = X
(I−H)X=0(I-H)X = 0由上一条:X−HX=0X - HX = 0
I−HI-H 也对称、幂等(I−H)(I−H)=I−2H+HH=I−H(I-H)(I-H) = I - 2H + HH = I - H
tr(H)=p\mathrm{tr}(H) = ptr(X(X⊤X)−1X⊤)=tr((X⊤X)−1X⊤X)=tr(Ip)=p\mathrm{tr}(X(X^\top X)^{-1}X^\top) = \mathrm{tr}((X^\top X)^{-1}X^\top X) = \mathrm{tr}(I_p) = p(迹的循环性)
tr(I−H)=n−p\mathrm{tr}(I-H) = n-ptr(In)−tr(H)=n−p\mathrm{tr}(I_n) - \mathrm{tr}(H) = n - p
Rch05 · 5.4:用数字验证

max(abs(H - t(H)))       # 对称:≈ 0

max(abs(H %*% H - H))    # 幂等:≈ 0

sum(diag(H))             # 迹 = p = 2

max(abs(H %*% X - X))    # HX = X
Console 输出
[1] 8.326673e-17
[1] 5.551115e-17
[1] 2
[1] 3.552714e-15

(8e-17、3e-15 这种数就是 0,电脑做小数运算有微小误差。)HH 的对角线元素 hiih_{ii} 叫杠杆值(leverage),第 8 章专门讲。

5.5 随机向量的期望和协方差(证明题的"计算器")

随机向量 Y=(Y1,…,Yn)⊤Y = (Y_1, \dots, Y_n)^\top:

三条核心规则(A、B 是常数矩阵,c 是常数向量):

E(AY+c)=A E(Y)+cCov(AY)=A Cov(Y) A⊤Cov(AY,BZ)=A Cov(Y,Z) B⊤\boxed{E(AY + c) = A\,E(Y) + c} \qquad \boxed{\mathrm{Cov}(AY) = A\,\mathrm{Cov}(Y)\,A^\top} \qquad \boxed{\mathrm{Cov}(AY, BZ) = A\,\mathrm{Cov}(Y,Z)\,B^\top}

它们就是第 1 章"常数提出来要平方"的矩阵版:提到左边是 A,提到右边是 A⊤A^\top。

✍️ 2025 年真题 Q1 Part II (a)【5 分】

Let Y be n×1 and Z be p×1 random vectors, and let Σ = Cov(Y, Z) be their n×p covariance matrix. Suppose A and B are n×n and p×p matrices respectively, show that Cov(AY, BZ) = AΣBᵀ.

证明:由定义 Cov(U,V)=E[(U−EU)(V−EV)⊤]\mathrm{Cov}(U,V) = E[(U - EU)(V-EV)^\top],且 E(AY)=A EYE(AY) = A\,EY,E(BZ)=B EZE(BZ) = B\,EZ:

Cov(AY,BZ)=E[(AY−A EY)(BZ−B EZ)⊤]=E[A(Y−EY)(Z−EZ)⊤B⊤]\mathrm{Cov}(AY, BZ) = E\big[(AY - A\,EY)(BZ - B\,EZ)^\top\big] = E\big[A(Y - EY)(Z - EZ)^\top B^\top\big] =A E[(Y−EY)(Z−EZ)⊤] B⊤=AΣB⊤.■= A\,E\big[(Y-EY)(Z-EZ)^\top\big]\,B^\top = A\Sigma B^\top. \qquad\blacksquare

关键两步:① (B(Z−EZ))⊤=(Z−EZ)⊤B⊤(B(Z-EZ))^\top = (Z-EZ)^\top B^\top;② 常数矩阵可以提到期望外面(期望的线性)。令 Z=YZ = Y、B=AB = A 就得到 Cov(AY)=A Cov(Y)A⊤\mathrm{Cov}(AY) = A\,\mathrm{Cov}(Y)A^\top。

Rch05 · 5.7:模拟验证 Cov(AY) = A Σ Aᵀ(可跳过)

set.seed(5)
Sigma <- matrix(c(4, 1, 1, 2), 2, byrow = TRUE)
Y <- matrix(rnorm(2 * 100000), ncol = 2) %*% chol(Sigma)   # 10 万个协方差为 Sigma 的 Y

A <- matrix(c(1, 2, 3, -1), 2, byrow = TRUE)
cov(Y %*% t(A))          # 模拟

A %*% Sigma %*% t(A)     # 理论
Console 输出
         [,1]     [,2]
[1,] 16.15811 13.24897
[2,] 13.24897 32.31738
     [,1] [,2]
[1,]   16   13
[2,]   13   32

5.6 b 的均值和方差(Tutorial Week 3 Q5)

写 b=Cyb = Cy,C=(X⊤X)−1X⊤C = (X^\top X)^{-1}X^\top 是常数矩阵。已知 E(y)=XβE(y) = X\beta,Cov(y)=σ2I\mathrm{Cov}(y) = \sigma^2 I:

E(b)=C E(y)=(X⊤X)−1X⊤Xβ=β(无偏)E(b) = C\,E(y) = (X^\top X)^{-1}X^\top X\beta = \beta \quad(\textbf{无偏}) Cov(b)=C(σ2I)C⊤=σ2(X⊤X)−1X⊤X(X⊤X)−1=σ2(X⊤X)−1\mathrm{Cov}(b) = C(\sigma^2 I)C^\top = \sigma^2 (X^\top X)^{-1}X^\top X (X^\top X)^{-1} = \sigma^2 (X^\top X)^{-1}

所以 se(bj)=σ^[(X⊤X)−1]jj\mathrm{se}(b_j) = \hat\sigma\sqrt{[(X^\top X)^{-1}]_{jj}} —— 这就是 summary 里 Std. Error 的来源。

Rch05 · 5.5

fire_mod <- lm(rate ~ Cyear, data = firearms)
sigma2 <- summary(fire_mod)$sigma^2
sqrt(diag(sigma2 * solve(t(X) %*% X)))     # se(b0), se(b1)

summary(fire_mod)$coefficients[, "Std. Error"]
Console 输出
                    x
0.13635601 0.01499716
(Intercept)       Cyear
 0.13635601  0.01499716

Gauss–Markov 定理(Tutorial Week 5 Q7,可能考陈述/判断题):在 E(ε)=0E(\varepsilon) = 0、Cov(ε)=σ2I\mathrm{Cov}(\varepsilon) = \sigma^2 I 下(不需要正态),最小二乘估计 bb 是 BLUE:Best Linear Unbiased Estimator,在所有线性、无偏的估计量中方差最小。

5.7 二次型的期望 & σ̂² 无偏(Tutorial Week 3 Q7、Week 5 Q10b)

迹的三条性质:tr(cA)=c tr(A)\mathrm{tr}(cA) = c\,\mathrm{tr}(A);tr(A+B)=trA+trB\mathrm{tr}(A+B) = \mathrm{tr}A + \mathrm{tr}B;tr(AB)=tr(BA)\mathrm{tr}(AB) = \mathrm{tr}(BA)。一个数(1×1 矩阵)的迹就是它自己。

二次型期望公式:若 E(y)=μE(y) = \mu,Cov(y)=V\mathrm{Cov}(y) = V,则

E(y⊤Ay)=tr(AV)+μ⊤AμE(y^\top A y) = \mathrm{tr}(AV) + \mu^\top A\mu

用它证明 σ^2=y⊤(I−H)yn−p\hat\sigma^2 = \dfrac{y^\top(I-H)y}{n-p} 无偏:取 A=I−HA = I - H,V=σ2IV = \sigma^2 I,μ=Xβ\mu = X\beta:

E[y⊤(I−H)y]=σ2 tr(I−H)+β⊤X⊤(I−H)Xβ=σ2(n−p)+0E[y^\top(I-H)y] = \sigma^2\,\mathrm{tr}(I-H) + \beta^\top X^\top(I-H)X\beta = \sigma^2(n-p) + 0

(因为 (I−H)X=0(I-H)X = 0。)除以 n−pn-p 得 E(σ^2)=σ2E(\hat\sigma^2) = \sigma^2。而极大似然估计用 SSres/n\text{SSres}/n,是有偏的(偏小)。

5.8 多元正态分布(只需要知道结论)

y∼N(μ,V)y \sim N(\mu, V)(多元正态)时:

📄 原题 · Tutorial Week 5 Q3
Let Y₁ and Y₂ be independent random variables with Y₁ ~ N(1, 3) and Y₂ ~ N(2, 5). If W₁ = Y₁ + 2Y₂ and W₂ = 4Y₁ − Y₂, what is the joint distribution of W₁ and W₂?
答案(用 Cov(AY) = AΣAᵀ)

W=AYW = AY,A=(124−1)A = \begin{pmatrix}1 & 2\\ 4 & -1\end{pmatrix},E(Y)=(1,2)⊤E(Y) = (1,2)^\top,Cov(Y)=diag(3,5)\mathrm{Cov}(Y) = \mathrm{diag}(3,5)。

E(W)=A(1,2)⊤=(5,2)⊤E(W) = A(1,2)^\top = (5, 2)^\top;Cov(W)=A diag(3,5)A⊤=(3+2012−1012−1048+5)=(232253)\mathrm{Cov}(W) = A\,\mathrm{diag}(3,5)A^\top = \begin{pmatrix} 3+20 & 12-10 \\ 12-10 & 48+5\end{pmatrix} = \begin{pmatrix}23 & 2 \\ 2 & 53\end{pmatrix}。

所以 W∼N2((5,2)⊤,(232253))W \sim N_2\big((5,2)^\top, \begin{pmatrix}23&2\\2&53\end{pmatrix}\big)(正态的线性组合仍是正态)。

✅ 本章检查清单
  • 能写出 y=Xβ+εy = X\beta+\varepsilon,知道 X 是 n×pn\times p,p 含截距
  • 会推 b=(X⊤X)−1X⊤yb = (X^\top X)^{-1}X^\top y
  • 能一行证明 H 对称、幂等、HX=XHX=X、tr(H)=p\mathrm{tr}(H)=p
  • 会用 Cov(AY,BZ)=AΣB⊤\mathrm{Cov}(AY, BZ) = A\Sigma B^\top 证明 E(b)=βE(b)=\beta、Cov(b)=σ2(X⊤X)−1\mathrm{Cov}(b) = \sigma^2(X^\top X)^{-1}

第 6 章 · 多元线性回归的推断

本章目标
读懂多元回归的 summary;分清 partial t 检验(一个变量)和 overall F 检验(所有变量);会做多元的置信区间和预测区间。
配套脚本:R/ch06_mlr_inference.R 原题:Lab Week 4 Q3、Q4(a)(b);讲义 risk 例子 考试关联:2025 Q2 Part I (a)(c)(d) 共 11 分。

6.1 多元回归的 summary:和 SLR 一模一样的读法

讲义 Week 3–4 的 risk 数据:25 个公司,响应 risk,7 个预测变量。

Rch06 · 6.1

setwd("C:/Users/Cestbon/Desktop/MATHLAB/datasets")
risk <- read.table("risk.txt", header = TRUE)
risk_mod <- lm(risk ~ Div + Ratio + Size + Growth + Leverage + Earn1 + Earn2, data = risk)
# 等价简写:lm(risk ~ ., data = risk)   "." = 其余所有列

summary(risk_mod)
Console 输出
Coefficients:
            Estimate Std. Error t value Pr(>|t|)
(Intercept)  2.19056    1.86970   1.172  0.25751
Div          0.44264    0.14170   3.124  0.00618 **
Ratio        0.86455    0.37330   2.316  0.03331 *
Size        -0.24719    0.13164  -1.878  0.07767 .
Growth       1.96264    6.25298   0.314  0.75744
Leverage     3.59223    1.43608   2.501  0.02288 *
Earn1        0.13459    0.05978   2.251  0.03788 *
Earn2        1.04504    0.93798   1.114  0.28072
---
Residual standard error: 0.9816 on 17 degrees of freedom
Multiple R-squared:  0.7417,	Adjusted R-squared:  0.6353
F-statistic: 6.972 on 7 and 17 DF,  p-value: 0.0005272

先把三个数对上:n=25n = 25,p=8p = 8(7 个斜率 + 截距),残差自由度 n−p=17n - p = 17("on 17 degrees of freedom")。overall F 的自由度是 (p−1,n−p)=(7,17)(p-1, n-p) = (7, 17)。

💡 系数的含义变了:"在其他变量不变时"
多元回归里,Div 的系数 0.443 的意思是:在其他 6 个变量保持不变的情况下,Div 增加 1,平均 risk 增加 0.443。所以同一个变量在不同模型里的系数可能完全不一样。

6.2 partial t 检验:这个变量"在其他变量都在的情况下"有没有用

summary 每一行的 t 和 p 检验的是

H0:βj=0vsH1:βj≠0(其他变量都在模型里),t=bjse(bj)∼H0tn−pH_0: \beta_j = 0 \quad\text{vs}\quad H_1: \beta_j \ne 0 \qquad (\text{其他变量都在模型里}),\qquad t = \frac{b_j}{\mathrm{se}(b_j)} \overset{H_0}{\sim} t_{n-p}

例:Div 的 t = 3.124,p = 0.00618 < 0.05 → "There is strong evidence (p = 0.00618) that Div is related to risk in the presence of the other predictors."

2025 年 (c) 原文:"Is there evidence that Theatres is related to the response in the presence of Budget, Opening, Ratings and intercept? State the relevant test statistic and p-value." → 这就是问 partial t:直接读 summary 里 Theatres 那一行的 t value 和 Pr(>|t|)(官方答案 t = 2.118391, p = 0.04073864)。

⚠️ partial t 不能一次检验好几个变量
"Div 和 Ratio 都不显著" 不能推出 "把两个一起去掉也没关系"。检验一组变量要用 F 检验(第 7 章)。

6.3 overall F 检验:所有预测变量一起有没有用

H0:β1=β2=⋯=βk=0vsH1:至少一个βj≠0H_0: \beta_1 = \beta_2 = \cdots = \beta_k = 0 \quad\text{vs}\quad H_1: \text{至少一个} \beta_j \ne 0 F=SSreg/(p−1)SSres/(n−p)=MSregMSres∼H0Fp−1, n−pF = \frac{\text{SSreg}/(p-1)}{\text{SSres}/(n-p)} = \frac{\text{MSreg}}{\text{MSres}} \overset{H_0}{\sim} F_{p-1,\,n-p}

它比较的是"只有截距的模型" vs "全模型"。答案在 summary 最后一行:F-statistic: 6.972 on 7 and 17 DF, p-value: 0.0005272。

🎯 2025 Q2 (a)【4 分】标准答法

State the value of the F statistic used to test H0: β₁ = β₂ = β₃ = β₄ = 0 versus H1: β₁ ≠ 0 or β₂ ≠ 0 or β₃ ≠ 0 or β₄ ≠ 0. Null distribution? Conclusion?

  • Observed F statistic:summary 最后一行的 F(2025:30.32171)
  • Null distribution:Fp−1, n−pF_{p-1,\,n-p} = F4,38F_{4,38}(n = 43, p = 5)—— 就是 summary 里 "on 4 and 38 DF"
  • Conclusion:"p-value = 2.311e-11 < 0.05, so we reject H0. At least one of the predictors is linearly related to USRevenue."

如果要更多位小数:summary(model)$fstatistic。

Rch06 · 6.4

fs <- summary(risk_mod)$fstatistic     # F 值、分子自由度、分母自由度

fs
pf(fs[1], fs[2], fs[3], lower.tail = FALSE)
Console 输出
   value    numdf    dendf
 6.97226  7.00000 17.00000
       value
0.0005272062

6.4 Lab Week 4 Q3(capmodel)

📄 原题 · Lab Week 4 Q3
Fit a linear model with y (Price) as the response and x1 (PE_ratio) and x2 (TSE300) as the predictors and then answer the following questions from the output.
(a) Test each of the coefficients in the model for significance in the presence of the other terms (use a 5 percent level of significance).
(b) From the p-value in the summary output do you think the multiple linear regression model you have fitted is better than the one containing just an intercept?
Rch06 · 6.3

capital <- read.table("capmodel.txt", header = TRUE)
cap_model <- lm(Price ~ PE_ratio + TSE300, data = capital)
summary(cap_model)
Console 输出
Coefficients:
             Estimate Std. Error t value Pr(>|t|)
(Intercept)  2.618932   1.090238   2.402  0.02731 *
PE_ratio    -0.572783   0.140111  -4.088  0.00069 ***
TSE300       0.011221   0.000664  16.900 1.73e-12 ***
---
Residual standard error: 0.235 on 18 degrees of freedom
Multiple R-squared:  0.9426,	Adjusted R-squared:  0.9362
F-statistic: 147.8 on 2 and 18 DF,  p-value: 6.762e-12
答案

(a) PE_ratio:t = −4.088,p = 0.00069 < 0.05,在 TSE300 存在时显著;TSE300:t = 16.90,p = 1.73e-12 < 0.05,在 PE_ratio 存在时显著。

(b) F = 147.8 on 2 and 18 DF,p = 6.762e-12 < 0.05 → strong evidence that the model is better than the intercept-only model.

6.5 Lab Week 4 Q4 (a)(b):t 都不显著,F 却显著?

📄 原题 · Lab Week 4 Q4 (a)(b)
Fit a multiple linear regression model with INF as the response and the remaining variables (QUES, LEGAL, DEV) as predictors.
(a) Do any of the partial t tests indicate a significant coefficient for one of the predictors in the presence of the others?
(b) Does the model including all the predictors explain significantly more of the variation than a model including only an intercept term? Can you explain the discrepancy between the answer here and the answer to the previous question?
Rch06 · 6.5

inflation <- read.table("inflation.txt", header = TRUE)
summary(lm(INF ~ QUES + LEGAL + DEV, data = inflation))
Console 输出
Coefficients:
            Estimate Std. Error t value Pr(>|t|)
(Intercept)  59.3686    18.1299   3.275  0.00421 **
QUES         -4.1176     3.4047  -1.209  0.24216
LEGAL         0.1202     5.0303   0.024  0.98120
DEV         -22.6215    14.2982  -1.582  0.13103
---
Residual standard error: 23.27 on 18 degrees of freedom
Multiple R-squared:  0.4297,	Adjusted R-squared:  0.3346
F-statistic:  4.52 on 3 and 18 DF,  p-value: 0.01567
答案(判断题常考这个"矛盾")

(a) 三个 partial t 的 p 值都 > 0.1,没有一个单独显著。

(b) F = 4.52,p = 0.01567 < 0.05,整体显著。解释:partial t 检验的是"其他变量已经在模型里时,再加这个变量有没有帮助"。三个预测变量包含的信息高度重叠,任何一个在其他两个存在时都"可有可无",但三个合起来确实能解释 INF 的变异。

6.6 系数的置信区间

bj±tα/2; n−p se(bj)b_j \pm t_{\alpha/2;\,n-p}\ \mathrm{se}(b_j)
Rch06 · 6.6

confint(risk_mod, level = 0.99)
0.44264 + c(-1, 1) * qt(0.995, 17) * 0.14170    # Div 手算,自由度 n - p = 17
Console 输出
                   0.5 %     99.5 %
(Intercept)  -3.22825015  7.6093713
Div           0.03195498  0.8533235
Ratio        -0.21735763  1.9464556
Size         -0.62872019  0.1343309
Growth      -16.15994490 20.0852244
Leverage     -0.56986723  7.7543314
Earn1        -0.03867460  0.3078535
Earn2        -1.67343214  3.7635178
[1] 0.03196074 0.85331926

Div 的 99% CI 不含 0,和 partial t 的 p = 0.00618 < 0.01 一致。

6.7 多元回归的 CI 和 PI(2025 (d) 3 分)

新观测的预测变量向量写成 x0=(1,x01,…,x0k)⊤x_0 = (1, x_{01}, \dots, x_{0k})^\top(第一个 1 对应截距):

均值 CI: x0⊤b±tα/2;n−p σ^x0⊤(X⊤X)−1x0,PI: x0⊤b±tα/2;n−p σ^1+x0⊤(X⊤X)−1x0\text{均值 CI: } x_0^\top b \pm t_{\alpha/2;n-p}\,\hat\sigma\sqrt{x_0^\top(X^\top X)^{-1}x_0}, \qquad \text{PI: } x_0^\top b \pm t_{\alpha/2;n-p}\,\hat\sigma\sqrt{1 + x_0^\top(X^\top X)^{-1}x_0}
📄 2025 真题 Q2 Part I (d)【3 分】
A new movie was released during the same time period when these data were collected. It had a budget of $30 million and was shown in 3,065 theatres, grossing $19.63 million during the first weekend. The movie's IMDb rating was 7.6 out of 10. Obtain a 97% prediction interval for the USRevenue based on the model with all four predictors and intercept.

套路:predict(model, data.frame(Budget = 30, Opening = 19.63, Theatres = 3065, Ratings = 7.6), interval = "prediction", level = 0.97)。官方答案 (−5.25421, 188.2444)。注意单位:题目说 "$30 million",数据里 Budget 的单位就是百万,所以填 30,不是 30000000。

Rch06 · 6.7(讲义 risk 例子)

newdata <- data.frame(Div = 0.5, Ratio = 1.0, Size = 10.0, Growth = 0.1,
                      Leverage = 0.3, Earn1 = 2.0, Earn2 = 0.6)   # 每个变量都要给!

predict(risk_mod, newdata, interval = "confidence")
predict(risk_mod, newdata, interval = "prediction")
predict(risk_mod, newdata, interval = "prediction", level = 0.97)
Console 输出
       fit      lwr      upr
1 2.974621 2.137804 3.811438
       fit       lwr     upr
1 2.974621 0.7409124 5.20833
       fit       lwr      upr
1 2.974621 0.4675088 5.481733

ch06 脚本 6.7 节还用矩阵公式手算了 97% PI,结果完全一样,可以运行看看。

6.8 adjusted R²

R2R^2 有个缺点:只要加变量,R² 就不会下降(哪怕加的是纯噪声),所以不能用 R² 比较参数个数不同的模型。adjusted R² 把平方和换成均方:

Rˉ2=1−SSres/(n−p)SStotal/(n−1)=1−n−1n−p(1−R2)\bar R^2 = 1 - \frac{\text{SSres}/(n-p)}{\text{SStotal}/(n-1)} = 1 - \frac{n-1}{n-p}(1 - R^2)

加一个没用的变量时 Rˉ2\bar R^2 可能下降。它甚至可以是负数(当 R2<(p−1)/(n−1)R^2 < (p-1)/(n-1) 时,Lab 7 Q1(b)ii)。

Rch06 · 6.8

n <- 25; p <- 8; R2 <- summary(risk_mod)$r.squared
1 - (n - 1) / (n - p) * (1 - R2)
Console 输出
[1] 0.6352906

6.9 summary 给的 p 值不能直接用的三种情况

summary 里的 t 和 p 只针对 H0:βj=0H_0: \beta_j = 0 的双侧检验。题目一变就要自己算。

(1) 检验 βj 等于某个非 0 的数

例:zinc 数据,检验 H0:β1=1H_0: \beta_1 = 1 vs H1:β1≠1H_1: \beta_1 \ne 1("斜率是不是 1")。统计量还是 (估计 − 假设值)/标准误,只是假设值不再是 0:

t=b1−1se(b1)∼H0tn−pt = \frac{b_1 - 1}{\mathrm{se}(b_1)} \overset{H_0}{\sim} t_{n-p}

(2) 单侧检验

H1:β1<1H_1: \beta_1 < 1 → p 值只算左尾 pt(t, df);H1:β1>1H_1: \beta_1 > 1 → 只算右尾 1 - pt(t, df)。(slides Week 2 "One-sided test for βj")

Rch06 · 6.9

setwd("C:/Users/Cestbon/Desktop/MATHLAB/datasets")
zinc <- read.csv("zinc.csv")
m <- lm(plant ~ sediment, data = zinc)
est <- coef(m)["sediment"]
se  <- summary(m)$coefficients["sediment", "Std. Error"]
t_obs <- (est - 1) / se          # H0: beta1 = 1

dfr <- df.residual(m)            # 残差自由度 n - p(这里 13)

t_obs
2 * pt(-abs(t_obs), dfr)         # 双侧 p 值:H1: beta1 != 1

pt(t_obs, dfr)                   # 单侧 p 值:H1: beta1 < 1
Console 输出
  sediment 
-0.9368095 
 sediment 
0.3659349 
 sediment 
0.1829674

p = 0.366 > 0.05:没有证据表明斜率不是 1。(第一行的 "sediment" 只是名字标签,不用管。)

(3) R 显示 "< 2.2e-16" 或者位数不够

p 值小于 2.2e-16 时,summary 不显示具体数字。Möbius 的数字框里不要填 "<",一律用下面的方法拿到精确值(如 8.644334e-19)再粘贴:

Rch06 · 6.9

tm2 <- lm(Volume ~ Girth, data = trees)
summary(tm2)$coefficients                  # 系数表里的 p 值显示完整数字

fs <- summary(tm2)$fstatistic
pf(fs[1], fs[2], fs[3], lower.tail = FALSE)   # overall F 的精确 p 值

setwd("C:/Users/Cestbon/Desktop/MATHLAB/datasets")
risk <- read.table("risk.txt", header = TRUE)
a <- anova(lm(risk ~ Div, data = risk), lm(risk ~ ., data = risk))
a$F[2]                                     # anova(小, 大) 的 F(更多位数)

a$"Pr(>F)"[2]                              # anova(小, 大) 的 p 值(更多位数)
Console 输出
              Estimate Std. Error   t value     Pr(>|t|)
(Intercept) -36.943459   3.365145 -10.97827 7.621449e-12
Girth         5.065856   0.247377  20.47829 8.644334e-19
       value 
8.644334e-19 
[1] 4.947348
[1] 0.004240843

summary 里 Girth 的 p 显示为 < 2e-16,真实值是 8.644334e-19。

✅ 本章检查清单
  • 看到 "in the presence of …" → partial t → summary 那一行
  • 看到 "H0: β₁ = … = βₖ = 0" → overall F → summary 最后一行,分布 Fp−1,n−pF_{p-1,n-p}
  • 会写 "reject H0 …" 结论
  • 会给 predict 的 newdata 填齐所有变量,level 写成小数

第 7 章 · ANOVA 表与 F 检验家族(Q2 Part I 核心)

本章目标
彻底搞懂 anova() 的输出(sequential sums of squares);掌握一个万能 F 公式,用它解决 overall F、比较两个模型、sequential F、partial F;会补全 ANOVA 表。
配套脚本:R/ch07_anova_F_tests.R 原题:Lab Week 4 Q2、Q4(c)(d) 考试关联:2025 (b) 4 分 + 判断题第 4 题。

7.1 sequential sums of squares:anova() 每一行在说什么

多元回归里 anova(model) 每个变量一行。它不是"这个变量的贡献",而是"按顺序加进来时,这个变量让 SSreg 多了多少":

重要事实:所有 sequential SS 加起来 = SSreg(2025 判断题第 4 题,答案 True):

R(β1∣β0)+R(β2∣β0,β1)+⋯+R(βk∣β0,…,βk−1)=R(β1,…,βk∣β0)=SSregR(\beta_1|\beta_0) + R(\beta_2|\beta_0,\beta_1) + \cdots + R(\beta_k|\beta_0,\dots,\beta_{k-1}) = R(\beta_1,\dots,\beta_k|\beta_0) = \text{SSreg}
Rch07 · 7.1

setwd("C:/Users/Cestbon/Desktop/MATHLAB/datasets")
risk <- read.table("risk.txt", header = TRUE)
risk_mod <- lm(risk ~ Div + Ratio + Size + Growth + Leverage + Earn1 + Earn2, data = risk)
anova(risk_mod)
sum(anova(risk_mod)[1:7, "Sum Sq"])     # 前 7 行加起来 = SSreg
Console 输出
Analysis of Variance Table

Response: risk
          Df  Sum Sq Mean Sq F value    Pr(>F)
Div        1 18.4253 18.4253 19.1217 0.0004147 ***
Ratio      1  5.6024  5.6024  5.8142 0.0274926 *
Size       1 10.1251 10.1251 10.5078 0.0047982 **
Growth     1  1.6456  1.6456  1.7078 0.2086785
Leverage   1  6.0841  6.0841  6.3140 0.0223551 *
Earn1      1  3.9497  3.9497  4.0990 0.0589119 .
Earn2      1  1.1961  1.1961  1.2413 0.2807217
Residuals 17 16.3808  0.9636
[1] 47.02817

换顺序:sequential SS 全变了,但它们的总和、以及 summary 里的一切(系数、t、p、R²、overall F)完全不变。所以写 lm() 时变量的顺序只影响 anova() 的输出。

💡 SSreg 增加 = SSres 减少
因为 SStotal 只和 y 有关、固定不变,R(β2∣β1)=SSreg(β1,β2)−SSreg(β1)=SSres(β1)−SSres(β1,β2)R(\beta_2|\beta_1) = \text{SSreg}(\beta_1,\beta_2) - \text{SSreg}(\beta_1) = \text{SSres}(\beta_1) - \text{SSres}(\beta_1,\beta_2)。这个等式就是下面万能 F 公式的分子。

7.2 Lab Week 4 Q2:补全 ANOVA 表

📄 原题 · Lab Week 4 Q2
cheese<-read.table('cheese.txt',header = T); model<-lm(taste~H2S + Lactic + Acetic, data= cheese); anova(model)
              Df  Sum Sq Mean Sq F value    Pr(>F)
cheese$H2S     1   X1X    4376.7 42.6454 6.358e-07 ***
cheese$Lactic  1   617.2   617.2   X3X   0.02122 *
cheese$Acetic  1     0.6     0.6  0.0054 0.94198
Residuals     X2X 2668.4   102.6
(a) Complete the above ANOVA table by finding X1X, X2X and X3X. (b) Compute SStotal. (c) Compute the value of the F statistic used to test the hypothesis that β₁ = β₂ = β₃ = 0.
先自己填,再看答案

只需要两条规则:Mean Sq = Sum Sq / Df,F = Mean Sq / MSres。

  • X1X = Mean Sq × Df = 4376.7 × 1 = 4376.7
  • X2X = Sum Sq / Mean Sq = 2668.4 / 102.6 = 26(残差自由度;也等于 n − p = 30 − 4)
  • X3X = 617.2 / 102.6 = 6.0156
  • (b) SStotal = 所有 Sum Sq 之和 = 4376.7 + 617.2 + 0.6 + 2668.4 = 7662.9
  • (c) SSreg = 4376.7 + 617.2 + 0.6 = 4994.5;F = (4994.5/3) / 102.6 = 16.23(R 精确值 16.22,差别来自表里的四舍五入)
Rch07 · 7.2

c(X1X = 4376.7 * 1, X2X = 2668.4 / 102.6, X3X = 617.2 / 102.6)
(4376.7 + 617.2 + 0.6) / 3 / 102.6
Console 输出
        X1X         X2X         X3X
4376.700000   26.007797    6.015595
[1] 16.22645

7.3 万能 F 公式:比较两个嵌套模型

"嵌套"(nested)= 小模型的变量全都在大模型里。检验"多出来的那些变量有没有用":

H0:多出来的系数全是 0vsH1:至少一个不是 0H_0: \text{多出来的系数全是 } 0 \qquad\text{vs}\qquad H_1: \text{至少一个不是 } 0 F=(SSres小−SSres大)/(p大−p小)SSres大/(n−p大) ∼H0 F p大−p小, n−p大\boxed{F = \frac{\big(\text{SSres}_{\text{小}} - \text{SSres}_{\text{大}}\big) / \big(p_{\text{大}} - p_{\text{小}}\big)}{\text{SSres}_{\text{大}} / (n - p_{\text{大}})} \ \overset{H_0}{\sim}\ F_{\,p_{\text{大}} - p_{\text{小}},\ n - p_{\text{大}}}}

大白话:分子 = "加了这些变量后,残差平方和平均每个变量减少了多少";分母 = 大模型的 σ^2\hat\sigma^2。减少得越多(相对于噪声),F 越大,越说明多出来的变量有用。

R 里一行:anova(小模型, 大模型)(先小后大)。

Rch07 · 7.3

risk_mod_0 <- lm(risk ~ 1, data = risk)        # 只有截距

anova(risk_mod_0, risk_mod)                     # = overall F

model_null <- lm(risk ~ Div, data = risk)
anova(model_null, risk_mod)                     # H0: 除 Div 外 6 个系数都 = 0
Console 输出
Model 1: risk ~ 1
Model 2: risk ~ Div + Ratio + Size + Growth + Leverage + Earn1 + Earn2
  Res.Df    RSS Df Sum of Sq      F    Pr(>F)
1     24 63.409
2     17 16.381  7    47.028 6.9723 0.0005272 ***

Model 1: risk ~ Div
Model 2: risk ~ Div + Ratio + Size + Growth + Leverage + Earn1 + Earn2
  Res.Df    RSS Df Sum of Sq      F   Pr(>F)
1     23 44.984
2     17 16.381  6    28.603 4.9473 0.004241 **

怎么读 anova(m1, m2) 的输出:Res.Df = 各自的 n−pn-p;RSS = 各自的 SSres;Df = 多了几个参数;Sum of Sq = RSS 减少了多少;F 和 Pr(>F) 就是答案。零分布 FDf, 大模型的 Res.DfF_{\text{Df},\ \text{大模型的 Res.Df}},比如第二个是 F6,17F_{6,17}。

第一个例子说明:overall F 就是"只有截距"vs"全模型"的特例,F = 6.9723 和 summary 最后一行一样。

7.4 Lab Week 4 Q4 (c):一次检验两个变量

📄 原题 · Lab Week 4 Q4 (c)
(c) Test whether the coefficients for QUES and LEGAL are both zero in the model including all the predictors using an appropriate F test.
Rch07 · 7.4

inflation <- read.table("inflation.txt", header = TRUE)
inf_mod_full <- lm(INF ~ DEV + QUES + LEGAL, data = inflation)
inf_mod_null <- lm(INF ~ DEV, data = inflation)
anova(inf_mod_null, inf_mod_full)
Console 输出
Model 1: INF ~ DEV
Model 2: INF ~ DEV + QUES + LEGAL
  Res.Df     RSS Df Sum of Sq      F Pr(>F)
1     20 10872.5
2     18  9749.7  2    1122.8 1.0365 0.3749

H0:βQUES=βLEGAL=0H_0: \beta_{QUES} = \beta_{LEGAL} = 0。F = 1.0365 ~ F2,18F_{2,18},p = 0.3749 > 0.05 → 不拒绝 H0:没有证据表明 QUES 和 LEGAL 有用。

用 sequential SS 手算(课程答案的做法):把 DEV 放在第一个拟合,anova(inf_mod_full) 里 QUES、LEGAL 两行的 Sum Sq 加起来就是 R(βQUES,βLEGAL∣β0,βDEV)R(\beta_{QUES}, \beta_{LEGAL} \mid \beta_0, \beta_{DEV}):F = ((1122.5 + 0.3)/2) / 541.7 = 1.036。

7.5 sequential F 检验 & 2025 年 (b) 的关键细节 ★

📄 原题 · Lab Week 4 Q4 (d)
(d) Test whether the coefficient for QUES is zero in a model including DEV and QUES using a sequential F-test.
Rch07 · 7.5

inf_mod_1 <- lm(INF ~ DEV + QUES, data = inflation)
anova(inf_mod_null, inf_mod_1)      # 小 = DEV,大 = DEV + QUES
Console 输出
Model 1: INF ~ DEV
Model 2: INF ~ DEV + QUES
  Res.Df   RSS Df Sum of Sq      F Pr(>F)
1     20 10872
2     19  9750  1    1122.5 2.1875 0.1555

课程答案:F = 1122.5 / ((0.3 + 9749.7)/19) = 2.1875 ~ F1,19F_{1,19},p = 0.1555。注意分母用的是 "DEV + QUES" 这个模型自己的 MSres(自由度 19),不是全模型(含 LEGAL)的 MSres。

🎯 2025 年 (b) 到底该怎么算?我用官方答案反推出来了

原题:"(b) Is there evidence that a model with Opening, Budget and intercept is better than a model with just Budget and intercept? State the relevant test statistic and p-value."(全模型有 4 个变量,n = 43)

有两种看似合理的算法:

  1. 直接读全模型 anova(full) 里 Opening 那一行:分母是全模型的 MSres,自由度 (1, 38)
  2. anova(lm(USRevenue ~ Budget), lm(USRevenue ~ Budget + Opening)):分母是 "Budget + Opening" 模型的 MSres,自由度 (1, 40)

官方答案 F = 60.06548,p = 1.7294e-09。用 R 反推:

Rch07 · 7.6

pf(60.06548, 1, 38, lower.tail = FALSE)   # 方法 1 的自由度

pf(60.06548, 1, 40, lower.tail = FALSE)   # 方法 2 的自由度
Console 输出
[1] 2.432703e-09
[1] 1.729399e-09

结论:官方用的是方法 2。考试里看到 "Is model A better than model B?",就把题目里说的两个模型原样建出来,然后 anova(小, 大)。不要偷懒去读全模型 anova 表里的行。只有当大模型就是全模型、并且被检验的变量在公式里排在最后时,两种算法才给出同一个数。

formula sheet 第 3 页也是这么写的(考场能看到):R(βk∣β0,…,βk−1)SSres/(n−k−1)∼F1, n−k−1\dfrac{R(\beta_k|\beta_0,\dots,\beta_{k-1})}{\text{SSres}/(n-k-1)} \sim F_{1,\,n-k-1},分母是含 k 个预测变量的那个模型自己的 SSres。

例外:slides(Week 4 第 80 页)还介绍了另一种 sequential F:分母用全模型的 MSres,自由度 (1,n−p)(1, n-p),也就是 anova(full) 每一行显示的 F。如果题目明确说 "use the sequential sums of squares in the ANOVA table of the full model",那就读那一行。

7.6 partial F = (partial t)²

"去掉一个变量的模型" vs "全模型" 的 F 检验,就等价于这个变量的 partial t 检验:F=t2F = t^2,p 值相同。

Rch07 · 7.7

anova(lm(risk ~ . - Earn2, data = risk), risk_mod)        # ". - Earn2" = 除了 Earn2 以外的所有变量

summary(risk_mod)$coefficients["Earn2", "t value"]^2
Console 输出
  Res.Df    RSS Df Sum of Sq      F Pr(>F)
1     18 17.577
2     17 16.381  1    1.1961 1.2413 0.2807
[1] 1.241319

7.7 看到什么题 → 敲什么代码(Q2 Part I 总结)

题目怎么问是什么检验R 代码零分布
"F statistic to test H0: β₁ = … = βₖ = 0"
"Is the model better than intercept only?"
overall Fsummary(full) 最后一行Fp−1, n−pF_{p-1,\,n-p}
"Is X related to the response in the presence of A, B, C?"partial tsummary(full) 中 X 那一行的 t 和 ptn−pt_{n-p}
"Is a model with A, B better than a model with just A?"
"Test whether βB = 0 in a model with A and B (sequential F)"
嵌套模型 Fanova(lm(y ~ A), lm(y ~ A + B))F1, n−p大F_{1,\,n-p_{\text{大}}}
"Test whether β_C and β_D are both zero in the full model"一组变量的 Fanova(lm(y ~ A + B), full)F2, n−pF_{2,\,n-p}
"97% prediction interval for a new …"PIpredict(full, data.frame(...), interval = "prediction", level = 0.97)
"95% CI for the mean response …"均值 CIpredict(..., interval = "confidence")
"99% CI for the coefficient of X"系数 CIconfint(full, level = 0.99)
"Complete the ANOVA table"算术MS = SS/Df;F = MS/MSres;SStotal = 所有 SS 之和
⚠️ 易错点
  • anova(大, 小) 顺序反了也能出结果,但 Df 和 Sum of Sq 是负的。养成"先小后大"的习惯。
  • 两个模型必须用同一份数据(同一个 data.frame)。
  • "null distribution" 下拉框:overall F 选 Fp−1,n−pF_{p-1,n-p};比较模型选 F多的参数个数, n−p大F_{\text{多的参数个数},\ n-p_{\text{大}}}。
✅ 本章检查清单
  • 能解释 anova() 每一行是"按顺序加入时的增量",总和 = SSreg
  • 会写万能 F 公式,会用 anova(小, 大)
  • 记住 2025 (b):把题目说的两个模型原样建出来比较
  • 会补全 ANOVA 表

第 8 章 · 帽子矩阵与杠杆值 leverage

本章目标
知道杠杆值 hiih_{ii} 是什么、为什么只和 x 有关;会用 hatvalues();记住 ∑hii=p\sum h_{ii} = p、平均杠杆 p/np/n、"高杠杆"的门槛 2p/n2p/n。
配套脚本:R/ch08_hat_leverage.R 原题:Tutorial Week 5 Q11 考试关联:2025 Part II (a)(b) 共 4 分 + 判断题第 1、2 题 共 4 分。

8.1 杠杆值是什么

第 5 章:y^=Hy\hat y = Hy。写出第 i 行:

y^i=hii yi+∑j≠ihij yj\hat y_i = h_{ii}\,y_i + \sum_{j\ne i} h_{ij}\,y_j

hiih_{ii}(H 的第 i 个对角线元素)就是"第 i 个观测值 yiy_i 对它自己的拟合值 y^i\hat y_i 有多大话语权"。hiih_{ii} 越大,这个点越能把拟合线"拽"向自己。这就是杠杆(leverage):像跷跷板,离中心越远的点力臂越长。

另一个等价写法:hii=xi⊤(X⊤X)−1xih_{ii} = x_i^\top(X^\top X)^{-1}x_i,其中 xi⊤x_i^\top 是 X 的第 i 行。所以 hiih_{ii} 只取决于 X(预测变量),和 y 完全无关。(判断题常客。)

在 SLR 里有显式公式(Tutorial Week 5 Q11a):

hii=1n+(xi−xˉ)2Sxxh_{ii} = \frac{1}{n} + \frac{(x_i - \bar x)^2}{S_{xx}}

x 离平均值 xˉ\bar x 越远,杠杆越大;正好在 xˉ\bar x 处杠杆最小,等于 1/n1/n。

玩法:把红点左右拖,看 h 怎么变(上下拖 h 不变!);拖到最右边、再上下拖,看蓝线(含红点)被它拽得多厉害,而灰虚线(不含红点)不动。

8.2 杠杆值的性质(判断题素材)

性质为什么
∑i=1nhii=tr(H)=p\sum_{i=1}^n h_{ii} = \mathrm{tr}(H) = p第 5 章的迹循环性
平均杠杆 =p/n= p/np 除以 n 个点
0≤hii≤10 \le h_{ii} \le 1;有截距时 1/n≤hii≤11/n \le h_{ii} \le 1H 和 I−H 都幂等对称 ⇒ 对角线 ≥ 0(Tut W5 Q11b,c)
只和 X 有关hii=xi⊤(X⊤X)−1xih_{ii} = x_i^\top(X^\top X)^{-1}x_i
高杠杆的经验规则:hii>2p/nh_{ii} > 2p/n(平均值的两倍)Lecture Notes 5.2
Var(ei)=σ2(1−hii)\mathrm{Var}(e_i) = \sigma^2(1 - h_{ii})高杠杆点的残差方差反而小:线被它拽过去了
n=pn = p 时所有 hii=1h_{ii} = 1X 是可逆方阵 ⇒ H=XX−1(X⊤)−1X⊤=IH = X X^{-1}(X^\top)^{-1}X^\top = I
✍️ 2025 判断题 1、2(各 2 分)

1. "It is possible to construct an example dataset for a simple linear model where all leverages hii = 1, i = 1,…,n. (hint: consider n = 2)" → True。取 n = 2,两个不同的 x 值,X 是 2×2 满秩矩阵,可逆,所以 H=X(X⊤X)−1X⊤=XX−1(X⊤)−1X⊤=I2H = X(X^\top X)^{-1}X^\top = XX^{-1}(X^\top)^{-1}X^\top = I_2,h11=h22=1h_{11} = h_{22} = 1。

2. "The trace of the hat matrix is equal to p, the number of regression parameters β in the general linear model." → True。tr(H)=tr(X(X⊤X)−1X⊤)=tr((X⊤X)−1X⊤X)=tr(Ip)=p\mathrm{tr}(H) = \mathrm{tr}(X(X^\top X)^{-1}X^\top) = \mathrm{tr}((X^\top X)^{-1}X^\top X) = \mathrm{tr}(I_p) = p。

8.3 2025 Part II (a)(b):trees 数据

📄 2025 真题 Q2 Part II
Using the trees dataset available in R (type ?trees in R for more information), build a simple linear regression model (with intercept) with Volume as the response variable and Height as the sole predictor.
(a) [2 marks] What is the sum of the leverages for all observations in the model?
(b) [2 marks] How many observations in the model have leverage values exceeding two times the average leverage?
Rch08 · 8.1–8.4

model <- lm(Volume ~ Height, data = trees)
h <- hatvalues(model)            # 每个观测的杠杆值

sum(h)                           # (a) = p = 2

n <- nrow(trees)                 # 31

p <- length(coef(model))         # 2

mean(h)                          # 平均杠杆 = p/n

2 * p / n                        # 门槛

sum(h > 2 * p / n)               # (b) 有几个超过

which(h > 2 * p / n)             # 是哪几个
Console 输出
[1] 2
[1] 0.06451613
[1] 0.1290323
[1] 4
 2  3 20 31
 2  3 20 31

答案:(a) 2,(b) 4(和官方答案一致)。which() 输出两行一样的数字:上面一行是行名,下面是位置。

Rch08 · 8.1–8.2:两种方法验证 hatvalues

X <- model.matrix(model)
max(abs(diag(X %*% solve(t(X) %*% X) %*% t(X)) - h))     # H 的对角线:≈ 0

x <- trees$Height
max(abs(1/n + (x - mean(x))^2 / sum((x - mean(x))^2) - h))   # SLR 公式:≈ 0
Console 输出
[1] 1.06859e-15
[1] 8.951173e-16

8.4 看图

Rch08 · 8.5

plot(Volume ~ Height, data = trees, pch = 19,
     col = ifelse(h > 2 * p / n, "red", "grey40"))   # 高杠杆点标红

abline(model)
dotchart(h, main = "leverages"); abline(v = 2 * p / n, col = "red")

你会看到 4 个红点都在 Height 的两端(特别矮或特别高的树)。这正是 hii=1/n+(xi−xˉ)2/Sxxh_{ii} = 1/n + (x_i - \bar x)^2/S_{xx} 告诉我们的。

8.5 高杠杆点的残差为什么小

因为 e=(I−H)ye = (I-H)y,Var(e)=σ2(I−H)\mathrm{Var}(e) = \sigma^2(I-H),所以 Var(ei)=σ2(1−hii)\mathrm{Var}(e_i) = \sigma^2(1-h_{ii})。hiih_{ii} 接近 1 时,残差方差接近 0:线几乎被拽着穿过这个点。所以不能直接用普通残差找离群点,要先除以 1−hii\sqrt{1-h_{ii}} 标准化(第 10 章)。

Rch08 · 8.7:模拟验证(第 11 个点 x = 25 很极端;可跳过)

set.seed(8)
xs <- c(1:10, 25); Xs <- cbind(1, xs)
hs <- diag(Xs %*% solve(t(Xs) %*% Xs) %*% t(Xs))
E <- replicate(20000, {
  ys <- 1 + 2 * xs + rnorm(11)    # 真 sigma = 1

  resid(lm(ys ~ xs))
})
round(apply(E, 1, var), 3)      # 模拟的 Var(e_i)(真 σ = 1)

round(1 - hs, 3)                # 理论 1 - h_ii
Console 输出
    1     2     3     4     5     6     7     8     9    10    11
0.808 0.859 0.862 0.894 0.890 0.911 0.915 0.902 0.903 0.915 0.175
 [1] 0.817 0.844 0.866 0.884 0.897 0.905 0.909 0.908 0.902 0.892 0.175
✅ 本章检查清单
  • hatvalues(model);sum(...) = p;sum(h > 2*p/n)
  • 能证明 tr(H) = p,能举 n = 2 的例子说明所有 h = 1
  • 知道杠杆只看 x,Var(eᵢ) = σ²(1 − hᵢᵢ)

第 9 章 · 模型选择:PRESS、Cp、adjusted R²、AIC、逐步回归

本章目标
会算并比较 PRESS、Mallows' Cp、adjusted R²、AIC;会跑 forward / backward / stepwise 并写出"路径";知道这些方法的局限(判断题)。
配套脚本:R/ch09_model_selection.R 原题:Lab Week 7 Q1、Q2;讲义 cheese 例子 考试关联:2025 Part II (d) PRESS 3 分 + 判断题第 5 题;助教明确提到 Lab 7 Q1 风格题。

9.1 为什么不能只看 R² 或 SSres

加变量 → SSres 一定变小 → R² 一定变大。如果只看它们,永远选最复杂的模型。但复杂模型对新数据的预测往往更差:它把噪声也"背"下来了(过拟合)。模型选择的核心是一个权衡:拟合得好 vs 不要太复杂。下面每个准则都是这个权衡的不同写法。

9.2 PRESS:用"没见过这个点"的模型去预测它

第 i 个 PRESS 残差:把第 i 个点从数据里拿掉,用剩下 n−1 个点拟合,再去预测 yiy_i:

ei,−i=yi−y^i,−i,PRESS=∑i=1nei,−i2e_{i,-i} = y_i - \hat y_{i,-i}, \qquad \text{PRESS} = \sum_{i=1}^n e_{i,-i}^2

这就是"留一法交叉验证"(leave-one-out CV)。PRESS 越小,模型对新数据的预测越好。它不会随变量增多而必然下降。

神奇的捷径(不用真的拟合 n 次):

ei,−i=ei1−hii\boxed{e_{i,-i} = \frac{e_i}{1 - h_{ii}}}

普通残差除以 (1−hii)(1 - h_{ii}) 就行。因为 0<1−hii≤10 < 1 - h_{ii} \le 1,所以 ∣ei,−i∣≥∣ei∣|e_{i,-i}| \ge |e_i|,于是 PRESS ≥ SSres(Tutorial Week 5 Q12:Rpred2=1−PRESS/SStotal<R2R^2_{pred} = 1 - \text{PRESS}/\text{SStotal} < R^2)。

🎯 背下这个函数(Lab 7 Q1 原题里给的提示)
Rch09 · 9.2–9.3
PRESS <- function(linear.model) {
  pr <- residuals(linear.model) / (1 - hatvalues(linear.model))
  sum(pr^2)
}
setwd("C:/Users/Cestbon/Desktop/MATHLAB/datasets")
cheese <- read.table("cheese.txt", header = TRUE)
PRESS(lm(taste ~ H2S + Lactic, data = cheese))    # 讲义:3135.437
PRESS(lm(Volume ~ Height, data = trees))          # 2025 Part II (d):6077.439
Console 输出
[1] 3135.437
[1] 6077.439

Lab 7 原题提示里写的是 lm.influence(linear.model)$hat,和 hatvalues(linear.model) 完全一样。考场上忘了就去 tut_labs.pdf 的 Lab Week 7 Q1 抄。

Rch09 · 9.1:拿掉第 3 个点真的重新拟合,验证公式
i <- 3
fit_minus_i <- lm(taste ~ H2S + Lactic, data = cheese[-i, ])     # cheese[-3, ] = 去掉第 3 行
cheese$taste[i] - predict(fit_minus_i, newdata = cheese[i, ])    # 真正的 PRESS 残差
cheese_mod <- lm(taste ~ H2S + Lactic, data = cheese)
residuals(cheese_mod)[i] / (1 - hatvalues(cheese_mod)[i])                        # 公式
Console 输出
      3
14.7147
      3
14.7147

9.3 Mallows' Cp

对一个有 p 个参数的候选模型(全模型有更多参数):

Cp=p+(σ^p2−σ^F2)(n−p)σ^F2C_p = p + \frac{(\hat\sigma_p^2 - \hat\sigma_F^2)(n - p)}{\hat\sigma_F^2}

σ^p2\hat\sigma^2_p = 候选模型的 σ^2\hat\sigma^2,σ^F2\hat\sigma^2_F = 全模型的 σ^2\hat\sigma^2。选 Cp 最小的模型;好的模型 Cp ≈ p(没有偏差)。

Rch09 · 9.5:手写 Cp 函数(考场没有 leaps 包也能用)
Cp <- function(model, full) {
  n <- length(residuals(full)); p <- length(coef(model))
  s2p <- summary(model)$sigma^2; s2F <- summary(full)$sigma^2
  p + (s2p - s2F) * (n - p) / s2F
}
full <- lm(taste ~ H2S + Lactic + Acetic, data = cheese)
Cp(lm(taste ~ H2S + Lactic, data = cheese), full)
Cp(full, full)                    # 全模型 Cp = p = 4
Console 输出
[1] 2.005401
[1] 4

leaps 包一次算所有子集(讲义和 Lab 7 的写法):

Rch09 · 9.5
library(leaps)          # 如果报错 "no package":install.packages("leaps")
cp    <- leaps(x = cheese[, 2:4], y = cheese$taste, names = names(cheese)[2:4], method = "Cp")
r2    <- leaps(x = cheese[, 2:4], y = cheese$taste, method = "r2")
adjr2 <- leaps(x = cheese[, 2:4], y = cheese$taste, method = "adjr2")
cbind(cp$which, R2 = r2$r2, AdjR2 = adjr2$adjr2, Cp = cp$Cp, p = cp$size)
Console 输出
  Acetic H2S Lactic        R2     AdjR2        Cp p
1      0   1      0 0.5711615 0.5558458  6.018928 2
1      0   0      1 0.4959486 0.4779468 11.634646 2
1      1   0      0 0.3019934 0.2770646 26.116173 2
2      0   1      1 0.6517024 0.6259025  2.005401 3
2      1   1      0 0.5821773 0.5512274  7.196444 3
2      1   0      1 0.5202762 0.4847411 11.818244 3
3      1   1      1 0.6517747 0.6115948  4.000000 4

怎么读这张表:每一行是一个候选模型。最左列是变量个数;0/1 表示这个变量在不在模型里;p 是参数个数(变量数 + 1)。x = cheese[, 2:4] 的意思是"第 2 到第 4 列作为候选预测变量"(第 1 列 taste 是响应),换数据时要改成对应的列号。

本例:Cp 最小 (2.005) 和 adjusted R² 最大 (0.626) 都是第 4 行:H2S + Lactic。

9.4 AIC

AIC=nlog⁡ ⁣(SSresn)+2p(去掉常数后的版本,stepAIC 打印的就是它)\text{AIC} = n\log\!\left(\frac{\text{SSres}}{n}\right) + 2p \quad(\text{去掉常数后的版本,stepAIC 打印的就是它})

越小越好。和 Cp 一样是"拟合 + 复杂度惩罚"。对正态线性模型,AIC 和 Cp 是等价的准则(讲义)。注意 R 里有两个函数:extractAIC() 用上面的公式(stepAIC 显示的值),AIC() 包含了所有常数项,两者数值不同,但比较模型时结论一样。

Rch09 · 9.7
AIC(cheese_mod)            # 227.7838(讲义表里的值)
extractAIC(cheese_mod)     # 第二个数 140.6475(stepAIC 里显示的值)
Console 输出
[1] 227.7838
[1]   3.0000 140.6475

9.5 逐步选择:forward / backward / stepwise

变量多时子集太多(10 个变量就有 1024 个模型),只能一步一步走:

Rch09 · 9.8
library(MASS)       # stepAIC 在 MASS 包里(R 自带)
null_mod <- lm(taste ~ 1, data = cheese)
stepAIC(null_mod, scope = ~ Acetic + H2S + Lactic, direction = "forward")
Console 输出
Start:  AIC=168.29
taste ~ 1

         Df Sum of Sq    RSS    AIC
+ H2S     1    4376.7 3286.1 144.89
+ Lactic  1    3800.4 3862.5 149.74
+ Acetic  1    2314.1 5348.7 159.50
<none>                7662.9 168.29

Step:  AIC=144.89
taste ~ H2S

         Df Sum of Sq    RSS    AIC
+ Lactic  1    617.18 2669.0 140.65
<none>                3286.1 144.89
+ Acetic  1     84.41 3201.7 146.11

Step:  AIC=140.65
taste ~ H2S + Lactic

         Df Sum of Sq    RSS    AIC
<none>                2669.0 140.65
+ Acetic  1   0.55427 2668.4 142.64

怎么读:每个 "Step" 块第一行是当前模型;表格按 AIC 从小到大排序;第一行就是这一步的选择。如果第一行是 <none>,说明"什么都不改最好",停止。路径:taste ~ 1 → +H2S → +Lactic → 停。最终模型 taste ~ H2S + Lactic。

Rch09 · 9.8:backward 和 both
full_mod <- lm(taste ~ Acetic + H2S + Lactic, data = cheese)
stepAIC(full_mod, direction = "backward")
stepAIC(lm(taste ~ Acetic, data = cheese), scope = ~ Acetic + H2S + Lactic, direction = "both")
# 没有 MASS 包也没关系:R 自带的 step() 用法完全一样
step(null_mod, scope = ~ Acetic + H2S + Lactic, direction = "forward")

9.6 Lab Week 7 Q1(biomass)—— 助教点名的题型

📄 原题 · Lab Week 7 Q1
An experiment was conducted to study the effect of stream characteristics on fish biomass. The response variable is y (the fish biomass) and predictors are x1, x2, x3 and x4. The following output from R shows an example of the model selection carried out on the biomass data set using the Mallow's Cp, R² and adjusted R² criterion.
(a) i. Which model is chosen by Mallow's Cp criterion? ii. Calculate Cp's according to the formula Cp = p + (σ̂²ₚ − σ̂²_F)(n − p)/σ̂²_F. Did you get the same answers as in the output above? iii. Identify two models for which the Cp value is close to p. Conduct an appropriate sequential F test to test whether one model is better than the other one. iv. Compute the PRESS statistic for each of the two models from the previous part. Comment on which model is better in view of the predictive power of the model.
(b) i. Which model is chosen by adjusted R² criterion? ii. The adjusted R² appears to be negative in some models. Give an explanation, how is it possible.
Rch09 · 9.6
data <- read.table("biomass.txt", header = TRUE)
Cpb  <- leaps(x = data[, 2:5], y = data$y, names = names(data)[2:5], method = "Cp")
r2b  <- leaps(x = data[, 2:5], y = data$y, method = "r2")
adjb <- leaps(x = data[, 2:5], y = data$y, method = "adjr2")
cbind(Cpb$which, R2 = r2b$r2, AdjR2 = adjb$adjr2, MallowCp = Cpb$Cp, p = Cpb$size)
Console 输出
  x1 x2 x3 x4          R2       AdjR2   MallowCp p
1  0  0  0  1 0.889036048  0.87516555   8.830749 2
1  1  0  0  0 0.446804941  0.37765556  67.936600 2
1  0  1  0  0 0.069519721 -0.04679031 118.362189 2
1  0  0  1  0 0.008698854 -0.11521379 126.491126 2
2  1  0  0  1 0.946421810  0.93111376   3.160927 3
2  0  1  0  1 0.890450376  0.85915048  10.641719 3
2  0  0  1  1 0.889869673  0.85840387  10.719332 3
2  1  0  1  0 0.456630193  0.30138168  68.623418 3
2  1  1  0  0 0.447262861  0.28933796  69.875397 3
2  0  1  1  0 0.069622058 -0.19620021 120.348511 3
3  1  1  0  1 0.960284376  0.94042656   3.308143 4
3  1  0  1  1 0.946422784  0.91963418   5.160796 4
3  0  1  1  1 0.890777320  0.83616598  12.598022 4
3  1  1  1  0 0.456813875  0.18522081  70.598868 4
4  1  1  1  1 0.962589904  0.93266183   5.000000 5
完整答案

(a) i. Cp 最小 = 3.16:模型 x1 + x4。

(a) ii. Cp(lm(y ~ x1 + x4, data = data), lm(y ~ x1 + x2 + x3 + x4, data = data)) = 3.160927,一样。

(a) iii. Cp 接近 p 的:x1+x4(p = 3, Cp = 3.16)和 x1+x2+x4(p = 4, Cp = 3.31)。嵌套 F 检验:anova(lm(y ~ x1 + x4, data = data), lm(y ~ x1 + x4 + x2, data = data)) → F = 2.0943,p = 0.198 > 0.05,没有证据说明加入 x2 更好。

(a) iv. PRESS(x1+x4) = 488928.9,PRESS(x1+x2+x4) = 447884.3 → 后者更小,预测能力更好。(注意 F 检验和 PRESS 给出了不同的倾向,这很正常:一个看显著性,一个看预测。)

(b) i. adjusted R² 最大 = 0.9404:x1 + x2 + x4。

(b) ii. Rˉ2=1−n−1n−p(1−R2)\bar R^2 = 1 - \frac{n-1}{n-p}(1 - R^2),当 R2<p−1n−1R^2 < \frac{p-1}{n-1} 时 Rˉ2<0\bar R^2 < 0:模型几乎没解释任何东西,而惩罚项让它变成负数。

Rch09 · 9.6:iii 和 iv
anova(lm(y ~ x1 + x4, data = data), lm(y ~ x1 + x4 + x2, data = data))
PRESS(lm(y ~ x1 + x4, data = data))
PRESS(lm(y ~ x1 + x4 + x2, data = data))
Console 输出
Model 1: y ~ x1 + x4
Model 2: y ~ x1 + x4 + x2
  Res.Df   RSS Df Sum of Sq      F Pr(>F)
1      7 74053
2      6 54893  1     19160 2.0943  0.198
[1] 488928.9
[1] 447884.3

9.7 Lab Week 7 Q2:写出 forward 的路径

📄 原题 · Lab Week 7 Q2 (a)(b)
(a) For the risk data discussed in lectures ('risk.txt'), carry out forward selection using AIC. Write down the path of models and the final model.
Hint: library(MASS); null <- lm(risk~1, data=riskdat); full <- lm(risk~., data=riskdat); stepAIC(null, scope = list(lower = null, upper = full), direction = 'forward')
(b) Modify the code in part a) to carry out backward elimination and stepwise regression procedures on the risk data using AIC.
Rch09 · 9.9
riskdat <- read.table("risk.txt", header = TRUE)
null  <- lm(risk ~ 1, data = riskdat)
fullr <- lm(risk ~ ., data = riskdat)
stepAIC(null, scope = list(lower = null, upper = fullr), direction = "forward")
stepAIC(fullr, direction = "backward")

输出很长,只看每个 Step 的第一行(当前模型):

Console 输出
Start:  AIC=25.27   risk ~ 1
Step:  AIC=18.69    risk ~ Div
Step:  AIC=11.09    risk ~ Div + Size
Step:  AIC=9.36     risk ~ Div + Size + Leverage
Step:  AIC=6.83     risk ~ Div + Size + Leverage + Ratio
Step:  AIC=3.68     risk ~ Div + Size + Leverage + Ratio + Earn1
Step:  AIC=3.58     risk ~ Div + Size + Leverage + Ratio + Earn1 + Earn2
         Df Sum of Sq    RSS    AIC
<none>                16.476 3.5753
+ Growth  1  0.094928 16.381 5.4309      <- 加 Growth 反而变大,停止

答案格式:Path: risk ~ 1 → +Div → +Size → +Leverage → +Ratio → +Earn1 → +Earn2. Final model: risk ~ Div + Size + Leverage + Ratio + Earn1 + Earn2。Backward:从全模型开始 → −Growth → 停,最终模型相同。

9.8 这些方法的问题(判断题素材)

✅ 本章检查清单
  • 会写 PRESS 函数,知道 ei,−i=ei/(1−hii)e_{i,-i} = e_i/(1-h_{ii})
  • 会 Cp 公式和 leaps 表;全模型 Cp = p
  • 会跑 stepAIC 并写出路径
  • 知道 forward/backward 不保证最优

第 10 章 · 残差诊断与离群点

本章目标
会看残差图判断哪个假设被违反;分清三种"标准化残差":rstandard(内学生化)、rstudent(外学生化)、标准化 PRESS 残差;会做离群点检验。
配套脚本:R/ch10_residual_diagnostics.R 原题:讲义 Week 7 例子、Lab 2 Q1(f) 考试关联:2025 Part II (c) 3 分 + 判断题第 3 题 2 分。

10.1 四个假设 & 怎么用残差图检查

假设怎么检查违反时长什么样
1. 误差不相关本课不检查(随机抽样一般满足)
2. 均值是线性的(linearity)Residuals vs Fitted 图(plot(model, which = 1))U 形 / 弯曲等系统性形状
3. 方差恒定(constant variance)同上喇叭形:越往右越散(或越窄)
4. 正态(normality)Normal Q-Q 图(which = 2)点偏离对角线,尤其两端(S 形、弯曲)
Rch10 · 10.2:讲义 Week 7 的两个例子

setwd("C:/Users/Cestbon/Desktop/MATHLAB/datasets")
inflation <- read.table("inflation.txt", header = TRUE)
inf_mod <- lm(INF ~ QUES + LEGAL + DEV, data = inflation)
par(mfrow = c(1, 2)); plot(inf_mod, which = c(1, 2)); par(mfrow = c(1, 1))
risk <- read.table("risk.txt", header = TRUE)
risk_mod <- lm(risk ~ ., data = risk)
par(mfrow = c(1, 2)); plot(risk_mod, which = c(1, 2)); par(mfrow = c(1, 1))

par(mfrow = c(1, 2)) 让两张图并排显示,看完用 par(mfrow = c(1, 1)) 恢复。讲义的结论:inflation:有 U 形和喇叭形,QQ 图也不直 → 几个假设都不满足。risk:没有 U 形(线性 OK),但有喇叭形(方差不恒定),QQ 图 OK(正态 OK)。

📄 原题 · Lab Week 2 Q1 (f)
State the model assumptions when fitting the simple linear regression model. Check these assumptions by examining the diagnostic plots.
答案(Wendy's 数据)

假设:errors uncorrelated, zero mean (⇒ linear mean), constant variance σ², (normally distributed)。

Residuals vs Fitted 有明显 U 形 → linearity violated;看不出喇叭形 → constant variance 尚可;QQ 图呈 S 形 → 有一些证据表明 normality violated。

10.2 为什么普通残差不够用

第 8 章:Var(ei)=σ2(1−hii)\mathrm{Var}(e_i) = \sigma^2(1 - h_{ii})。各个残差方差不同,高杠杆点的残差天生就小(线被它拽过去了)。所以要把每个残差除以它自己的标准差,放到同一把尺子上比较。

10.3 三种标准化残差

名字公式R分布
标准化残差(σ 已知,理论上的)eiσ1−hii\dfrac{e_i}{\sigma\sqrt{1-h_{ii}}}N(0,1)
内学生化残差 internally studentized
(R 叫 standardized residuals)
ri=eiσ^1−hiir_i = \dfrac{e_i}{\hat\sigma\sqrt{1-h_{ii}}}rstandard(model)不是精确的 t(eie_i 和 σ^\hat\sigma 不独立)
外学生化残差 externally studentizedti=eiσ^(−i)1−hiit_i = \dfrac{e_i}{\hat\sigma_{(-i)}\sqrt{1-h_{ii}}}rstudent(model)tn−p−1t_{n-p-1}

σ^(−i)\hat\sigma_{(-i)} = 去掉第 i 个点后重新拟合得到的 σ^\hat\sigma。为什么要去掉?如果第 i 个点真是离群点,它会让 σ^\hat\sigma 变大,把自己的 rir_i "稀释"掉;去掉它再估计 σ 就没有这个问题,而且 eie_i 和 σ^(−i)\hat\sigma_{(-i)} 独立,所以 tit_i 精确服从 tn−p−1t_{n-p-1}。

捷径公式(不用重新拟合):σ^(−i)2=(n−p)σ^2−ei2/(1−hii)n−p−1\hat\sigma_{(-i)}^2 = \dfrac{(n-p)\hat\sigma^2 - e_i^2/(1-h_{ii})}{n-p-1}。

玩法:把红点往上拖离开其他点,看 r 和 t 怎么变大;t 总是比 r 更"极端"。再把红点拖到最右边(高杠杆)然后上下拖,注意普通残差 e 很小但 t 依然可能很大。

Rch10 · 10.3:手算验证 rstandard 和 rstudent

capital <- read.table("capmodel.txt", header = TRUE)
capital <- capital[-c(20, 19), ]              # 讲义里先删了两行

cap_mod <- lm(Price ~ PE_ratio + TSE300, data = capital)
e <- residuals(cap_mod); h <- hatvalues(cap_mod)
n <- nrow(capital); p <- 3; s <- summary(cap_mod)$sigma
r_manual <- e / (s * sqrt(1 - h))
max(abs(r_manual - rstandard(cap_mod)))       # 0:rstandard 就是这个

s_minus_i <- sqrt(((n - p) * s^2 - e^2 / (1 - h)) / (n - p - 1))
max(abs(e / (s_minus_i * sqrt(1 - h)) - rstudent(cap_mod)))   # 0:rstudent 就是这个
Console 输出
[1] 0
[1] 4.440892e-16

10.4 标准化 PRESS 残差 = 标准化残差(2025 判断题 3)

✍️ 2025 判断题 3(2 分)

"Standardised PRESS residuals (i.e. ei,−i divided by their standard deviation) are identical to standardised ordinary residuals (i.e. ei divided by their standard deviation)." → True。

理由:ei,−i=ei1−hiie_{i,-i} = \dfrac{e_i}{1-h_{ii}},Var(ei)=σ2(1−hii)\mathrm{Var}(e_i) = \sigma^2(1-h_{ii}),所以 Var(ei,−i)=σ2(1−hii)(1−hii)2=σ21−hii\mathrm{Var}(e_{i,-i}) = \dfrac{\sigma^2(1-h_{ii})}{(1-h_{ii})^2} = \dfrac{\sigma^2}{1-h_{ii}}。因此

ei,−iσ/1−hii=ei/(1−hii)σ/1−hii=eiσ1−hii,\frac{e_{i,-i}}{\sigma/\sqrt{1-h_{ii}}} = \frac{e_i/(1-h_{ii})}{\sigma/\sqrt{1-h_{ii}}} = \frac{e_i}{\sigma\sqrt{1-h_{ii}}},

正好是标准化的普通残差。

10.5 离群点检验

用外学生化残差做检验(mean shift 模型:第 i 个误差的均值不是 0):

H0:第 i 个点不是离群点ti∼H0tn−p−1,p=2P(Tn−p−1≥∣ti∣)H_0: \text{第 } i \text{ 个点不是离群点} \quad t_i \overset{H_0}{\sim} t_{n-p-1}, \qquad p = 2P(T_{n-p-1} \ge |t_i|)
Rch10 · 10.4:讲义 capmodel 例子

cap_mod_1 <- lm(Price ~ TSE300, data = capital)    # SLR,p = 2

t_21 <- rstudent(cap_mod_1)["21"]                   # 行名为 "21" 的观测

t_21
2 * pt(-abs(t_21), df = nrow(capital) - 2 - 1)      # 自由度 n - p - 1 = 19 - 2 - 1 = 16
Console 输出
       21
-3.370171
         21
0.003897903

p = 0.0039 < 0.05 → 拒绝 H0,第 21 号观测可能是离群点,需要进一步调查。2 * pt(-abs(t), df) 和 2 * (1 - pt(abs(t), df)) 是同一个东西。

⚠️ 自由度是 n − p − 1,不是 n − p
因为又额外去掉了一个点。2025 (c) 只问值没问 p 值,但模拟题会问。

10.6 2025 Part II (c):最大的正外学生化残差

📄 2025 真题 Q2 Part II (c)【3 分】
What is the value of the largest positive externally studentized residual in the model? (model: lm(Volume ~ Height, data = trees))
Rch10 · 10.5

model <- lm(Volume ~ Height, data = trees)
max(rstudent(model))          # 答案

which.max(rstudent(model))    # 是第几个观测
Console 输出
[1] 2.622258
31
31
题目问代码
largest positive externally studentized residualmax(rstudent(model))
largest (in absolute value) externally studentized residualmax(abs(rstudent(model))),再用 which.max(abs(...)) 找是哪个
most negativemin(rstudent(model))
internally studentized / standardized residual of obs 5rstandard(model)[5]
how many |rstudent| > 2sum(abs(rstudent(model)) > 2)

10.7 plot(model) 的四张图

Rch10 · 10.6

par(mfrow = c(2, 2)); plot(model); par(mfrow = c(1, 1))
  1. Residuals vs Fitted:线性 & 等方差
  2. Normal Q-Q:正态(纵轴是 rstandard)
  3. Scale-Location:纵轴 ∣ri∣\sqrt{|r_i|},看等方差、找大残差
  4. Residuals vs Leverage:横轴杠杆,纵轴 rstandard;右上/右下角的点(高杠杆 + 大残差)最值得注意

图上自动标出的数字(如 31)是最极端的几个观测的行号。

每张图"正常"和"不正常"分别长什么样,第 25 章用模拟数据画了对照图。

✅ 本章检查清单
  • 能对着残差图说出哪个假设被违反
  • rstandard = 内学生化(用 σ̂);rstudent = 外学生化(用 σ̂₍₋ᵢ₎),~ tn−p−1t_{n-p-1}
  • 能证明标准化 PRESS 残差 = 标准化残差
  • 会 max(rstudent(model)) 和离群点 p 值

第 13 章 · 模型选择进阶:regsubsets、交叉验证、LASSO

本章目标
第 9 章讲了 PRESS、Cp、AIC 和逐步回归,Lab Test 网页里 regsubsets、交叉验证、LASSO 只要求"了解概念"。期末要会真的跑出来:regsubsets() 选每个大小的最优模型,然后对这些模型算 adjusted R² 和 PRESS 做比较。
配套脚本:R/ch13_model_selection_plus.R 原题:Lab Week 7 Q3(risk) 考试关联:2023 期末 Q2 Part I,7 分。

13.1 regsubsets:每个大小找一个"最优"模型

有 k 个预测变量时,一共有 2k2^k 个子集模型。最优子集选择(best subset selection)的做法是:对每个大小(1 个变量、2 个变量……)在所有同样大小的模型里挑 RSS 最小的那个。同样大小的模型参数个数一样,所以直接比 RSS 是公平的。

不同大小的模型之间不能比 RSS,因为变量越多 RSS 越小。这一步要用 adjusted R²、Cp、PRESS 或 AIC(第 9 章)。

Rch13 · 13.1:cheese 数据
setwd("C:/Users/Cestbon/Desktop/MATHLAB/datasets")
cheese <- read.table("cheese.txt", header = TRUE)
library(leaps)
best <- regsubsets(taste ~ Acetic + H2S + Lactic, data = cheese)
summary(best)
s <- summary(best)
s$adjr2
s$cp
which.max(s$adjr2)
coef(best, 2)
Console 输出
Selection Algorithm: exhaustive
         Acetic H2S Lactic
1  ( 1 ) " "    "*" " "
2  ( 1 ) " "    "*" "*"
3  ( 1 ) "*"    "*" "*"
[1] 0.5558458 0.6259025 0.6115948
[1] 6.018928 2.005401 4.000000
[1] 2
(Intercept)         H2S      Lactic
 -27.591815    3.946267   19.887204

怎么读 summary:每一行是一个大小。第 1 行只有 H2S 打了 *,意思是"1 个变量的模型里最好的是 taste ~ H2S";第 2 行是 H2S + Lactic;第 3 行是全模型。

⚠️ 不要想当然
2023 期末 Q2 里,1 个变量的最优模型是 cyl,不是大家以为的 wt。一定要照着 * 号写模型,不要凭感觉。默认最多找 8 个变量;变量更多时要加 nvmax = 变量个数(Lab 7 Q3 的答案就漏了这一步,老师在论坛上承认了)。

13.2 regsubsets 不给 PRESS:要自己对每个模型算

summary(best) 里有 adjr2、cp、bic、rss,没有 PRESS。考试题(2023 Q2 (b))要求对 3 个模型都算 adjusted R² 和 PRESS,所以要把每个模型用 lm() 重新拟合一遍。PRESS 公式见第 9 章:PRESS=∑(ei1−hii)2\text{PRESS} = \sum \big(\frac{e_i}{1-h_{ii}}\big)^2。

Rch13 · 13.2
PRESS <- function(model) sum((residuals(model) / (1 - hatvalues(model)))^2)
c(PRESS(lm(taste ~ H2S, data = cheese)),
  PRESS(lm(taste ~ H2S + Lactic, data = cheese)),
  PRESS(lm(taste ~ Acetic + H2S + Lactic, data = cheese)))
Console 输出
[1] 3688.080 3135.437 3402.240

结论模板:"Based on the PRESS statistic, the best model is taste ~ H2S + Lactic since it has the smallest PRESS (3135.4). Based on adjusted R², the best model is also H2S + Lactic (largest adjusted R², 0.626)." 两个标准可能选出不同的模型,各自报告即可。

📄 2023 期末 Q2 (c)【1 分】
Explain briefly the role of the PRESS statistic in model selection.
答案模板

PRESS = sum of squared prediction errors ei,−i=yi−y^i,−ie_{i,-i} = y_i - \hat y_{i,-i}, where each yiy_i is predicted by the model fitted without the i-th observation. It measures out-of-sample predictive performance: unlike RSS / R², it does not automatically decrease when predictors are added, because over-complicated models have a larger variance of prediction. We choose the model with the smallest PRESS.

13.3 验证集方法(validation set)

思路:把数据随机分成两半,用训练集拟合模型,去预测测试集,算测试误差 1ntest∑(yi−y^i)2\frac{1}{n_{test}}\sum (y_i - \hat y_i)^2。测试误差小的模型预测能力好。

Rch13 · 13.3:risk 数据
risk <- read.table("risk.txt", header = TRUE)
set.seed(1)
train <- sample(1:nrow(risk), nrow(risk) / 2)
test <- (1:nrow(risk))[-train]
fit <- lm(risk ~ Div + Ratio + Leverage, data = risk[train, ])
pred <- predict(fit, newdata = risk[test, ])
mean((risk$risk[test] - pred)^2)
set.seed(2)
train2 <- sample(1:nrow(risk), nrow(risk) / 2)
fit2 <- lm(risk ~ Div + Ratio + Leverage, data = risk[train2, ])
mean((risk$risk[-train2] - predict(fit2, risk[-train2, ]))^2)
Console 输出
[1] 2.525176
[1] 36.4298

同一个模型,只是换了随机划分,测试误差从 2.5 变成 36.4。这就是讲义说的验证集方法的缺点:结果依赖随机划分,很不稳定;而且只用一半数据拟合,浪费了信息。

⚠️ 常见错误(Lab 7 答案里也有)
算测试误差时必须用训练集拟合的模型去预测测试集。如果写成 predict(lm(..., data = risk[test, ])),就变成了在测试集上拟合再预测自己,算出来的只是测试集的 RSS/n,不是测试误差。

13.4 Lab 7 Q3 (b):最优子集 + 测试误差

📄 原题 · Lab Week 7 Q3
(a) Split the data set into a training set and a test set. (b) Fit a multiple linear regression model involving all the predictors on the training set. Perform best subset selection using regsubsets() function. For the best subsets of each size compute the test error obtained. What is the best model according to this criterion?
Rch13 · 13.4
set.seed(1)
train <- sample(1:nrow(risk), nrow(risk) / 2)
best_tr <- regsubsets(risk ~ ., data = risk[train, ], nvmax = 7)
test_X <- model.matrix(risk ~ ., data = risk[-train, ])
test_mse <- rep(NA, 7)
for (k in 1:7) {
  b <- coef(best_tr, k)
  pred <- test_X[, names(b)] %*% b
  test_mse[k] <- mean((risk$risk[-train] - pred)^2)
}
round(test_mse, 4)
which.min(test_mse)
Console 输出
[1] 2.6369 2.3118 2.5252 2.7413 2.4906 2.5076 2.5124
[1] 2

逐行解释:coef(best_tr, k) 取出大小为 k 的最优模型的系数(在训练集上估计的);test_X[, names(b)] 从测试集的设计矩阵里只取这个模型用到的列;两者相乘就是预测值。按这个随机划分,2 个变量的模型测试误差最小。换一个 seed 结果可能不同,这正是 13.3 讲的不稳定。

13.5 K 折交叉验证(K-fold CV)

为了解决验证集方法不稳定的问题:把数据随机分成 K 份(折),每次拿出 1 折当测试集,用其余 K−1 折拟合,算这 1 折的误差;轮流 K 次,取平均。

CV(K)=1K∑k=1KMSEk\text{CV}_{(K)} = \frac1K\sum_{k=1}^K \text{MSE}_k

留一法 LOOCV 是 K = n 的特例:每次只留 1 个点。对线性模型不用真的拟合 n 次,因为 CV(n)=1n∑(ei1−hii)2=PRESS/n\text{CV}_{(n)} = \frac1n\sum\big(\frac{e_i}{1-h_{ii}}\big)^2 = \text{PRESS}/n。

Rch13 · 13.5
set.seed(1)
K <- 5
folds <- sample(rep(1:K, length.out = nrow(cheese)))
cv_err <- rep(NA, K)
for (k in 1:K) {
  fit <- lm(taste ~ H2S + Lactic, data = cheese[folds != k, ])
  pred <- predict(fit, cheese[folds == k, ])
  cv_err[k] <- mean((cheese$taste[folds == k] - pred)^2)
}
mean(cv_err)
PRESS(lm(taste ~ H2S + Lactic, data = cheese)) / nrow(cheese)
Console 输出
[1] 103.1724
[1] 104.5146
方法优点缺点
验证集简单依赖随机划分,不稳定;只用一半数据拟合
K 折 CV(K = 5 或 10)稳定得多;每个点都当过一次测试点要拟合 K 次
LOOCV(K = n)没有随机性;线性模型有公式 PRESS/n一般模型要拟合 n 次

13.6 LASSO

LASSO 在最小二乘上加了一个惩罚:最小化 ∑(yi−xi⊤β)2+λ∑j≥1∣βj∣\sum (y_i - x_i^\top\beta)^2 + \lambda\sum_{j\ge1}|\beta_j|。λ 越大,系数被压得越小,有些会恰好变成 0,所以 LASSO 同时完成"选变量 + 估计"。它是另一种在偏差和方差之间做权衡的方法:牺牲一点偏差,换来更小的预测方差。λ 用交叉验证来选。

Rch13 · 13.6:Lab 7 Q3 (c)
library(glmnet)
x <- model.matrix(risk ~ ., data = risk)[, -1]
y <- risk$risk
set.seed(1)
cv_out <- cv.glmnet(x[train, ], y[train], nfolds = 3)
cv_out$lambda.min
lasso_tr <- glmnet(x[train, ], y[train])
lasso_pred <- predict(lasso_tr, s = cv_out$lambda.min, newx = x[-train, ])
mean((y[-train] - lasso_pred)^2)
lasso_full <- glmnet(x, y, lambda = cv_out$lambda.min)
coef(lasso_full)
Console 输出
[1] 0.1206482
[1] 2.324801
8 x 1 sparse Matrix of class "dgCMatrix"
                    s0
(Intercept)  3.3255012
Div          0.3562071
Ratio        0.5972630
Size        -0.2012875
Growth       .
Leverage     3.1268013
Earn1        0.0930809
Earn2        0.1325868

. 表示系数被压成了 0:这里 Growth 被踢掉了,剩 6 个非零系数(不算截距)。LASSO 的测试误差 2.32 和最优子集的最好结果(2.31)差不多。model.matrix(...)[, -1] 是因为 glmnet 要的是不含截距列的预测变量矩阵。

💡 考试怎么考 LASSO
往年真题里没有出现过 LASSO 的上机题。最可能的考法是简答或判断:LASSO 能不能把系数变成恰好 0(能)、λ 怎么选(交叉验证)、λ = 0 时是什么(普通最小二乘)、λ 很大时是什么(所有斜率都是 0,只剩截距)。
✅ 本章检查清单
  • 会用 regsubsets(),会读 * 号,照着写出每个大小的最优模型
  • 会对这几个模型用 lm() 重新拟合,算 adjusted R² 和 PRESS 并选模型
  • 能用一句话解释 PRESS 在模型选择里的作用
  • 说得出验证集、K 折 CV、LOOCV 的区别,以及 LOOCV = PRESS/n
  • 知道 LASSO 会把一些系数压成 0,λ 用交叉验证选

第 14 章 · 残差的性质 + 用哑变量做离群点检验

本章目标
第 10 章已经讲了 rstandard、rstudent 和离群点 t 检验。本章补三件期末要用的事:① 残差向量的均值和协方差矩阵 σ2(I−H)\sigma^2(I-H)(证明题地基);② Normal Q-Q 图;③ 用哑变量做离群点检验:在模型里加一个只有第 k 个观测是 1 的变量,看它的 partial t。这是 2021 Q2(10 分)和 2023 Q1 Part III(6 分)的原题型。
配套脚本:R/ch14_residuals_outlier_dummy.R 原题:讲义 Week 7–8、Tutorial Week 5 Q13。

14.1 残差的均值和协方差矩阵

回忆 e=y−y^=(I−H)ye = y - \hat y = (I - H)y。把 y=Xβ+εy = X\beta + \varepsilon 代进去,用 HX=XHX = X(第 11 章 T7):

e=(I−H)(Xβ+ε)=Xβ−Xβ+(I−H)ε=(I−H)ε.e = (I-H)(X\beta + \varepsilon) = X\beta - X\beta + (I-H)\varepsilon = (I-H)\varepsilon.
✍️ 证明:E(e) = 0,Var(e) = σ²(I − H)
E(e)=(I−H)E(ε)=0,E(e) = (I-H)E(\varepsilon) = 0, Var(e)=(I−H) Var(ε) (I−H)⊤=σ2(I−H)(I−H)⊤=σ2(I−H)2=σ2(I−H).\mathrm{Var}(e) = (I-H)\,\mathrm{Var}(\varepsilon)\,(I-H)^\top = \sigma^2 (I-H)(I-H)^\top = \sigma^2(I-H)^2 = \sigma^2(I-H).

用到:Var(Aε)=A Var(ε)A⊤\mathrm{Var}(A\varepsilon) = A\,\mathrm{Var}(\varepsilon)A^\top;I−HI-H 对称、幂等。

由此得到三个结论(判断题常考):

Rch14 · 14.1
setwd("C:/Users/Cestbon/Desktop/MATHLAB/datasets")
capital <- read.table("capmodel.txt", header = TRUE)
capital <- capital[-c(20, 19), ]
cap_mod <- lm(Price ~ TSE300, data = capital)
X <- model.matrix(cap_mod)
H <- X %*% solve(t(X) %*% X) %*% t(X)
n <- nrow(X); p <- ncol(X)
e <- residuals(cap_mod)
max(abs((diag(n) - H) %*% capital$Price - e))
sum(e)
H[1, 2]
Console 输出
[1] 4.4309e-13
[1] 1.526557e-16
[1] 0.06849128

第一行是 0(只差电脑的舍入误差),说明 e=(I−H)ye = (I-H)y;残差和为 0(有截距);h12≠0h_{12} \ne 0,所以 e1,e2e_1, e_2 相关。

14.2 Normal Q-Q 图

原理:如果 Z1,…,ZnZ_1,\dots,Z_n 来自 N(μ,σ2)N(\mu, \sigma^2),那么把排好序的 Z(i)Z_{(i)} 对着标准正态的期望顺序统计量画图,应该近似是一条直线(截距 μ、斜率 σ)。R 的 plot(model, which = 2) 画的是内学生化残差 rstandard 的 Q-Q 图。

Rch14 · 14.2
par(mfrow = c(1, 2))
plot(cap_mod, which = 2)
qqnorm(rstandard(cap_mod)); qqline(rstandard(cap_mod))
par(mfrow = c(1, 1))
💡 讲义的两个提醒
① 样本小的时候,即使误差不是正态,残差也常常"看起来"挺正态,所以 Q-Q 图在小样本里说服力有限。② Q-Q 图偏离直线,可能只是其他假设(线性、等方差)被违反的反映,要结合其他残差图一起看。

14.3 mean shift 离群点模型:加一个哑变量

怀疑第 k 个观测是离群点。mean shift 模型假设它的误差均值不是 0:E(εk)=ΔkE(\varepsilon_k) = \Delta_k,其他 E(εi)=0E(\varepsilon_i) = 0。等价于在模型里加一个哑变量 di=1d_i = 1(i=ki = k),di=0d_i = 0(其他):

yi=xi⊤β+Δkdi+εi,H0:Δk=0  vs  H1:Δk≠0.y_i = x_i^\top\beta + \Delta_k d_i + \varepsilon_i, \qquad H_0: \Delta_k = 0 \ \text{ vs } \ H_1: \Delta_k \ne 0.

检验 Δk=0\Delta_k = 0 就是看这个哑变量的 partial t 检验。

Rch14 · 14.3:讲义 capmodel 例子
which.max(abs(rstudent(cap_mod)))
k <- 19
capital$dummy <- c(rep(0, k - 1), 1, rep(0, nrow(capital) - k))
capital$dummy
m_dummy <- lm(Price ~ TSE300 + dummy, data = capital)
summary(m_dummy)
Console 输出
21
19
 [1] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1
Coefficients:
             Estimate Std. Error t value Pr(>|t|)
(Intercept) -4.913881   1.438079  -3.417  0.00353 **
TSE300       0.013952   0.001396   9.994 2.77e-08 ***
dummy       -1.510269   0.448128  -3.370  0.00390 **

Residual standard error: 0.2639 on 16 degrees of freedom
⚠️ "第几个观测"和"行名"不是一回事
这里删过两行,所以行名为 "21" 的观测其实在第 19 行。which.max 的输出上面一行是行名(21),下面一行是位置(19)。哑变量要按位置造。考试题会直接告诉你命令(例如 c(rep(0,5),1,rep(0,23))),照抄就行,但要会数:前面 0 的个数 = k − 1,后面 0 的个数 = n − k,总长 = n。

14.4 关键结论:哑变量的 partial t = 外学生化残差 t_k

Rch14 · 14.4
summary(m_dummy)$coefficients["dummy", "t value"]
rstudent(cap_mod)[k]
ti <- rstudent(cap_mod)[k]
2 * pt(-abs(ti), df = n - p - 1)
Console 输出
[1] -3.370171
       21
-3.370171
         21
0.003897903

完全相等,p 值也和第 10 章 10.5 用外学生化残差做的离群点检验一样。所以:

📄 2021 期末 Q2 (c)【4 分】
Is the above partial t-test in part (b) the same as the test based on the externally studentized residuals discussed in the lectures? State the value of the externally studentized residual for the 25th observation in model with log.mpg as the response and log.disp as the predictor. Find the p-value of an appropriate hypothesis test based on the externally studentized residuals. What R command did you use to find this p-value?
答案模板

Yes, they are the same test. In the mean shift outlier model, the partial t statistic for the dummy variable equals the externally studentized residual t25t_{25} of the original model, and both follow tn−p−1t_{n-p-1} under H0:Δ25=0H_0: \Delta_{25} = 0.

t25t_{25} = rstudent(model)[25](2021 数据算出来是 0.9841);p 值 = 2*pt(-abs(rstudent(model)[25]), df = n-2-1) = 0.3332(n = 32,df = 29)。p > 0.01 → do not reject H0,no evidence that obs 25 is an outlier。完整代码见第 22 章。

为什么相等?加了哑变量以后,第 k 个点有了"自己专属的参数",会被完美拟合(残差 = 0),所以其他参数的估计等于把第 k 个点删掉后的估计。dummy 的系数就是第 k 个点的 PRESS 残差:

Rch14 · 14.5
residuals(m_dummy)[k]
coef(m_dummy)["dummy"]
residuals(cap_mod)[k] / (1 - hatvalues(cap_mod)[k])
Console 输出
          21
2.081668e-17
    dummy
-1.510269
       21
-1.510269

14.5 考场答题模板(2023 Q1 Part III (b) 4 分 / 2021 Q2 (b) 4 分)

📄 题目原文
Is the dummy predictor significant according to a partial t-test? State the value of the test statistic, the distribution of the test statistic under the null hypothesis, the p-value and the conclusion using a 5% level of significance.
答案模板(数字用 2023 数据,见第 22 章)

H0:Δ6=0H_0: \Delta_6 = 0 vs H1:Δ6≠0H_1: \Delta_6 \ne 0 (coefficient of dummy).

Test statistic: t = 0.972 (from the summary output, row "dummy").

Null distribution: tn−pt_{n-p} for the model with the dummy, i.e. t29−3=t26t_{29-3} = t_{26}(等价地,原模型的 tn−p−1=t29−2−1=t26t_{n-p-1} = t_{29-2-1} = t_{26},同一个数)。

p-value = 0.340 > 0.05, so we do not reject H0H_0. There is no evidence that the 6th observation is an outlier (its mean is not shifted).

⚠️ 自由度
加了哑变量的模型有 p + 1 个参数,所以 partial t 的自由度是 n−(p+1)=n−p−1n - (p+1) = n - p - 1,和外学生化残差的自由度一致。R 的 summary 已经用对了,你只需要把自由度写对:看 summary 里 "Residual standard error: ... on 26 degrees of freedom",这个 26 就是。

14.6 Tutorial Week 5 Q13:mean shift 下残差的期望

📄 原题 · Tutorial Week 5 Q13 (Advanced)
Consider the mean shift outlier model with a single possible outlier yi=xi⊤β+εiy_i = x_i^\top\beta + \varepsilon_i, where the errors are uncorrelated with a common variance and for observation j, E(εj)=ΔjE(\varepsilon_j) = \Delta_j while E(εk)=0E(\varepsilon_k) = 0, k≠jk \ne j. What is the expected value of the jth raw residual E(ej)E(e_j) and the expected value of the jth PRESS residual E(ej,−j)E(e_{j,-j})?
答案

记 uju_j 为第 j 个标准基向量(第 j 个位置是 1),则 E(ε)=ΔjujE(\varepsilon) = \Delta_j u_j,ej=uj⊤e=uj⊤(I−H)εe_j = u_j^\top e = u_j^\top(I-H)\varepsilon:

E(ej)=uj⊤(I−H)Δjuj=Δj(1−hjj),E(ej,−j)=E(ej)1−hjj=Δj.E(e_j) = u_j^\top(I-H)\Delta_j u_j = \Delta_j(1 - h_{jj}),\qquad E(e_{j,-j}) = \frac{E(e_j)}{1-h_{jj}} = \Delta_j.

含义:普通残差把偏移"缩小"了 (1−hjj)(1-h_{jj}) 倍(高杠杆点缩得更厉害,所以普通残差不适合找离群点);PRESS 残差是无偏的。这也是第 11 章判断题第 37 题的来源。

✅ 本章检查清单
  • 能证明 e=(I−H)εe = (I-H)\varepsilon、E(e)=0E(e) = 0、Var(e)=σ2(I−H)\mathrm{Var}(e) = \sigma^2(I-H)
  • 知道残差方差不相等、残差之间相关
  • 会造哑变量(数清楚前后各几个 0),会读 dummy 那一行的 t 和 p
  • 知道 dummy 的 partial t = rstudent(原模型)[k],自由度 n − p − 1,能回答"是不是同一个检验"

第 15 章 · 影响点:Cook's D、DFFITS、DFBETAS、COVRATIO(含证明)

本章目标
期末最稳的分数来源之一。2020 Q4、2021 Q6、2023 Q4 每年都有一道 15 分的影响点题,题目从同一套小问里挑:解释 b−b−ib - b_{-i} 和 Cook's D 的含义 → 证明 Cook's D 的捷径公式 → 证明 y^i−y^i,−i=hiiei/(1−hii)\hat y_i - \hat y_{i,-i} = h_{ii}e_i/(1-h_{ii}) → 证明 DFFITS 的捷径公式;再加看图找影响点、手算。2020 Q4 只考 Cook's D 部分,2021 Q6 只考 DFFITS 部分,2023 Q4 两部分都考,所以两部分都要会。
formula sheet 上已经印了 rir_i、tit_i、Cook's D、DFFITS 的定义,不用背;要背的是从定义推到捷径公式的证明过程。
配套脚本:R/ch15_influence.R 原题:讲义 Week 8(rats、fish biomass)、Lab Week 8 Q1(compensation)。

15.1 什么是影响点(influential observation)

一个观测放进去或拿出来,会让结论(系数、拟合值、检验结果)发生很大变化,它就是影响点。

玩法:把红点拖到最右边,再上下拖。蓝线(用所有点)和灰虚线(去掉红点)差得越远,红点的影响越大。只上下拖、不往右拖,两条线差别就小得多。

15.2 rats 例子:一个点决定了整个结论

讲义的故事:19 只老鼠,研究者原本认为肝里的药量 y 和体重、肝重、剂量都没关系。但全模型说 Weight 和 Dose 都显著,而单独回归时谁都不显著。

Rch15 · 15.1 + 15.2
setwd("C:/Users/Cestbon/Desktop/MATHLAB/datasets")
rats <- read.table("rats.txt", header = TRUE)
rat_mod <- lm(y ~ Weight + Liver + Dose, data = rats)
summary(rat_mod)$coefficients
n <- nrow(rats); p <- 4
h <- hatvalues(rat_mod)
which(h > 2 * p / n)
round(rstudent(rat_mod), 3)
Console 输出
               Estimate  Std. Error    t value   Pr(>|t|)
(Intercept)  0.26592177 0.194585255  1.3666080 0.19188433
Weight      -0.02124634 0.007974304 -2.6643501 0.01767688
Liver        0.01429806 0.017217141  0.8304549 0.41930376
Dose         4.17811141 1.522625206  2.7440183 0.01506639
3
3
     1      2      3      4      5      6      7      8      9     10     11     12
 1.917 -1.302  0.797 -1.424 -1.134  0.097  0.777  0.731  0.159 -0.038 -1.114  0.589
    13     14     15     16     17     18     19
-1.616 -0.366  0.414 -0.851 -0.256  0.843  2.139

第 3 只老鼠杠杆 h33=0.851h_{33} = 0.851,远大于 2p/n=0.422p/n = 0.42;它的外学生化残差并不大(0.80)。把它去掉:

Rch15 · 15.3
summary(lm(y ~ Weight + Liver + Dose, data = rats[-3, ]))$coefficients
Console 输出
                Estimate Std. Error    t value  Pr(>|t|)
(Intercept)  0.311427385 0.20509398  1.5184618 0.1511537
Weight      -0.007783059 0.01871680 -0.4158329 0.6838360
Liver        0.008989337 0.01865861  0.4817795 0.6374069
Dose         1.484876661 3.71306448  0.3999060 0.6952607

什么都不显著了。"Weight 和 Dose 显著"这个结论完全是第 3 只老鼠造成的。只看残差找不到它,所以需要专门的影响度量。

15.3 四个影响度量:定义、含义、经验标准

记号:b−ib_{-i} = 去掉第 i 个观测后的最小二乘估计;y^i,−i=xi⊤b−i\hat y_{i,-i} = x_i^\top b_{-i} = 用这个估计在 xix_i 处的预测值;σ^−i\hat\sigma_{-i} = 去掉第 i 个观测后的 σ 估计;rir_i = 内学生化残差(rstandard),tit_i = 外学生化残差(rstudent)。

度量定义捷径公式衡量什么经验标准
Cook's D
cooks.distance
Di=(b−b−i)⊤X⊤X(b−b−i)pσ^2D_i = \dfrac{(b - b_{-i})^\top X^\top X(b - b_{-i})}{p\hat\sigma^2}Di=ri2phii1−hiiD_i = \dfrac{r_i^2}{p}\dfrac{h_{ii}}{1-h_{ii}}去掉第 i 个点后所有参数(因而所有拟合值)变了多少Di>1D_i > 1 有影响,> 0.5 值得看;或和 Fp,n−pF_{p,n-p} 的 50% 分位数比
DFFITS
dffits
y^i−y^i,−iσ^−ihii\dfrac{\hat y_i - \hat y_{i,-i}}{\hat\sigma_{-i}\sqrt{h_{ii}}}tihii1−hiit_i\sqrt{\dfrac{h_{ii}}{1-h_{ii}}}第 i 个拟合值变了几个标准误∣DFFITS∣>2|\text{DFFITS}| > 2
DFBETAS
dfbetas
bj−bj,−iσ^−icjj\dfrac{b_j - b_{j,-i}}{\hat\sigma_{-i}\sqrt{c_{jj}}},cjjc_{jj} = (X⊤X)−1(X^\top X)^{-1} 第 j 个对角元(不讲)第 j 个系数变了几个标准误∣DFBETAS∣>2|\text{DFBETAS}| > 2
COVRATIO
covratio
det⁡(σ^−i2(X−i⊤X−i)−1)det⁡(σ^2(X⊤X)−1)\dfrac{\det(\hat\sigma_{-i}^2(X_{-i}^\top X_{-i})^{-1})}{\det(\hat\sigma^2(X^\top X)^{-1})}σ^−i2pσ^2p11−hii\dfrac{\hat\sigma_{-i}^{2p}}{\hat\sigma^{2p}}\dfrac{1}{1-h_{ii}}去掉第 i 个点后估计的精度怎么变> 1+3p/n1+3p/n:去掉后精度变差;< 1−3p/n1-3p/n:去掉后精度变好

补充两个关系:Di=(y^−y^−i)⊤(y^−y^−i)pσ^2D_i = \dfrac{(\hat y - \hat y_{-i})^\top(\hat y - \hat y_{-i})}{p\hat\sigma^2}(所有拟合值变化的平方和);DFFITSi2=(b−b−i)⊤X⊤X(b−b−i)σ^−i2≈pDi\text{DFFITS}_i^2 = \dfrac{(b-b_{-i})^\top X^\top X(b-b_{-i})}{\hat\sigma_{-i}^2} \approx p D_i。

💡 Cook's D 为什么和 F 分布比
参数的 100(1−α)%100(1-\alpha)\% 置信椭球是 {β:(b−β)⊤X⊤X(b−β)/(pσ^2)≤Fα;p,n−p}\{\beta: (b-\beta)^\top X^\top X(b-\beta)/(p\hat\sigma^2) \le F_{\alpha;p,n-p}\}。DiD_i 就是把 β 换成 b−ib_{-i}。Di>F0.5;p,n−pD_i > F_{0.5;p,n-p} 的意思是:去掉第 i 个点后,估计跑出了用全部数据算的 50% 置信区域。

15.4 influence.measures:一次全给出

Rch15 · 15.4 – 15.6:讲义后半用的模型(去掉 Liver)
rat_mod2 <- lm(y ~ Weight + Dose, data = rats)
im <- influence.measures(rat_mod2)
round(im$infmat[1:5, ], 4)
which(apply(im$is.inf, 1, any))
p <- 3
qf(0.5, p, n - p)
c(1 - 3 * p / n, 1 + 3 * p / n)
p * cooks.distance(rat_mod2)[3]
dffits(rat_mod2)[3]^2
Console 输出
   dfb.1_ dfb.Wght dfb.Dose   dffit  cov.r cook.d    hat
1 -0.0873   0.1619  -0.1501  0.3830 0.8869 0.0459 0.0670
2  0.0555  -0.1030   0.0956 -0.2438 1.1072 0.0200 0.0670
3 -0.2440  -2.0504   2.1665  2.3466 5.7082 1.8202 0.8292
4  0.0734  -0.1361   0.1262 -0.3220 0.9874 0.0336 0.0670
5  0.6731  -0.3772   0.2862 -0.8226 1.0998 0.2117 0.2483
3
3
[1] 0.8233027
[1] 0.5263158 1.4736842
      3
5.46047
       3
5.506388

列名对照:dfb.xxx = DFBETAS(每个系数一列),dffit = DFFITS,cov.r = COVRATIO,cook.d = Cook's D,hat = 杠杆。完整输出最后一列 inf 打 * 的是 R 认为可能有影响的观测(R 对杠杆用 3p/n3p/n 的标准)。

解读第 3 只老鼠(讲义原话的意思):

15.5 用捷径公式和定义两种方式验证(证明题的数值版本)

Rch15 · 15.7 + 15.8
r <- rstandard(rat_mod2); tt <- rstudent(rat_mod2); h <- hatvalues(rat_mod2)
max(abs(r^2 / p * h / (1 - h) - cooks.distance(rat_mod2)))
max(abs(tt * sqrt(h / (1 - h)) - dffits(rat_mod2)))
i <- 3
X <- model.matrix(rat_mod2); b <- coef(rat_mod2)
b_mi <- coef(lm(y ~ Weight + Dose, data = rats[-i, ]))
s2 <- summary(rat_mod2)$sigma^2
D_def <- t(b - b_mi) %*% t(X) %*% X %*% (b - b_mi) / (p * s2)
c(D_def, cooks.distance(rat_mod2)[i])
yhat_i <- sum(X[i, ] * b); yhat_i_mi <- sum(X[i, ] * b_mi)
c(yhat_i - yhat_i_mi, h[i] * residuals(rat_mod2)[i] / (1 - h[i]))
Console 输出
[1] 1.110223e-16
[1] 1.110223e-16
                3
1.820157 1.820157
                  3
0.1628587 0.1628587

先看到它们真的相等,再去证明,就不慌了。

15.6 证明题(2020 Q4、2021 Q6、2023 Q4 原题)

题目总会给你下面这个结论,不要求证明,直接用:

b−i=b−(X⊤X)−1xiei1−hii(∗)b_{-i} = b - \frac{(X^\top X)^{-1}x_i e_i}{1-h_{ii}} \qquad (\ast)

其中 xi⊤x_i^\top 是 X 的第 i 行,eie_i 是第 i 个普通残差,hii=xi⊤(X⊤X)−1xih_{ii} = x_i^\top(X^\top X)^{-1}x_i。

P15-1 · 解释 b−b−ib - b_{-i} 和 Cook's D 的含义 2023 Q4(a) 2 分

bb is the least squares estimate of β using all n observations; b−ib_{-i} is the least squares estimate obtained by fitting the model without the i-th observation. So b−b−ib - b_{-i} is the change in the estimated parameters caused by deleting the i-th observation.

Cook's distance DiD_i measures how much all of the estimated parameters (and hence all of the fitted values) change when the i-th observation is left out, scaled by pσ^2p\hat\sigma^2. A large DiD_i indicates that observation i is influential.

P15-2 · 证明 Di=ri2phii1−hiiD_i = \dfrac{r_i^2}{p}\dfrac{h_{ii}}{1-h_{ii}} 2023 Q4(b) 4 分 · 2020 Q4(iv) 6 分

由 (∗)(\ast):b−b−i=(X⊤X)−1xiei1−hiib - b_{-i} = \dfrac{(X^\top X)^{-1}x_i e_i}{1-h_{ii}}。代入 Cook's D 的定义:

Di=(b−b−i)⊤X⊤X(b−b−i)pσ^2=ei2(1−hii)2pσ^2  xi⊤(X⊤X)−1X⊤X(X⊤X)−1xi=ei2(1−hii)2pσ^2  xi⊤(X⊤X)−1xi=ei2 hii(1−hii)2pσ^2=ei2σ^2(1−hii)⋅hiip(1−hii)=ri2p hii1−hii,\begin{aligned} D_i &= \frac{(b-b_{-i})^\top X^\top X (b-b_{-i})}{p\hat\sigma^2} = \frac{e_i^2}{(1-h_{ii})^2 p\hat\sigma^2}\; x_i^\top (X^\top X)^{-1} X^\top X (X^\top X)^{-1} x_i \\ &= \frac{e_i^2}{(1-h_{ii})^2 p\hat\sigma^2}\; x_i^\top (X^\top X)^{-1} x_i = \frac{e_i^2\, h_{ii}}{(1-h_{ii})^2 p\hat\sigma^2} \\ &= \frac{e_i^2}{\hat\sigma^2(1-h_{ii})}\cdot\frac{h_{ii}}{p(1-h_{ii})} = \frac{r_i^2}{p}\,\frac{h_{ii}}{1-h_{ii}}, \end{aligned}

因为 ri=eiσ^1−hiir_i = \dfrac{e_i}{\hat\sigma\sqrt{1-h_{ii}}},即 ri2=ei2σ^2(1−hii)r_i^2 = \dfrac{e_i^2}{\hat\sigma^2(1-h_{ii})}。

每一步用到:① (AB)⊤=B⊤A⊤(AB)^\top = B^\top A^\top 且 (X⊤X)−1(X^\top X)^{-1} 对称,所以 (b−b−i)⊤=ei1−hiixi⊤(X⊤X)−1(b-b_{-i})^\top = \frac{e_i}{1-h_{ii}} x_i^\top (X^\top X)^{-1};② eie_i、1−hii1-h_{ii} 是数,可以提出来;③ (X⊤X)−1X⊤X=I(X^\top X)^{-1}X^\top X = I;④ hiih_{ii} 的定义。

P15-3 · 解释 y^i=xi⊤b\hat y_i = x_i^\top b、y^i,−i=xi⊤b−i\hat y_{i,-i} = x_i^\top b_{-i},以及 y^i−y^i,−i\hat y_i - \hat y_{i,-i} 的含义 2021 Q6(b)(d)、2023 Q4(c)(d) 共 3 分

y^i\hat y_i is the fitted value at xix_i from the model fitted to all the data, so y^i=xi⊤b\hat y_i = x_i^\top b. y^i,−i\hat y_{i,-i} is the prediction of the i-th response from the model fitted without the i-th observation; that model has estimate b−ib_{-i} and we evaluate it at the same predictor values xix_i, so y^i,−i=xi⊤b−i\hat y_{i,-i} = x_i^\top b_{-i}.

y^i−y^i,−i\hat y_i - \hat y_{i,-i} = the change in the fitted value at the i-th point when the i-th observation is deleted. 2021 Q6(b) 要求在散点图上画出来:在 x=xix = x_i 处,黑线(全部数据拟合)和红线(去掉第 i 点拟合)之间的竖直距离。

P15-4 · 证明 y^i−y^i,−i=hiiei1−hii\hat y_i - \hat y_{i,-i} = \dfrac{h_{ii}e_i}{1-h_{ii}},并求期望和方差 2021 Q6(e) 5 分 · 2023 Q4(e) 4 分
y^i−y^i,−i=xi⊤b−xi⊤b−i=xi⊤(b−b−i)=(∗)xi⊤(X⊤X)−1xi ei1−hii=hiiei1−hii.\hat y_i - \hat y_{i,-i} = x_i^\top b - x_i^\top b_{-i} = x_i^\top(b - b_{-i}) \overset{(\ast)}{=} \frac{x_i^\top (X^\top X)^{-1}x_i\, e_i}{1-h_{ii}} = \frac{h_{ii}e_i}{1-h_{ii}}.

期望:E(ei)=0E(e_i) = 0(第 14 章),hiih_{ii} 只依赖 X,是常数,所以

E(y^i−y^i,−i)=hii1−hiiE(ei)=0.E(\hat y_i - \hat y_{i,-i}) = \frac{h_{ii}}{1-h_{ii}}E(e_i) = 0.

方差:Var(ei)=σ2(1−hii)\mathrm{Var}(e_i) = \sigma^2(1-h_{ii}),所以

Var(y^i−y^i,−i)=hii2(1−hii)2 σ2(1−hii)=σ2hii21−hii.\mathrm{Var}(\hat y_i - \hat y_{i,-i}) = \frac{h_{ii}^2}{(1-h_{ii})^2}\,\sigma^2(1-h_{ii}) = \frac{\sigma^2 h_{ii}^2}{1-h_{ii}}.
P15-5 · 证明 DFFITSi=tihii1−hii\text{DFFITS}_i = t_i\sqrt{\dfrac{h_{ii}}{1-h_{ii}}} 2021 Q6(f)、2023 Q4(f) 各 2 分

用 P15-4 的结果代入定义,再凑出 ti=eiσ^−i1−hiit_i = \dfrac{e_i}{\hat\sigma_{-i}\sqrt{1-h_{ii}}}:

DFFITSi=y^i−y^i,−iσ^−ihii=hiiei(1−hii)σ^−ihii=eiσ^−i1−hii⋅hii1−hii=tihii1−hii.\text{DFFITS}_i = \frac{\hat y_i - \hat y_{i,-i}}{\hat\sigma_{-i}\sqrt{h_{ii}}} = \frac{h_{ii}e_i}{(1-h_{ii})\hat\sigma_{-i}\sqrt{h_{ii}}} = \frac{e_i}{\hat\sigma_{-i}\sqrt{1-h_{ii}}}\cdot\frac{\sqrt{h_{ii}}}{\sqrt{1-h_{ii}}} = t_i\sqrt{\frac{h_{ii}}{1-h_{ii}}}.

关键一步:hiihii=hii\dfrac{h_{ii}}{\sqrt{h_{ii}}} = \sqrt{h_{ii}},11−hii=11−hii⋅11−hii\dfrac{1}{1-h_{ii}} = \dfrac{1}{\sqrt{1-h_{ii}}}\cdot\dfrac{1}{\sqrt{1-h_{ii}}}。

⚠️ 拿分要点
  • 每道小题第一行先写定义(例如 "By definition, Di=…D_i = \ldots" 或 "Recall ri=…r_i = \ldots"),哪怕后面推不下去也有分。
  • 题目写 "you can make use of the following result (you are not asked to prove this)" 的式子,直接引用,写 "by (2)"。
  • 后面小题可以直接用前面小题的结论(比如 (f) 用 (e)),即使前面没证出来。

15.7 看图找影响点(2020 Q4(i)、2021 Q6(a) 各 3 分)

Rch15 · 15.9
par(mfrow = c(1, 2)); plot(rat_mod2, which = c(4, 5)); par(mfrow = c(1, 1))

which = 4 是 Cook's distance 柱状图(横轴观测编号);which = 5 是 Residuals vs Leverage:横轴杠杆、纵轴 rstandard,红色虚线是 Cook's D = 0.5 和 1 的等高线。落在虚线外面(通常在右上角或右下角)的点,Cook's D 超过了对应值。

📄 2021 期末 Q6 (a)【3 分】(图见 past_final_exams/MATH2831_2021_Mobius.pdf 第 13 页)
After examining the plots, identify the potential influential observation. Write a few sentences, commenting on both plots, to give your reasons.
答案模板

Observation 14 is potentially influential. In the Residuals vs Leverage plot it has a large (negative) standardized residual, about −3, together with a relatively high leverage (about 0.24), and it lies beyond the Cook's distance contour of 1 (D14≈1.28D_{14} \approx 1.28). In the scatterplot, removing this point changes the fitted line noticeably: the red line (without obs 14) is steeper than the black line (all data), so this single point changes the slope considerably.

15.8 只给输出,手算 DFFITS 和 Cook's D(2021 Q6(c)、2020 Q4(ii))

Rch15 · 15.10
h14 <- 0.23572744; t14 <- -4.5839057
t14 * sqrt(h14 / (1 - h14))
h_20 <- c(`11` = 0.37847203, `12` = 0.38099986, `13` = 0.43661124)
r_20 <- c(`11` = -2.75414799, `12` = -0.69093819, `13` = 2.60073093)
r_20^2 / 3 * h_20 / (1 - h_20)
Console 输出
[1] -2.545755
        11         12         13
1.53966559 0.09794702 1.74725513

2021 Q6(c):∣DFFITS14∣=2.55>2|\text{DFFITS}_{14}| = 2.55 > 2 → by the rule of thumb from lectures, observation 14 is influential:去掉它,第 14 个拟合值会变约 2.5 个标准误。

📄 2020 期末 Q4 (i)(ii)【3 + 3 分】(图见 past_final_exams/MATH2831_2020.pdf 第 8 页)
A multiple linear model is fitted to data with response y and predictors x1 and x2 (n = 13).
i) Figure 3 shows a diagnostic plot for the fitted model. Based on the Cook's distance measure, which observations would you classify as being influential? Give reasons why.
ii) For the observation(s) identified as influential in the previous part, calculate Cook's DiD_i using the formula Di=ri2hiip(1−hii)D_i = \frac{r_i^2 h_{ii}}{p(1-h_{ii})} and the R output of hatvalues(model) and rstandard(model). (Obs 11: h = 0.37847203, r = −2.75414799; obs 13: h = 0.43661124, r = 2.60073093.)
答案

(i) Observations 11 and 13 are influential. In the Cook's distance plot their bars are the two tallest, both above 1, while all other bars are small. In the Residuals vs Leverage plot both lie outside the Cook's distance contour of 1: each combines a large standardized residual (about −2.75 and 2.6) with a high leverage (0.38 and 0.44, well above the average leverage p/n=3/13=0.23p/n = 3/13 = 0.23). Obs 12 has a similar leverage but a small residual, so it is not influential.

(ii) p = 3(截距 + x1 + x2)。注意题目给的是 rstandard,就是公式里的 rir_i(内学生化残差):

D11=(−2.754)2×0.37853×0.6215=7.585×0.37851.8646=1.54,D13=2.6012×0.43663×0.5634=1.75.D_{11} = \frac{(-2.754)^2 \times 0.3785}{3 \times 0.6215} = \frac{7.585 \times 0.3785}{1.8646} = 1.54,\qquad D_{13} = \frac{2.601^2 \times 0.4366}{3 \times 0.5634} = 1.75.

两个都 > 1,确认是影响点。作对比:D12=0.10D_{12} = 0.10,杠杆同样高,但残差小,所以没影响。

15.9 去掉影响点后区间变窄(讲义 fish biomass)

Rch15 · 15.11
biodata <- read.table("biomass.txt", header = TRUE)
model <- lm(y ~ x4, data = biodata)
influence.measures(model)
model2 <- lm(y ~ x4, data = biodata[-c(3, 4), ])
newdata <- data.frame(x4 = 50)
predict(model, newdata, interval = "prediction")
predict(model2, newdata, interval = "prediction")
Console 输出
     dfb.1_   dfb.x4     dffit  cov.r   cook.d   hat inf
1  -0.15299  0.09029  -0.15515 1.4811 1.35e-02 0.151
2   0.03261 -0.00369   0.04269 1.4457 1.04e-03 0.101
3   2.85558 -8.82552 -10.05760 0.0059 2.92e+00 0.435   *
4  -0.84773  2.47071   2.78343 0.4924 1.98e+00 0.472   *
...
      fit      lwr     upr
1 153.881 -188.442 496.204
       fit      lwr      upr
1 132.9646 50.51806 215.4112

观测 3 和 4 的 COVRATIO 很小(0.006 < 1−3p/n=0.41 - 3p/n = 0.4)→ 去掉它们,估计的精度会大幅提高。确实如此:σ̂ 从 138.5 降到 31.1,预测区间宽度从约 685 缩到约 165。

15.10 Lab Week 8 Q1:compensation(33 家公司)

📄 原题 · Lab Week 8 Q1 (b)(c)
(b) Plot leverages and externally studentized residuals and identify potentially high influence observations. (c) Compute the influence measures: Cook's D, DFFITS, DFBETAS and COVRATIOS for all 33 firms. Discuss your interpretation of these measurements and state which firms are potentially influential and should be reexamined and why.
Rch15 · 15.12
comp <- read.table("compensation.txt", header = TRUE)
comp_model <- lm(Compensation ~ ., data = comp)
par(mfrow = c(2, 2)); plot(comp_model); par(mfrow = c(1, 1))
n <- nrow(comp); p <- 4
which(hatvalues(comp_model) > 3 * p / n)
cm <- influence.measures(comp_model)
round(cm$infmat[apply(cm$is.inf, 1, any), ], 3)
Console 输出
13 25 29
13 25 29
   dfb.1_ dfb.Sals dfb.Prft dfb.Empl  dffit  cov.r cook.d   hat
2  -0.019   -0.392   -0.052    0.428 -0.555  1.627  0.078 0.348
5   0.426    0.022   -0.009   -0.038  0.550  0.373  0.059 0.031
13 -0.073    0.873   -0.175   -0.660  1.002  2.131  0.252 0.525
25  1.111    1.184   -1.928   -0.569 -5.357 11.195  6.862 0.925
29 -0.046    0.035   -0.191    0.197  0.231  1.878  0.014 0.394

结论:第 25 家公司是最需要重新检查的:杠杆 0.925(几乎是 1)、Cook's D = 6.86 ≫ 1、|DFFITS| = 5.36 > 2、COVRATIO = 11.2 ≫ 1.36。它的销售额、利润、员工数都远超其他公司。13、29 杠杆高但 Cook's D 小,影响有限;5 的 COVRATIO 偏小(残差较大),值得看一眼。

📄 原题 · Lab Week 8 Q1 (d)(e)
(d) Make a scatter plot of Compensation versus Profits and comment. Fit a simple linear regression model with Compensation as the response and Profits as the predictor. Using diagnostic tools, identify the point with the highest leverage, which is almost certainly a highly influential point. Refit the simple linear regression model with this observation removed and comment on the impact on the slope of the fitted line.
(e) Now apply log transform to the predictor. Plot Compensation versus log(Profits) and comment on the relationship. Fit a simple linear regression model using the log(Profits) as the predictor and the Compensation as the response. Construct the residual plots and compute the influence measures and comment on any assumptions that are violated or observations which may be highly influential. Is this model preferred over the model without the log transform from part (d)? Why or why not.
Rch15 · 15.13
comp_p <- lm(Compensation ~ Profits, data = comp)
which.max(hatvalues(comp_p)); max(hatvalues(comp_p))
comp_p25 <- lm(Compensation ~ Profits, data = comp[-25, ])
rbind(all = coef(comp_p), without25 = coef(comp_p25))
comp_log <- lm(Compensation ~ log(Profits), data = comp)
summary(comp_log)$coefficients
c(R2_profits = summary(comp_p)$r.squared, R2_logprofits = summary(comp_log)$r.squared)
par(mfrow = c(2, 2)); plot(comp_log); par(mfrow = c(1, 1))
cl <- influence.measures(comp_log)
round(cl$infmat[apply(cl$is.inf, 1, any), ], 3)
Console 输出
25
25
[1] 0.878591
          (Intercept)   Profits
all          371.5918 0.1273929
without25    340.7724 0.2751123
              Estimate Std. Error    t value     Pr(&gt;|t|)
(Intercept)  -46.75252   85.75179 -0.5452076 5.895123e-01
log(Profits)  88.70951   16.35196  5.4250072 6.348134e-06
   R2_profits R2_logprofits
    0.2813294     0.4870157
   dfb.1_ dfb.l(P) dffit cov.r cook.d   hat
5  -0.059    0.160 0.558 0.650  0.123 0.033
12  0.068   -0.063 0.072 1.225  0.003 0.130
25 -0.250    0.271 0.286 1.495  0.042 0.295
27  0.013    0.061 0.403 0.806  0.072 0.031

(d) 散点图里大部分公司的 Profits 挤在左下角,第 25 家公司的利润(3011)远大于其他公司,单独在右边。它的杠杆 0.879,是最高的(Cook's D = 8.45)。去掉它,斜率从 0.127 变成 0.275,翻了一倍多:这一个点决定了斜率,是强影响点。

(e) 取 log 后,Profits 在横轴上分布均匀多了,Compensation 和 log(Profits) 大致呈线性关系。第 25 家的杠杆降到 0.295,Cook's D 只有 0.04,不再是影响点。被标星号的 5、12、25、27 都没有 Cook's D 接近 0.5 的:5 和 27 是残差较大(外学生化残差 3.02、2.25,COVRATIO < 1),12、25 是杠杆稍高。残差图里方差仍略有随拟合值增大的趋势,值得一提。更推荐 log 模型:没有单个点主导拟合,R² 也从 0.28 提高到 0.49。

✅ 本章检查清单
  • 说得出四个度量各衡量什么、经验标准是多少
  • 会 influence.measures、cooks.distance、dffits、dfbetas、covratio
  • 能独立写出 P15-2、P15-4、P15-5 三个证明(合起来约 10 分,每年都考)
  • 会看 Residuals vs Leverage 图上的 Cook's 等高线
  • 会用给定的 hiih_{ii}、tit_i、rir_i 手算 DFFITS 和 Cook's D

第 16 章 · 变换:方差稳定、log、在原尺度比较、多项式回归

本章目标
假设被违反时怎么补救:① 变换响应变量(√y、log y、1/y),会用 Taylor 展开说明为什么能稳定方差;② 比较原尺度和 log 尺度两个模型的诊断图,说出哪个更好、为什么(2019、2020、2021、2023 每年都考,2–3 分);③ 变换后怎么在原尺度上预测、比较 PRESS;④ 多项式回归。
配套脚本:R/ch16_transformations.R 原题:讲义 Week 9(geese、inflation、trees)、Lab Week 8 Q2(fish)、Tutorial Week 9 Q3。

16.1 为什么变换能稳定方差(Tutorial Week 9 Q3)

很多数据的方差会随均值变大(残差图呈喇叭形)。对响应做变换 z=f(y)z = f(y),在 E(y)E(y) 附近做一阶 Taylor 展开:

f(y)≈f(Ey)+f′(Ey) (y−Ey)⇒Var(f(y))≈[f′(Ey)]2 Var(y).f(y) \approx f(E y) + f'(E y)\,(y - E y) \quad\Rightarrow\quad \mathrm{Var}(f(y)) \approx [f'(E y)]^2\,\mathrm{Var}(y).

选 f 让右边变成常数,方差就"稳定"了:

方差和均值的关系变换验证典型场景
Var(y)∝E(y)\mathrm{Var}(y) \propto E(y)y\sqrt yf′=12Eyf' = \frac{1}{2\sqrt{Ey}},Var≈14Ey⋅c Ey=c/4\mathrm{Var} \approx \frac{1}{4Ey}\cdot c\,Ey = c/4计数数据、Poisson
sd(y)∝E(y)\mathrm{sd}(y) \propto E(y)log⁡y\log yf′=1Eyf' = \frac{1}{Ey},Var≈1(Ey)2⋅c (Ey)2=c\mathrm{Var} \approx \frac{1}{(Ey)^2}\cdot c\,(Ey)^2 = c指数分布、"按比例"变化的量
sd(y)∝(Ey)2\mathrm{sd}(y) \propto (E y)^21/y1/yf′=−1(Ey)2f' = -\frac{1}{(Ey)^2}
y∼Bin(n,p)y \sim \text{Bin}(n,p)sin⁡−1y/n\sin^{-1}\sqrt{y/n}Var≈14n\mathrm{Var} \approx \frac{1}{4n}比例数据

y 有 0 时用 log⁡(y+1)\log(y+1) 或 1/(y+1)1/(y+1)。

✍️ 表中最后一行:比例数据的 arcsine 变换(Tutorial Week 9 Q3(c))

设 Y∼Bin(n,p)Y \sim \text{Bin}(n, p),比例 p^=Y/n\hat p = Y/n:Ep^=pE\hat p = p,Var(p^)=p(1−p)/n\mathrm{Var}(\hat p) = p(1-p)/n,方差随均值变化。取 f(x)=sin⁡−1xf(x) = \sin^{-1}\sqrt{x},用链式法则:

f′(x)=11−x⋅12x=12x(1−x).f'(x) = \frac{1}{\sqrt{1 - x}}\cdot\frac{1}{2\sqrt{x}} = \frac{1}{2\sqrt{x(1-x)}}.

代入 Taylor 公式 Var(f(p^))≈[f′(p)]2 Var(p^)\mathrm{Var}(f(\hat p)) \approx [f'(p)]^2\,\mathrm{Var}(\hat p):

Var(sin⁡−1p^)≈14p(1−p)⋅p(1−p)n=14n,\mathrm{Var}\big(\sin^{-1}\sqrt{\hat p}\big) \approx \frac{1}{4p(1-p)}\cdot\frac{p(1-p)}{n} = \frac{1}{4n},

和 p 无关,是常数,所以方差被稳定了。

📄 原题 · Tutorial Week 9 Q3 (a)(b)
Using Taylor series expansion, verify that the following transformations are approximately variance-stabilizing. (a) Y ~ Poisson(λ), consider the transform g(y)=yg(y) = \sqrt y. (b) Y ~ exp(λ), g(y)=ln⁡(y)g(y) = \ln(y).
答案

(a) E(Y)=Var(Y)=λE(Y) = \mathrm{Var}(Y) = \lambda。Y≈EY+12EY(Y−EY)\sqrt Y \approx \sqrt{EY} + \frac{1}{2\sqrt{EY}}(Y - EY),所以 Var(Y)≈14EYVar(Y)=λ4λ=14\mathrm{Var}(\sqrt Y) \approx \frac{1}{4EY}\mathrm{Var}(Y) = \frac{\lambda}{4\lambda} = \frac14,是常数。

(b) E(Y)=1/λE(Y) = 1/\lambda,Var(Y)=1/λ2=(EY)2\mathrm{Var}(Y) = 1/\lambda^2 = (EY)^2。ln⁡Y≈ln⁡EY+1EY(Y−EY)\ln Y \approx \ln EY + \frac{1}{EY}(Y - EY),所以 Var(ln⁡Y)≈1(EY)2(EY)2=1\mathrm{Var}(\ln Y) \approx \frac{1}{(EY)^2}(EY)^2 = 1,是常数。

16.2 snow geese:试 √ 再试 log

Rch16 · 16.1 + 16.2
setwd("C:/Users/Cestbon/Desktop/MATHLAB/datasets")
geese <- read.csv("geese.csv")
geese_mod <- lm(obs1 ~ photo, data = geese)
par(mfrow = c(1, 2)); plot(obs1 ~ photo, data = geese); abline(geese_mod)
plot(geese_mod, which = 1); par(mfrow = c(1, 1))
geese_sqrt <- lm(sqrt(obs1) ~ sqrt(photo), data = geese)
geese_log <- lm(log(obs1) ~ log(photo), data = geese)
par(mfrow = c(1, 2)); plot(geese_sqrt, which = 1); plot(geese_log, which = 1)
par(mfrow = c(1, 1))

原模型:散点越往右越散,残差图是明显的喇叭形 → 方差随均值增大。√ 变换有改善但还有一点喇叭形;两边都取 log 后残差图最均匀。讲义结论:"The log transformation seems to have stabilised the variance very well." 这里 x 和 y 都是鹅的数量,所以两边做同样的变换是合理的(一般情况下不一定这样做)。

16.3 考试题型:"比较两个模型的诊断图"(每年 2–3 分)

📄 2023 Q1 (a) / 2021 Q1 (a)【2 分】
Examine diagnostic plots for the two fitted simple linear regression models, one with mpg as the response and disp as the predictor, and another with log.mpg as the response and log.disp as the predictor. Comment on which model is better suited for analyzing the data set and why. Type your comments in a few sentences in the box below.
答题思路 + 模板(2023 数据画出来的图)

思路:对每个模型用 par(mfrow=c(2,2)); plot(model) 看四张图,逐条对照假设:Residuals vs Fitted(线性、等方差)、Normal Q-Q(正态)、Scale-Location(等方差)、Residuals vs Leverage(影响点)。

模板:In the model mpg ~ disp, the Residuals vs Fitted plot shows a clear U-shaped (curved) pattern, so the linearity assumption is violated, and the Scale-Location plot shows the spread increasing with the fitted values, so the constant variance assumption is doubtful. In the model log.mpg ~ log.disp, the curvature is largely removed and the spread is more even, so the linearity and constant variance assumptions are more reasonable; the Q-Q plot is roughly straight. Therefore the log-log model is better suited. However, in the log model observation 26 (disp = 2.8, a very small value) has a very high leverage (about 0.6) and lies outside the Cook's distance contour of 1, so it is influential and should be investigated further.

最后那句是用我们抄下来的 2023 数据画图看到的:log 之后 disp = 2.8 的车离其他点很远。考试时如实写出你在图上看到的东西就行。

⚠️ 不能比 R²
讲义原话:"models must be compared on the original scale and we cannot simply look at the R² or error standard deviation for models at different scales." 响应变量换了尺度,R² 和 σ̂ 就不可比了。比较依据是诊断图(推断目的),或者原尺度上的 PRESS(预测目的,见 16.5)。

16.4 inflation:log(INF)

Rch16 · 16.3
inflation <- read.table("inflation.txt", header = TRUE)
inf_mod <- lm(INF ~ QUES, data = inflation)
inf_log <- lm(log(INF) ~ QUES, data = inflation)
par(mfrow = c(2, 2)); plot(inf_mod); par(mfrow = c(1, 1))
par(mfrow = c(2, 2)); plot(inf_log); par(mfrow = c(1, 1))

原模型方差随均值增大;log 后方差稳定了很多,但 Residuals vs Leverage 图上第 22 个观测仍然有影响,讲义建议进一步调查它。

16.5 预测目的:在原尺度上比较 PRESS

设 z=f(y)z = f(y),对 z 拟合模型。第 i 个 PRESS 残差在 z 尺度上是 zi−z^i,−iz_i - \hat z_{i,-i}。要在原尺度上比较,就把预测值变回去:yi−f−1(z^i,−i)y_i - f^{-1}(\hat z_{i,-i}),然后算

∑i=1n(yi−f−1(z^i,−i))2,\sum_{i=1}^n \big(y_i - f^{-1}(\hat z_{i,-i})\big)^2,

拿它和原模型的 PRESS 比。

Rch16 · 16.4
PRESS <- function(model) sum((residuals(model) / (1 - hatvalues(model)))^2)
PRESS(inf_mod)
z_press <- residuals(inf_log) / (1 - hatvalues(inf_log))
z_hat_mi <- log(inflation$INF) - z_press
sum((inflation$INF - exp(z_hat_mi))^2)
Console 输出
[1] 16070.89
[1] 21610.81

和讲义表格里"with obs 20, 22"那一列一致(16,071 和 21,611):按这个标准原模型反而更好。讲义解释:这是离群点造成的,去掉观测 20、22 后结论反过来,log 模型更好(6501.7 < 6738.5)。代码里的关键一步:z^i,−i=zi−(zi−z^i,−i)=zi−PRESS 残差\hat z_{i,-i} = z_i - (z_i - \hat z_{i,-i}) = z_i - \text{PRESS 残差}。

16.6 Lab Week 8 Q2:fish(幂函数关系)

📄 原题 · Lab Week 8 Q2
It is believed that the weight of a fish varies with the length by the approximate relationship y≈axby \approx a x^b … (c) Apply the log transform to both the response and predictor … (d) Fit a simple linear regression model with log(weight) as the response and log(length) as the predictor … (e) Write the equation of the fitted line … (f) Predict the weight of a catfish if it is about 400 millimeters long.
Rch16 · 16.5
fish <- read.table("fish.txt", header = TRUE)
fish_model <- lm(weight ~ length, data = fish)
par(mfrow = c(2, 2)); plot(fish_model); par(mfrow = c(1, 1))
fish_model2 <- lm(log(weight) ~ log(length), data = fish)
par(mfrow = c(2, 2)); plot(fish_model2); par(mfrow = c(1, 1))
coef(fish_model2)
exp(predict(fish_model2, data.frame(length = 400)))
Console 输出
(Intercept) log(length)
 -13.763624    3.368046
       1
611.4922

为什么取 log:y=axby = a x^b 两边取 log 得 log⁡y=log⁡a+blog⁡x\log y = \log a + b\log x,在 log 尺度上是线性的。原模型的 Residuals vs Fitted 有明显 U 形(线性不成立),Q-Q 图右偏;log-log 模型的残差图好得多。

拟合线:log⁡(weight)^=−13.764+3.368log⁡(length)\widehat{\log(\text{weight})} = -13.764 + 3.368\log(\text{length}),即 weight^=e−13.764 length3.368\widehat{\text{weight}} = e^{-13.764}\,\text{length}^{3.368}。预测 400mm 的鱼:先在 log 尺度预测,再 exp 回去,约 611.5 克。

⚠️ 用 log 变量时,newdata 填什么
如果公式里写的是 log(length),newdata 里填原始的 length = 400,R 会自己取 log。如果像真题那样先建了一列 log.disp 再用 log.mpg ~ log.disp,那 newdata 里要填 log.disp = log(240)(第 22 章)。

16.7 多项式回归:trees

均值结构不是线性时,可以加入预测变量的平方项。y=β0+β1x+β2x2+εy = \beta_0 + \beta_1 x + \beta_2 x^2 + \varepsilon 对参数仍然是线性的,所以还是线性模型,照样用 lm()。

Rch16 · 16.6
trees_mod <- lm(Volume ~ Girth, data = trees)
trees$Girth2 <- trees$Girth^2
trees_mod2 <- lm(Volume ~ Girth + Girth2, data = trees)
par(mfrow = c(1, 2)); plot(trees_mod, which = 1); plot(trees_mod2, which = 1); par(mfrow = c(1, 1))
AIC(trees_mod, trees_mod2)
anova(trees_mod, trees_mod2)
Console 输出
           df      AIC
trees_mod   3 181.6447
trees_mod2  4 167.4922
  Res.Df    RSS Df Sum of Sq      F    Pr(>F)
1     29 524.30
2     28 311.38  1    212.92 19.146 0.0001524 ***

线性模型的残差图有强烈的 U 形,第 31 棵树有影响;加入 Girth² 后 U 形消失,31 也不再有影响。AIC 从 181.6 降到 167.5,F 检验 p = 0.00015,都说明平方项该加。在公式里直接写也可以:lm(Volume ~ Girth + I(Girth^2), data = trees)(I() 不能省)。

⚠️ 不考(slides 上写着 not examinable)
预测变量的非线性变换(inverse exponential、power 等形状)、Box-Tidwell、Box-Cox。Lab 8 Q3 的 Box-Tidwell 可以跳过。
✅ 本章检查清单
  • 会用 Taylor 展开说明 √y、log y 为什么能稳定方差
  • 能写"比较两个模型诊断图"的答案:逐条说假设,选出更好的模型,再提一下影响点
  • 知道不同尺度的模型不能比 R²;会在原尺度上算 PRESS
  • log 模型的预测要 exp 回去;newdata 填原值还是 log 值要看公式怎么写
  • 会加平方项做多项式回归,用 AIC 或 F 检验判断要不要

第 17 章 · 加权最小二乘 WLS 与广义最小二乘 GLS(含证明)

本章目标
方差不恒定时,另一种补救办法是改模型:允许每个观测有自己的方差,方差大的观测给小权重。2021 Q5 和 2023 Q3 各有一道 15 分的 WLS 证明题,主干相同:无截距模型 → 推导 bwb_w → 求期望和方差 → MLE 是否等于 bwb_w → 两边乘 ri\sqrt{r_i} 变回普通最小二乘。区别:2023 多一问特例 (f);2021 没有 (f),但 (a) 先要普通最小二乘 b 及其 E(b)=βE(b)=\beta、Var(b)=σ2/∑xi2\mathrm{Var}(b)=\sigma^2/\sum x_i^2,(e) 占 5 分。
配套脚本:R/ch17_wls_gls.R 原题:讲义 Week 9、Tutorial Week 9 Q1–Q2。

17.1 想法:不可靠的观测,少听它的

假设 E(εi)=0E(\varepsilon_i) = 0,误差不相关,但 Var(εi)=σi2\mathrm{Var}(\varepsilon_i) = \sigma_i^2 各不相同;或者知道权重 wiw_i,使 Var(εi)=σ2/wi\mathrm{Var}(\varepsilon_i) = \sigma^2/w_i。加权最小二乘最小化

S(β,W)=∑i=1nwi(yi−xi⊤β)2=(y−Xβ)⊤W(y−Xβ),W=diag(w1,…,wn).S(\beta, W) = \sum_{i=1}^n w_i (y_i - x_i^\top\beta)^2 = (y - X\beta)^\top W (y - X\beta), \qquad W = \mathrm{diag}(w_1, \dots, w_n).

方差大(wiw_i 小)的观测不可靠,在平方和里分量轻。结果(17.2 证明):

bw=(X⊤WX)−1X⊤Wy,Var(bw)=σ2(X⊤WX)−1.b_w = (X^\top W X)^{-1}X^\top W y, \qquad \mathrm{Var}(b_w) = \sigma^2 (X^\top W X)^{-1}.
Rch17 · 17.1 + 17.2:讲义例子
x <- c(4.17, 5.58, 5.18, 6.11, 4.50, 4.61, 5.17, 4.53, 5.33, 5.14)
y <- c(18.10392, 25.93690, 24.54264, 26.39277, 10.06054, 20.07634,
       18.48421, 17.68286, 20.62061, 20.05093)
model <- lm(y ~ x)
model1 <- lm(y ~ x, weights = c(rep(1, 4), 10, rep(1, 5)))
model2 <- lm(y ~ x, weights = c(rep(1, 4), 1 / 10, rep(1, 5)))
plot(x, y); abline(model); abline(model1, col = "blue"); abline(model2, col = "red")
rbind(OLS = coef(model), w10 = coef(model1), w0.1 = coef(model2))
w <- c(rep(1, 4), 10, rep(1, 5))
X <- cbind(1, x); W <- diag(w)
b_w <- solve(t(X) %*% W %*% X) %*% t(X) %*% W %*% y
cbind(b_w, coef(model1))
Console 输出
     (Intercept)         x
OLS   -10.805648  6.160735
w10   -32.823502 10.087460
w0.1   -3.528737  4.862951
       [,1]      [,2]
  -32.82350 -32.82350
x  10.08746  10.08746

第 5 个点 (4.50, 10.06) 偏离很远。给它权重 10,线被拉向它(斜率 10.1);给它权重 1/10,线几乎不理它(斜率 4.9)。所以 WLS 也可以用来给影响点降权,代替直接删除。矩阵公式和 lm(..., weights = ) 结果一致。

💡 WLS 和变换比,好在哪
数据保留在原尺度,模型更好解释;常态方差下的大部分理论都能照搬。权重的来源:已知 σi2\sigma_i^2;每个 x 有多个重复观测时可以估计 σi2\sigma_i^2;或者取权重与某个预测变量成比例。

17.2 GLS 与 MLE(Tutorial Week 9 Q1)

更一般地,设 ε∼N(0,V)\varepsilon \sim N(0, V),V 是任意已知的协方差矩阵(不一定对角)。广义最小二乘 GLS 最小化 (y−Xβ)⊤V−1(y−Xβ)(y - X\beta)^\top V^{-1}(y - X\beta)。WLS 是 V=σ2W−1V = \sigma^2 W^{-1}(对角)的特例;普通最小二乘是 V=σ2IV = \sigma^2 I 的特例。

✍️ 证明:GLS 估计 = MLE,并求它的分布

y∼N(Xβ,V)y \sim N(X\beta, V),似然(formula sheet 第 2 页有多元正态密度):

L(β)=1(2π)n/2∣det⁡V∣1/2exp⁡{−12(y−Xβ)⊤V−1(y−Xβ)}.L(\beta) = \frac{1}{(2\pi)^{n/2}|\det V|^{1/2}}\exp\Big\{-\tfrac12 (y - X\beta)^\top V^{-1}(y - X\beta)\Big\}.

只有指数部分含 β,所以最大化 L ⇔ 最小化 S(β)=(y−Xβ)⊤V−1(y−Xβ)S(\beta) = (y - X\beta)^\top V^{-1}(y - X\beta),即 MLE = GLS 估计。展开。中间两项 −y⊤V−1Xβ-y^\top V^{-1}X\beta 和 −β⊤X⊤V−1y-\beta^\top X^\top V^{-1}y 都是 1×1 的数,数的转置等于它自己:(y⊤V−1Xβ)⊤=β⊤X⊤(V−1)⊤y=β⊤X⊤V−1y(y^\top V^{-1}X\beta)^\top = \beta^\top X^\top (V^{-1})^\top y = \beta^\top X^\top V^{-1}y(V 对称,所以 V−1V^{-1} 也对称),因此两项合并成 −2β⊤X⊤V−1y-2\beta^\top X^\top V^{-1}y。求导用 formula sheet 的 ∂(a⊤β)/∂β=a\partial(a^\top\beta)/\partial\beta = a 和 ∂(β⊤Aβ)/∂β=Aβ+A⊤β\partial(\beta^\top A\beta)/\partial\beta = A\beta + A^\top\beta;这里 A=X⊤V−1XA = X^\top V^{-1}X 对称,所以 Aβ+A⊤β=2AβA\beta + A^\top\beta = 2A\beta:

S(β)=y⊤V−1y−2β⊤X⊤V−1y+β⊤X⊤V−1Xβ,∂S∂β=−2X⊤V−1y+2X⊤V−1Xβ=0S(\beta) = y^\top V^{-1}y - 2\beta^\top X^\top V^{-1}y + \beta^\top X^\top V^{-1}X\beta,\qquad \frac{\partial S}{\partial\beta} = -2X^\top V^{-1}y + 2X^\top V^{-1}X\beta = 0 ⇒ β^=(X⊤V−1X)−1X⊤V−1y.\Rightarrow\ \hat\beta = (X^\top V^{-1}X)^{-1}X^\top V^{-1}y.

记 A=(X⊤V−1X)−1X⊤V−1A = (X^\top V^{-1}X)^{-1}X^\top V^{-1},β^=Ay\hat\beta = Ay:

E(β^)=AXβ=(X⊤V−1X)−1X⊤V−1Xβ=β,E(\hat\beta) = A X\beta = (X^\top V^{-1}X)^{-1}X^\top V^{-1}X\beta = \beta, Var(β^)=AVA⊤=(X⊤V−1X)−1X⊤V−1 V V−1X(X⊤V−1X)−1=(X⊤V−1X)−1.\mathrm{Var}(\hat\beta) = A V A^\top = (X^\top V^{-1}X)^{-1}X^\top V^{-1}\,V\,V^{-1}X(X^\top V^{-1}X)^{-1} = (X^\top V^{-1}X)^{-1}.

β^\hat\beta 是正态向量 y 的线性变换,所以 β^∼N(β,(X⊤V−1X)−1)\hat\beta \sim N\big(\beta, (X^\top V^{-1}X)^{-1}\big)。取 V=σ2W−1V = \sigma^2 W^{-1} 就得到 WLS 的 bw=(X⊤WX)−1X⊤Wyb_w = (X^\top WX)^{-1}X^\top Wy、Var(bw)=σ2(X⊤WX)−1\mathrm{Var}(b_w) = \sigma^2(X^\top WX)^{-1}。

⚠️ 两种权重写法,方差公式差一个 σ²
权重怎么定义VVar(bw)\mathrm{Var}(b_w)出现在
Var(εi)=σ2/wi\mathrm{Var}(\varepsilon_i) = \sigma^2/w_i(σ² 未知,wiw_i 只给相对大小)σ2W−1\sigma^2W^{-1}σ2(X⊤WX)−1\sigma^2(X^\top WX)^{-1}讲义;期末 2021 Q5、2023 Q3(权重叫 rir_i)
wi=1/σi2w_i = 1/\sigma_i^2(每个方差都已知)W−1W^{-1}(X⊤WX)−1(X^\top WX)^{-1},没有 σ²Tutorial Week 9 Q2
两种都对,各自代入 Var(β^)=(X⊤V−1X)−1\mathrm{Var}(\hat\beta) = (X^\top V^{-1}X)^{-1} 就能得到。考试时先看题目怎么定义权重,再写对应的那一个。

17.3 期末证明题:无截距模型的 WLS(2023 Q3 / 2021 Q5,各 15 分)

📄 2023 期末 Q3(2021 Q5 几乎相同,只是权重记作 ki,并多了一问 OLS)
Consider the simple linear regression model with no intercept yi=βxi+εiy_i = \beta x_i + \varepsilon_i, i = 1, …, n, (1) where εi\varepsilon_i are uncorrelated errors with zero mean, but with non-constant variance given by Var(εi)=σ2/ri\mathrm{Var}(\varepsilon_i) = \sigma^2/r_i for some positive weights rir_i.
(a) [2] Derive the weighted least squares estimator bwb_w of β by minimizing Sw(β)=∑ri(yi−βxi)2S_w(\beta) = \sum r_i(y_i - \beta x_i)^2.
(b) [2] Find E(bw)E(b_w) and Var(bw)\mathrm{Var}(b_w).
(c) [3] Find the mle of β if, in addition, the errors are normally distributed. Does the mle coincide with bwb_w?
(d) [3] Multiply both sides of (1) by ri\sqrt{r_i} … Show that the new model ynew,i=βxnew,i+εnew,iy_{new,i} = \beta x_{new,i} + \varepsilon_{new,i} (2) is the ordinary least squares regression model with no intercept, that is, the errors εnew,i\varepsilon_{new,i} are i) uncorrelated, ii) with zero mean and iii) with common variance σ².
(e) [2] Prove that the least squares estimator of β for the model (2) is equal to bwb_w.
(f) [3] Find an expression for bwb_w when Var(εi)=xi2σ2\mathrm{Var}(\varepsilon_i) = x_i^2\sigma^2, xi>0x_i > 0. Write down the model (2) in this case and comment on your findings.
(a) 推导 bwb_w【2 分】
dSwdβ=∑i=1nri⋅2(yi−βxi)(−xi)=−2∑rixiyi+2β∑rixi2=0 ⇒ bw=∑i=1nrixiyi∑i=1nrixi2.\frac{dS_w}{d\beta} = \sum_{i=1}^n r_i\cdot 2(y_i - \beta x_i)(-x_i) = -2\sum r_i x_i y_i + 2\beta\sum r_i x_i^2 = 0 \ \Rightarrow\ b_w = \frac{\sum_{i=1}^n r_i x_i y_i}{\sum_{i=1}^n r_i x_i^2}.

二阶导 2∑rixi2>02\sum r_ix_i^2 > 0,所以是最小值(写一句即可)。

(b) 期望和方差【2 分】

E(yi)=βxiE(y_i) = \beta x_i,Var(yi)=σ2/ri\mathrm{Var}(y_i) = \sigma^2/r_i,yiy_i 互不相关。bwb_w 是 yiy_i 的线性组合:

E(bw)=∑rixi E(yi)∑rixi2=∑rixi⋅βxi∑rixi2=β,E(b_w) = \frac{\sum r_i x_i\,E(y_i)}{\sum r_i x_i^2} = \frac{\sum r_i x_i\cdot\beta x_i}{\sum r_i x_i^2} = \beta, Var(bw)=∑ri2xi2 Var(yi)(∑rixi2)2=∑ri2xi2 σ2/ri(∑rixi2)2=σ2∑rixi2.\mathrm{Var}(b_w) = \frac{\sum r_i^2 x_i^2\,\mathrm{Var}(y_i)}{\big(\sum r_i x_i^2\big)^2} = \frac{\sum r_i^2 x_i^2\,\sigma^2/r_i}{\big(\sum r_i x_i^2\big)^2} = \frac{\sigma^2}{\sum r_i x_i^2}.

方差那一步用了"不相关":协方差项都是 0。

(c) MLE【3 分】

误差正态且不相关 ⇒ 独立,yi∼N(βxi,σ2/ri)y_i \sim N(\beta x_i, \sigma^2/r_i):

L(β)=∏i=1nri2πσ2exp⁡{−ri(yi−βxi)22σ2},log⁡L=const−12σ2∑ri(yi−βxi)2.L(\beta) = \prod_{i=1}^n \sqrt{\frac{r_i}{2\pi\sigma^2}}\exp\Big\{-\frac{r_i(y_i - \beta x_i)^2}{2\sigma^2}\Big\},\qquad \log L = \text{const} - \frac{1}{2\sigma^2}\sum r_i (y_i - \beta x_i)^2.

"const" 不含 β。所以最大化 log⁡L\log L ⇔ 最小化 ∑ri(yi−βxi)2=Sw(β)\sum r_i(y_i - \beta x_i)^2 = S_w(\beta),得 β^MLE=∑rixiyi∑rixi2=bw\hat\beta_{MLE} = \dfrac{\sum r_ix_iy_i}{\sum r_ix_i^2} = b_w。Yes, the mle coincides with bwb_w.(也可以对 log L 求导令其为 0,得到和 (a) 一样的方程。)

(d) 变换后满足普通最小二乘的假设【3 分】

εnew,i=ri εi\varepsilon_{new,i} = \sqrt{r_i}\,\varepsilon_i,ri\sqrt{r_i} 是常数:

  • ii) E(εnew,i)=ri E(εi)=0E(\varepsilon_{new,i}) = \sqrt{r_i}\,E(\varepsilon_i) = 0;
  • iii) Var(εnew,i)=ri Var(εi)=ri⋅σ2/ri=σ2\mathrm{Var}(\varepsilon_{new,i}) = r_i\,\mathrm{Var}(\varepsilon_i) = r_i\cdot\sigma^2/r_i = \sigma^2,对所有 i 相同;
  • i) i≠ji \ne j 时 Cov(εnew,i,εnew,j)=rirj Cov(εi,εj)=0\mathrm{Cov}(\varepsilon_{new,i}, \varepsilon_{new,j}) = \sqrt{r_ir_j}\,\mathrm{Cov}(\varepsilon_i, \varepsilon_j) = 0。

因此 (2) 是误差不相关、零均值、方差恒为 σ² 的普通无截距回归模型。

(e) 变换后的 OLS = bwb_w【2 分】

无截距模型的普通最小二乘估计是 ∑xiyi∑xi2\dfrac{\sum x_iy_i}{\sum x_i^2}(2021 Q5(a) 要求推导它并求期望和方差:就是 (a)(b) 中 ri≡1r_i \equiv 1 的情形,b=∑xiyi/∑xi2b = \sum x_iy_i/\sum x_i^2,E(b)=βE(b) = \beta,Var(b)=σ2/∑xi2\mathrm{Var}(b) = \sigma^2/\sum x_i^2)。用在模型 (2) 上:

β^=∑xnew,i ynew,i∑xnew,i2=∑rixi riyi∑(rixi)2=∑rixiyi∑rixi2=bw.\hat\beta = \frac{\sum x_{new,i}\,y_{new,i}}{\sum x_{new,i}^2} = \frac{\sum \sqrt{r_i}x_i\,\sqrt{r_i}y_i}{\sum (\sqrt{r_i}x_i)^2} = \frac{\sum r_i x_i y_i}{\sum r_i x_i^2} = b_w.
(f) 特例 Var(εi)=xi2σ2\mathrm{Var}(\varepsilon_i) = x_i^2\sigma^2【3 分】

σ2/ri=xi2σ2\sigma^2/r_i = x_i^2\sigma^2 ⇒ ri=1/xi2r_i = 1/x_i^2。代入 (a):

bw=∑1xi2xiyi∑1xi2xi2=∑yi/xin=1n∑i=1nyixi.b_w = \frac{\sum \frac{1}{x_i^2}x_iy_i}{\sum\frac{1}{x_i^2}x_i^2} = \frac{\sum y_i/x_i}{n} = \frac1n\sum_{i=1}^n\frac{y_i}{x_i}.

模型 (2):ri=1/xi\sqrt{r_i} = 1/x_i,两边除以 xix_i:

yixi=β+εixi,i.e. ynew,i=β⋅1+εnew,i,  xnew,i=1.\frac{y_i}{x_i} = \beta + \frac{\varepsilon_i}{x_i},\quad\text{i.e. } y_{new,i} = \beta\cdot 1 + \varepsilon_{new,i},\ \ x_{new,i} = 1.

Comment:after the transformation, the model is simply a constant-mean (intercept-only) model for the ratios yi/xiy_i/x_i with constant variance σ², so the WLS estimator is just the sample mean of the ratios yi/xiy_i/x_i. Observations with large xix_i (large variance) are effectively down-weighted.

Rch17 · 17.3:数值验证 (a)(e)(f)
set.seed(3)
xi <- runif(30, 1, 10); r <- 1 / xi^2
yi <- 2 * xi + rnorm(30, sd = xi)
b_w_formula <- sum(r * xi * yi) / sum(r * xi^2)
b_w_lm <- coef(lm(yi ~ xi - 1, weights = r))
y_new <- sqrt(r) * yi; x_new <- sqrt(r) * xi
b_ols_new <- coef(lm(y_new ~ x_new - 1))
c(b_w_formula, b_w_lm, b_ols_new)
mean(yi / xi)
Console 输出
               xi    x_new
2.077146 2.077146 2.077146
[1] 2.077146
Rch17 · 17.4:模拟验证 (b),并看 WLS 比 OLS 更精确(可跳过)
sigma <- 1
sims <- replicate(5000, {
  yy <- 2 * xi + rnorm(30, sd = sigma * xi)
  c(wls = sum(r * xi * yy) / sum(r * xi^2), ols = sum(xi * yy) / sum(xi^2))
})
apply(sims, 1, var)
sigma^2 / sum(r * xi^2)
Console 输出
       wls        ols
0.03394474 0.05157578
[1] 0.03333333

模拟方差 0.0339 ≈ 理论值 σ2/∑rixi2=0.0333\sigma^2/\sum r_ix_i^2 = 0.0333;同样数据下 OLS 的方差(0.052)更大。方差不恒定时 OLS 仍然无偏,但不再是最有效的。

17.4 讲义 EPS 例子(R 写法)

Rch17 · 17.5
EPS <- c(0.27, 0.42, 0.39, 0.50, 0.57, 0.64, 0.76, 0.93, 1.03)
Year <- 1:9
Wn <- c(1, 1, 1, 14, 6, 87, 9, 6, 7)
gmodel <- lm(EPS ~ Year, weights = Wn)
summary(gmodel)$coefficients
Console 输出
              Estimate Std. Error  t value     Pr(>|t|)
(Intercept) 0.06491108 0.06395270 1.014986 3.439035e-01
Year        0.09929155 0.01048375 9.470994 3.057737e-05

和讲义输出一致。weights = 填的是 wiw_i(与方差成反比),不是方差本身。讲义里的 lm.gls 来自 MASS 包,考试不会要求。

✅ 本章检查清单
  • 说得出 WLS 最小化什么,权重和方差什么关系(wi∝1/σi2w_i \propto 1/\sigma_i^2)
  • 会写 bw=(X⊤WX)−1X⊤Wyb_w = (X^\top WX)^{-1}X^\top Wy、Var(bw)=σ2(X⊤WX)−1\mathrm{Var}(b_w) = \sigma^2(X^\top WX)^{-1},能用 GLS 的 MLE 推出来
  • 能独立写完 2023 Q3 的 (a)–(f)(15 分,2021 年考过主干相同的题)
  • R:lm(y ~ x, weights = w);无截距 lm(y ~ x - 1)

第 18 章 · 分类变量(哑变量)与交互项

本章目标
Week 10 新内容。会把分类变量编成哑变量,说出每个系数的含义(参照组均值、组差、斜率差),会检验"组之间有没有差别"和"斜率在组间是否相同",会换参照组。往年 2020/2021/2023 真题没考,但今年在范围内,Lab 10 有 5 道题,很可能出一道 R 题。
配套脚本:R/ch18_categorical_interactions.R 原题:讲义 Week 10、Lab Week 10 Q1–Q4。

18.1 两水平的分类变量:哑变量

inflation 数据里 DEV = 1 表示发达国家、0 表示发展中国家。0 和 1 只是标签,用来区分两组。把它当作预测变量放进模型(wiw_i = DEV):

yi=β0+β1xi+β2wi+εi⇒E(yi)={β0+β2+β1xideveloped (wi=1)β0+β1xideveloping (wi=0)y_i = \beta_0 + \beta_1 x_i + \beta_2 w_i + \varepsilon_i \quad\Rightarrow\quad E(y_i) = \begin{cases}\beta_0 + \beta_2 + \beta_1 x_i & \text{developed } (w_i = 1)\\ \beta_0 + \beta_1 x_i & \text{developing } (w_i = 0)\end{cases}

两条平行线:斜率都是 β1\beta_1,截距差 β2\beta_2。β2\beta_2 = 在 x(QUES)相同的情况下,两组 y 的期望差("after adjusting for x")。检验组效应:看 β2\beta_2 的 partial t,H0:β2=0H_0: \beta_2 = 0。

Rch18 · 18.1
setwd("C:/Users/Cestbon/Desktop/MATHLAB/datasets")
inflation <- read.table("inflation.txt", header = TRUE)
inf_mod <- lm(INF ~ QUES + DEV, data = inflation)
summary(inf_mod)$coefficients
b <- coef(inf_mod)
plot(INF ~ QUES, data = inflation, col = inflation$DEV + 1, pch = 19)
abline(b[1], b[2], col = 1)
abline(b[1] + b[3], b[2], col = 2)
Console 输出
              Estimate Std. Error   t value     Pr(>|t|)
(Intercept)  59.621691   14.32393  4.162383 0.0005288133
QUES         -4.072338    2.75342 -1.479011 0.1555262726
DEV         -22.789136   12.12810 -1.879036 0.0756688803

结论怎么写(讲义原文的意思):There is weak evidence (p = 0.0757) that inflation differs between developed and developing countries after controlling for QUES; at the 5% level we do not reject H0:β2=0H_0: \beta_2 = 0. Holding QUES constant, going from a developing to a developed country changes inflation by b2=−22.79b_2 = -22.79, i.e. reduces it by 22.79.

18.2 用文字标签时,R 自动编码

Rch18 · 18.2
inflation$Dev <- ifelse(inflation$DEV == 1, "developed", "developing")
inf_mod_lab <- lm(INF ~ QUES + Dev, data = inflation)
summary(inf_mod_lab)$coefficients
head(model.matrix(inf_mod_lab), 3)
Console 输出
               Estimate Std. Error   t value   Pr(>|t|)
(Intercept)   36.832555   21.06292  1.748692 0.09648278
QUES          -4.072338    2.75342 -1.479011 0.15552627
Devdeveloping 22.789136   12.12810  1.879036 0.07566888
  (Intercept) QUES Devdeveloping
1           1 10.0             0
2           1  8.1             1
3           1  7.8             0

R 按字母顺序把第一个水平(developed)当参照组,为其他水平各建一个哑变量,名字是"变量名 + 水平名":Devdeveloping = 1 表示 developing。所以系数符号反过来了(+22.79),截距变成了发达国家的截距,但结论和 p 值完全一样。看 model.matrix() 就知道 R 是怎么编的。

18.3 交互项:不平行的线

yi=β0+β1xi+β2wi+β3wixi+εi ⇒ E(yi)={(β0+β2)+(β1+β3)xiwi=1β0+β1xiwi=0y_i = \beta_0 + \beta_1 x_i + \beta_2 w_i + \beta_3 w_i x_i + \varepsilon_i \ \Rightarrow\ E(y_i) = \begin{cases}(\beta_0 + \beta_2) + (\beta_1 + \beta_3)x_i & w_i = 1\\ \beta_0 + \beta_1 x_i & w_i = 0\end{cases}

β2\beta_2 = 截距之差,β3\beta_3 = 斜率之差。三种情况:

情况含义怎么检验
β2=β3=0\beta_2 = \beta_3 = 0两组完全一样(同一条线)H0:β2=β3=0H_0: \beta_2 = \beta_3 = 0 → 嵌套 F 检验:anova(lm(y ~ x), lm(y ~ x * w))
β3=0\beta_3 = 0,β2≠0\beta_2 \ne 0平行线:组间差别不随 x 变
β3≠0\beta_3 \ne 0不平行:x 的效应在两组不同H0:β3=0H_0: \beta_3 = 0 → 交互项的 partial t
Rch18 · 18.3
inf_int <- lm(INF ~ QUES + DEV + QUES:DEV, data = inflation)
summary(inf_int)$coefficients
anova(lm(INF ~ QUES, data = inflation), inf_int)
Console 输出
              Estimate Std. Error    t value     Pr(>|t|)
(Intercept)  66.796101  16.582713  4.0280561 0.0007889631
QUES         -5.641294   3.300321 -1.7093169 0.1045760430
DEV         -57.062476  41.031496 -1.3906994 0.1812721183
QUES:DEV      5.313783   6.073691  0.8748854 0.3931607074
  Res.Df     RSS Df Sum of Sq      F Pr(>F)
1     20 11561.9
2     18  9352.3  2    2209.5 2.1263 0.1483

A:H0:β2=β3=0H_0: \beta_2 = \beta_3 = 0,F = 2.13,p = 0.148 → no evidence of a difference in inflation between the two groups. B:H0:β3=0H_0: \beta_3 = 0,t = 0.875,p = 0.393 → no evidence that the effect of QUES differs between developing and developed countries。QUES * DEV 是 QUES + DEV + QUES:DEV 的简写。讲义还提醒:这个模型的残差图显示两组方差差别很大,检验结论可能不可靠。

⚠️ 拟合线怎么写
题目常让你写出每组的拟合线(Mock B Q2 (e))。参照组:截距 b0b_0、斜率 b1b_1;另一组:截距 b0+b2b_0 + b_2、斜率 b1+b3b_1 + b_3。比如上面发达国家:INF^=(66.80−57.06)+(−5.64+5.31) QUES=9.73−0.33 QUES\widehat{INF} = (66.80 - 57.06) + (-5.64 + 5.31)\,QUES = 9.73 - 0.33\,QUES。

18.4 讲义 mussel 例子(数据没发,只看输出)

Console 输出
lm(formula = log(Weight) ~ Age + Location + Age:Location, data = mussel)
              Estimate Std. Error t value Pr(>|t|)
(Intercept)   -0.78280    0.15020  -5.212 2.90e-06 ***
Age            0.17047    0.01437  11.860  < 2e-16 ***
Location       0.95547    0.19779   4.831 1.13e-05 ***
Age:Location  -0.04567    0.01827  -2.500   0.0154 *

Location = 0/1 表示两个地点。交互项 p = 0.0154 < 0.05 → 有证据表明 Age 对 log(Weight) 的效应在两个地点不同。地点 1:−0.783+0.170 Age-0.783 + 0.170\,\text{Age};地点 2:(−0.783+0.955)+(0.170−0.046) Age=0.173+0.125 Age(-0.783 + 0.955) + (0.170 - 0.046)\,\text{Age} = 0.173 + 0.125\,\text{Age}。这里也先做了 log 变换来稳定方差(第 16 章)。

18.5 三个及以上水平:r 个水平用 r − 1 个哑变量

讲义 real estate:房价 y、面积 x、取暖方式 z ∈ {electricity, heating oil, natural gas}。定义 w1=1w_1 = 1(electricity),w2=1w_2 = 1(heating oil);两个都是 0 就是 natural gas(参照组):

E(yi)={β0+β2+β1xielectricityβ0+β3+β1xiheating oilβ0+β1xinatural gasE(y_i) = \begin{cases}\beta_0 + \beta_2 + \beta_1x_i & \text{electricity}\\ \beta_0 + \beta_3 + \beta_1x_i & \text{heating oil}\\ \beta_0 + \beta_1x_i & \text{natural gas}\end{cases}

β2\beta_2 = electricity 和 natural gas 的差,β3\beta_3 = heating oil 和 natural gas 的差。为什么不能用 3 个哑变量:三个加起来恒等于 1,等于截距那一列,X 不满秩(第 19 章)。

Console 输出
lm(formula = Price ~ Size + w1 + w2, data = real)
            Estimate Std. Error t value Pr(>|t|)
(Intercept)  35.0703     8.1817   4.286  0.00128 **
Size          3.6882     0.4138   8.913 2.31e-06 ***
w1          -13.6639     4.2649  -3.204  0.00840 **
w2          -26.1094     4.2770  -6.105 7.69e-05 ***

anova(real_mod_null, real_mod)   # Price ~ Size  vs  Price ~ Size + w1 + w2
  Res.Df    RSS Df Sum of Sq      F    Pr(>F)
2     11 500.04  2    1695.8 18.652 0.0002923 ***

"取暖方式对房价有没有影响" = H0:β2=β3=0H_0: \beta_2 = \beta_3 = 0,不能看 summary(summary 里每个 t 只检验一个系数),要用嵌套 F 检验:F = 18.65,p = 0.0003 → strong evidence that heating method affects price after controlling for size。用 R 的自动编码 lm(Price ~ Size + Heating) 时,anova() 的 Heating 那一行正好是这个 F(Heating 排在 Size 后面,sequential SS 就是"控制 Size 后")。

18.6 Lab 10 Q2:pill(三组,看均值)

📄 原题 · Lab Week 10 Q2
Forty-five people are randomly divided into three groups of fifteen each … one group receiving the new pill, one group receiving vitamin C, and one group receiving a placebo … Dummy1 is one for subjects receiving the new pill and zero otherwise, Dummy2 is one for subjects receiving vitamin C and zero otherwise. (a) Estimate the mean number of days with colds in each group. (b) Is there evidence that the mean number of days with colds is the same in all groups? (c) Do you think the new pill is better than the placebo? Is taking vitamin C better than taking the placebo?
Rch18 · 18.4
pill <- data.frame(
  y = c(9,12,17,13,5,19,6,8,10,11,2,14,15,1,12,
        4,15,8,6,9,8,18,0,12,6,7,10,11,2,6,
        13,7,2,0,11,8,5,3,10,9,8,8,4,7,1),
  Dummy1 = rep(c(0, 1, 0), each = 15),
  Dummy2 = rep(c(0, 0, 1), each = 15))
pill_mod <- lm(y ~ Dummy1 + Dummy2, data = pill)
summary(pill_mod)
b <- coef(pill_mod)
c(placebo = b[[1]], new_pill = b[[1]] + b[[2]], vitaminC = b[[1]] + b[[3]])
Console 输出
Coefficients:
            Estimate Std. Error t value Pr(>|t|)
(Intercept)   10.267      1.187   8.646 7.15e-11 ***
Dummy1        -2.133      1.679  -1.270   0.2109
Dummy2        -3.867      1.679  -2.303   0.0263 *

Residual standard error: 4.599 on 42 degrees of freedom
Multiple R-squared:  0.1124,	Adjusted R-squared:  0.07018
F-statistic:  2.66 on 2 and 42 DF,  p-value: 0.08168
  placebo  new_pill  vitaminC
10.266667  8.133333  6.400000
💡 为什么 overall F 显著性和单个 t 不一致
overall F 把两个组差放在一起做一个检验(H0H_0:两个都 = 0),分子是两个组差贡献的平方和再除以 2。如果只有一个组差明显不为 0,另一个接近 0,这个"除以 2"会把显著的那个冲淡,F 就可能不显著;反过来,两个组差各自都不太显著,合起来也可能让 F 显著。这和第 11 章判断题第 15 题是同一类现象。

18.7 Lab 10 Q1、Q3、Q4(同样套路)

Rch18 · 18.5:carsales(Q1)
cars <- data.frame(
  RetailSales = c(978,1123,1125,1260,1121,1275,1257,1381,1172,1368,1382,1454,1260,1462),
  GNP = c(1112.5,1143.0,1169.3,1204.7,1248.9,1277.9,1308.9,1344.0,1358.8,1383.8,
          1416.3,1430.9,1416.6,1440.9),
  Increase = c(0,0,0,0,0,0,0,1,1,1,1,1,1,1))
summary(lm(RetailSales ~ GNP * Increase, data = cars))$coefficients
summary(lm(RetailSales ~ GNP + Increase, data = cars))$coefficients
Console 输出
                 Estimate   Std. Error    t value   Pr(>|t|)
(Intercept)  -254.7117487  585.6560812 -0.4349169 0.67285871
GNP             1.1720907    0.4835425  2.4239665 0.03581786
Increase     -452.5303476 1447.2017269 -0.3126933 0.76093718
GNP:Increase    0.3016354    1.0622778  0.2839515 0.78223996
              Estimate  Std. Error    t value  Pr(>|t|)
(Intercept) -330.29308 499.3970672 -0.6613837 0.5219787
GNP            1.23459   0.4121577  2.9954309 0.0121789
Increase     -42.45569  89.6100626 -0.4737826 0.6449192

(a) 交互项 t = 0.284,p = 0.78 → no evidence of interaction between GNP and Increase。(b) 去掉交互后,Increase 的 t = −0.474,p = 0.64 → no evidence of an effect due to Increase(石油危机)。

Rch18 · 18.6:sleep(Q3)
sleep_dat <- data.frame(
  Score = c(8.95,6.48,8.04,7.81,7.72,7.50,6.21,6.90, 7.70,8.04,5.81,5.96,6.61,7.30,6.07,7.46,
            5.99,5.78,6.79,7.60,6.43,5.78,5.85,6.00),
  Group2 = rep(c(0, 1, 0), each = 8),
  Group3 = rep(c(0, 0, 1), each = 8))
summary(lm(Score ~ Group2 + Group3, data = sleep_dat))
Console 输出
            Estimate Std. Error t value Pr(>|t|)
(Intercept)   7.4513     0.2856  26.087  < 2e-16 ***
Group2       -0.5825     0.4039  -1.442  0.16404
Group3       -1.1738     0.4039  -2.906  0.00845 **
F-statistic: 4.222 on 2 and 21 DF,  p-value: 0.02877

overall F:p = 0.029 → 睡眠剥夺程度和表现有关。Group 2(20 小时)和 Group 1(16 小时)差别不显著(p = 0.16);Group 3(24 小时)显著更差(p = 0.008)。

Rch18 · 18.7:hair colour(Q4),用 factor 让 R 自动编码
hair <- data.frame(
  Pain = c(62,60,71,55,48, 63,57,52,41,43, 42,50,41,37, 32,39,51,30,35),
  Colour = factor(rep(c("LightBlond","DarkBlond","LightBrunette","DarkBrunette"),
                      times = c(5, 5, 4, 5)),
                  levels = c("LightBlond","DarkBlond","LightBrunette","DarkBrunette")))
hair_mod <- lm(Pain ~ Colour, data = hair)
summary(hair_mod)
tapply(hair$Pain, hair$Colour, mean)
Console 输出
                    Estimate Std. Error t value Pr(>|t|)
(Intercept)           59.200      3.655  16.198 6.53e-11 ***
ColourDarkBlond       -8.000      5.169  -1.548 0.142507
ColourLightBrunette  -16.700      5.482  -3.046 0.008166 **
ColourDarkBrunette   -21.800      5.169  -4.218 0.000746 ***
F-statistic: 6.791 on 3 and 15 DF,  p-value: 0.004114
   LightBlond     DarkBlond LightBrunette  DarkBrunette
         59.2          51.2          42.5          37.4

(a) 均值:Light Blond = 59.2(参照组),Dark Blond = 59.2 − 8.0 = 51.2,Light Brunette = 42.5,Dark Brunette = 37.4。(b) ANOVA 表里的 F 检验 H0:β1=β2=β3=0H_0: \beta_1 = \beta_2 = \beta_3 = 0,即四组均值都相同;p = 0.004 → 至少有一组不同。factor(..., levels = ) 决定水平顺序,第一个就是参照组。

18.8 换参照组:relevel

summary 里每个哑变量的 t 只比较"这一组 vs 参照组"。想比较两个非参照组(比如 Light Brunette vs Dark Brunette),就把其中一个设为参照组重新拟合:

Rch18 · 18.8
hair$Colour2 <- relevel(hair$Colour, ref = "DarkBrunette")
summary(lm(Pain ~ Colour2, data = hair))$coefficients
Console 输出
                     Estimate Std. Error    t value     Pr(>|t|)
(Intercept)              37.4   3.654769 10.2332061 3.686473e-08
Colour2LightBlond        21.8   5.168623  4.2177576 7.456822e-04
Colour2DarkBlond         13.8   5.168623  2.6699566 1.747971e-02
Colour2LightBrunette      5.1   5.482153  0.9302915 3.669512e-01

Light Brunette vs Dark Brunette:p = 0.37,没有差别。relevel 要求变量是 factor;用 read.table 读文字列时要加 stringsAsFactors = TRUE,否则先用 factor() 转。讲义 real estate 例子也是这样回答"oil vs gas 有没有差别"的。另一种不用重新拟合的方法是一般线性假设(第 19 章)。

✅ 本章检查清单
  • 能写出每组的 E(y)E(y),说清楚每个系数的含义(参照组、组差、斜率差)
  • "组之间有没有差别"用嵌套 F(或模型里只有哑变量时用 overall F);单个组 vs 参照组看 partial t
  • 交互:β3\beta_3 的 t 检验 = 斜率在组间是否相同;能写出每组的拟合线
  • 会 factor、relevel、model.matrix,知道 R 默认按字母顺序选参照组
  • r 个水平只用 r − 1 个哑变量(否则不满秩)

第 19 章 · 非满秩模型、单因素分类模型、一般线性假设

本章目标
Week 10 后半。① 知道"最自然"的单因素模型 yij=μ+ai+εijy_{ij} = \mu + a_i + \varepsilon_{ij} 为什么不满秩;② 两种重新参数化:哑变量编码(参照组)和去掉截距(直接估计组均值),能写出设计矩阵 X、解释参数;③ 一般线性假设 H0:Cβ=dH_0: C\beta = d 的 F 统计量,会手算。
配套脚本:R/ch19_one_way_glh.R 原题:讲义 Week 10(height、tax forms)、Tutorial Week 9 Q4、Lab Week 10 Q5。

19.1 单因素分类模型(one-way classification)

数据按一个因素分成 k 组,yijy_{ij} = 第 i 组的第 j 个观测(j=1,…,nij = 1,\dots,n_i):

yij=μ+ai+εij,E(yij)=μ+ai.y_{ij} = \mu + a_i + \varepsilon_{ij},\qquad E(y_{ij}) = \mu + a_i.

μ = 总体均值(grand mean),aia_i = 第 i 组的组效应,即第 i 组均值偏离 μ 多少。目的:检验各组均值是否相同、比较两组之间的差。

写成回归:yij=μ+∑v=1kavxvj+εijy_{ij} = \mu + \sum_{v=1}^k a_v x_{vj} + \varepsilon_{ij},xvj=1x_{vj} = 1(属于第 v 组)否则 0。讲义 height 例子(4 男 4 女):

y=(172174⋮173164),X=(110110⋮⋮⋮101101),β=(μa1a2).y = \begin{pmatrix}172\\174\\ \vdots\\173\\164\end{pmatrix},\qquad X = \begin{pmatrix}1&1&0\\1&1&0\\ \vdots&\vdots&\vdots\\1&0&1\\1&0&1\end{pmatrix},\qquad \beta = \begin{pmatrix}\mu\\a_1\\a_2\end{pmatrix}.

X 的第 1 列 = 第 2 列 + 第 3 列(每个人恰好属于一组),所以 X 不满秩,X⊤XX^\top X 不可逆,正规方程没有唯一解,μ 和 aia_i 不能唯一估计。

Rch19 · 19.1
Height <- c(172, 174, 176, 171, 166, 165, 173, 164)
Gender <- factor(c(rep("M", 4), rep("F", 4)))
X_full <- cbind(mu = 1, a1 = Gender == "M", a2 = Gender == "F") * 1
qr(X_full)$rank
det(t(X_full) %*% X_full)
Console 输出
[1] 2
[1] 0

3 列但秩只有 2。解决办法:重新参数化,让 X 满秩。

19.2 方法 1:哑变量编码(选参照组 m)

把参照组 m 的那一列去掉,令 μm:=μ+am\mu_m := \mu + a_m:

E(yij)={μmi=mμm+aii≠mE(y_{ij}) = \begin{cases}\mu_m & i = m\\ \mu_m + a_i & i \ne m\end{cases}

截距 μm\mu_m = 参照组的均值;aia_i = 第 i 组均值和参照组均值的差。检验"第 i 组和参照组一样":aia_i 的 partial t;检验"所有组均值相同":H0H_0: 所有 ai=0a_i = 0,即 overall F。这就是第 18 章 R 默认的做法。

Rch19 · 19.2
height <- data.frame(Height, Gender)
height$Gender <- relevel(height$Gender, ref = "M")
model1 <- lm(Height ~ Gender, data = height)
model.matrix(model1)
coef(model1)
Console 输出
  (Intercept) GenderF
1           1       0
...
5           1       1
...
(Intercept)     GenderF
     173.25       -6.25

男性均值 173.25;女性 = 173.25 − 6.25 = 167。

19.3 方法 2:去掉截距,直接估计每组均值

利用 ∑vxvj=1\sum_v x_{vj} = 1,令 μv:=μ+av\mu_v := \mu + a_v:

yij=∑v=1kμvxvj+εij,E(yij)=μi.y_{ij} = \sum_{v=1}^k \mu_v x_{vj} + \varepsilon_{ij},\qquad E(y_{ij}) = \mu_i.

X 去掉全 1 列,每组一列 0/1,满秩。参数就是各组均值。R 里写 y ~ group - 1(或 -1 + group)。

Rch19 · 19.3
model2 <- lm(Height ~ Gender - 1, data = height)
model.matrix(model2)
coef(model2)
Console 输出
  GenderM GenderF
1       1       0
...
5       0       1
...
GenderM GenderF
 173.25  167.00
⚠️ 方法 2 的 summary 里的检验"没什么用"
每个 t 检验的是 μi=0\mu_i = 0(某组均值是不是 0),overall F 检验的是"所有组均值都是 0",而且 R² 也不是通常的意思(0.98 这种大数)。真正关心的"组均值是否相等"要用方法 1 的 F 检验,或者下面的一般线性假设。

19.4 tax forms(Lab 10 Q5 / Tutorial Week 9 Q4)

📄 原题 · Tutorial Week 9 Q4 / Lab Week 10 Q5 (a)
Completion times for tax returns: old format, and three new formats (A, B and C). Parametrize the above data into a format suitable for linear regression by using (a) Dummy Coding … Describe the form of the design matrix X.
答案

以 Current Format 为参照组,3 个哑变量:x1=1x_1 = 1(Format A),x2=1x_2 = 1(Format B),x3=1x_3 = 1(Format C)。X 有 4 列 (1,x1,x2,x3)(1, x_1, x_2, x_3):Current 的行是 (1,0,0,0),A 的行是 (1,1,0,0),B 是 (1,0,1,0),C 是 (1,0,0,1)。方法 2 则是 4 列都是组指示变量、没有全 1 列:Current 行 (1,0,0,0),A 行 (0,1,0,0)……

Effects coding(Tutorial 9 Q4 (b))讲义没讲,不考。

Rch19 · 19.4
time <- data.frame(
  Time = c(6.3,9.8,10.1,8.5,7.1, 9.2,8.6,10.3,11.4,8.5, 12.6,10.9,11.8,10.8,10.1,
           7.5,9.3,8.8,7.8,9.1),
  Format = factor(rep(c("a", "A", "B", "C"), each = 5), levels = c("a", "A", "B", "C")))
m1 <- lm(Time ~ Format, data = time)
summary(m1)
m2 <- lm(Time ~ -1 + Format, data = time)
summary(m2)$coefficients
Console 输出
            Estimate Std. Error t value Pr(>|t|)
(Intercept)   8.3600     0.5409  15.456 4.87e-11 ***
FormatA       1.2400     0.7649   1.621  0.12454
FormatB       2.8800     0.7649   3.765  0.00169 **
FormatC       0.1400     0.7649   0.183  0.85708
Residual standard error: 1.209 on 16 degrees of freedom
F-statistic: 6.056 on 3 and 16 DF,  p-value: 0.005895
        Estimate Std. Error  t value     Pr(>|t|)
Formata     8.36  0.5408789 15.45632 4.870815e-11
FormatA     9.60  0.5408789 17.74889 5.980430e-12
FormatB    11.24  0.5408789 20.78099 5.296767e-13
FormatC     8.50  0.5408789 15.71516 3.792605e-11

"a" 是现行格式(Current)。方法 1:现行格式均值 8.36;只有 B 和现行格式显著不同(p = 0.0017,B 慢 2.88);overall F p = 0.006 → 四种格式均值不全相同。方法 2 直接给出四个均值。

19.5 一般线性假设 H0:Cβ=dH_0: C\beta = d

想检验 μB=μC\mu_B = \mu_C?在方法 2 下就是 μB−μC=0\mu_B - \mu_C = 0,partial t 和 overall F 都不能直接回答。把它写成参数的线性组合:

μB−μC=(0,0,1,−1)(μaμAμBμC)=c⊤β=0.\mu_B - \mu_C = (0, 0, 1, -1)\begin{pmatrix}\mu_a\\\mu_A\\\mu_B\\\mu_C\end{pmatrix} = c^\top\beta = 0.

多个约束一起检验(如 μA=μB\mu_A = \mu_B 且 μB=μC\mu_B = \mu_C)就把它们堆成矩阵:

C=(01−10001−1),d=(00),H0:Cβ=d.C = \begin{pmatrix}0 & 1 & -1 & 0\\ 0 & 0 & 1 & -1\end{pmatrix},\quad d = \begin{pmatrix}0\\0\end{pmatrix},\quad H_0: C\beta = d.
✍️ 检验统计量(C 是 m × p,满行秩)
F=(Cb−d)⊤[C(X⊤X)−1C⊤]−1(Cb−d)m σ^2 ∼H0 Fm, n−p.F = \frac{(Cb - d)^\top\big[C(X^\top X)^{-1}C^\top\big]^{-1}(Cb - d)}{m\,\hat\sigma^2} \ \overset{H_0}{\sim}\ F_{m,\,n-p}.

m = 1 时的推导(讲义给了,m 一般时不要求证明):b∼N(β,σ2(X⊤X)−1)b \sim N(\beta, \sigma^2(X^\top X)^{-1}),所以 c⊤b∼N(c⊤β,σ2c⊤(X⊤X)−1c)c^\top b \sim N(c^\top\beta, \sigma^2c^\top(X^\top X)^{-1}c)。标准化后平方:

(c⊤b−c⊤β)2σ2c⊤(X⊤X)−1c∼χ12,\frac{(c^\top b - c^\top\beta)^2}{\sigma^2 c^\top(X^\top X)^{-1}c} \sim \chi^2_1,

σ² 未知,要换成 σ^2\hat\sigma^2。用 F 分布的定义:两个独立的卡方各自除以自由度再相除,就是 F 分布。已知 (n−p)σ^2σ2∼χn−p2\dfrac{(n-p)\hat\sigma^2}{\sigma^2} \sim \chi^2_{n-p},并且 σ^2\hat\sigma^2 与 b 独立,所以

F=χ12/1χn−p2/(n−p)=(c⊤b−d)2σ2c⊤(X⊤X)−1c(n−p)σ^2σ2/(n−p)=(c⊤b−d)2σ^2 c⊤(X⊤X)−1c∼F1,n−p(H0 下 c⊤β=d).F = \frac{\chi^2_1 / 1}{\chi^2_{n-p}/(n-p)} = \frac{\dfrac{(c^\top b - d)^2}{\sigma^2 c^\top(X^\top X)^{-1}c}}{\dfrac{(n-p)\hat\sigma^2}{\sigma^2}\Big/(n-p)} = \frac{(c^\top b - d)^2}{\hat\sigma^2\, c^\top(X^\top X)^{-1}c} \sim F_{1,n-p}\quad(H_0\text{ 下 } c^\top\beta = d).

σ² 上下约掉了,所以能用数据算出来。m = 1 时 F=t2F = t^2,t=c⊤b−dσ^c⊤(X⊤X)−1ct = \dfrac{c^\top b - d}{\hat\sigma\sqrt{c^\top(X^\top X)^{-1}c}}。

Rch19 · 19.5:手算(不需要 car 包)
GLH <- function(model, C, d = rep(0, nrow(C))) {
  b <- coef(model); X <- model.matrix(model)
  s2 <- summary(model)$sigma^2
  m <- nrow(C); df2 <- df.residual(model)
  Cb_d <- C %*% b - d
  Fstat <- as.numeric(t(Cb_d) %*% solve(C %*% solve(t(X) %*% X) %*% t(C)) %*% Cb_d / (m * s2))
  c(F = Fstat, df1 = m, df2 = df2, p.value = 1 - pf(Fstat, m, df2))
}
C1 <- matrix(c(0, 0, 1, -1), nrow = 1)
GLH(m2, C1)
C2 <- matrix(c(0, 1, -1, 0,
               0, 0, 1, -1), nrow = 2, byrow = TRUE)
GLH(m2, C2)
Console 输出
           F          df1          df2      p.value
12.831310887  1.000000000 16.000000000  0.002491774
           F          df1          df2      p.value
 6.498718168  2.000000000 16.000000000  0.008591778

H0:μB=μCH_0: \mu_B = \mu_C:F = 12.83 ~ F1,16F_{1,16},p = 0.0025 → 拒绝,B 和 C 的平均用时不同(和讲义 linearHypothesis 的结果一致)。H0:μA=μB=μCH_0: \mu_A = \mu_B = \mu_C:F = 6.50 ~ F2,16F_{2,16},p = 0.0086 → 三种新格式不全相同(和 Lab 10 答案一致)。

💡 写 C 矩阵的诀窍
① 先写出 β 里参数的顺序(看 coef(model));② 每个等式移项成"… = 0",一个等式一行;③ 系数按参数顺序填,没出现的参数填 0。同一个假设在不同参数化下 C 不同:方法 1 的 β = (μ_a, A−a, B−a, C−a),"μ_A = μ_B" 变成 (A−a) − (B−a) = 0,即行 (0, 1, −1, 0)。结果完全一样:
Rch19 · 19.6 + 19.7
C2_m1 <- matrix(c(0, 1, -1, 0,
                  0, 0, 1, -1), nrow = 2, byrow = TRUE)
GLH(m1, C2_m1)
time$grp <- factor(ifelse(time$Format == "a", "a", "ABC"))
anova(lm(Time ~ grp, data = time), m1)
Console 输出
           F          df1          df2      p.value
 6.498718168  2.000000000 16.000000000  0.008591778
  Res.Df    RSS Df Sum of Sq      F   Pr(>F)
1     18 42.416
2     16 23.404  2    19.012 6.4987 0.008592 **

第二种算法:H0H_0 成立时 A、B、C 是同一个均值,相当于只有两组(a 和 ABC)的约束模型;约束模型 vs 全模型的嵌套 F 检验给出同一个 F = 6.4987。这说明一般线性假设就是第 7 章"万能 F 公式"的推广。

讲义第二个例子(Week 10 slide 92):H0:μB=μCH_0: \mu_B = \mu_C 且 μB+μa=μA\mu_B + \mu_a = \mu_A。第二个约束不是"两个均值之差",所以换参照组时 C 的写法变化更大,正好练手:

参数化β 的顺序μB=μC\mu_B = \mu_C 这一行μB+μa−μA=0\mu_B + \mu_a - \mu_A = 0 这一行
方法 2(无截距)(μa,μA,μB,μC)(\mu_a, \mu_A, \mu_B, \mu_C)(0, 0, 1, −1)(1, −1, 1, 0)
方法 1,参照组 B(μB, a−B, A−B, C−B)(\mu_B,\ a-B,\ A-B,\ C-B)(0, 0, 0, 1)(1, 1, −1, 0)

参照组 B 下第二行怎么来:μa=μB+(a−B)\mu_a = \mu_B + (a-B),μA=μB+(A−B)\mu_A = \mu_B + (A-B),代入得 μB+μa−μA=μB+(a−B)−(A−B)\mu_B + \mu_a - \mu_A = \mu_B + (a-B) - (A-B),所以截距 μB\mu_B 的系数是 1,不是 0。

Rch19 · 19.9
C3 <- matrix(c(0, 0, 1, -1,
               1, -1, 1, 0), nrow = 2, byrow = TRUE)
GLH(m2, C3)
mB <- lm(Time ~ relevel(Format, ref = "B"), data = time)
coef(mB)
C3_B <- matrix(c(0, 0, 0, 1,
                 1, 1, -1, 0), nrow = 2, byrow = TRUE)
GLH(mB, C3_B)
Console 输出
           F          df1          df2      p.value
5.733133e+01 2.000000e+00 1.600000e+01 5.055313e-08
                (Intercept) relevel(Format, ref = "B")a
                      11.24                       -2.88
relevel(Format, ref = "B")A relevel(Format, ref = "B")C
                      -1.64                       -2.74
           F          df1          df2      p.value
5.733133e+01 2.000000e+00 1.600000e+01 5.055313e-08

两种写法都得到 F = 57.33 ~ F2,16F_{2,16},p = 5.1e-08 → 拒绝 H0H_0,和讲义 linearHypothesis 的结果一样。(输出用科学计数法:5.733133e+01 = 57.33。)

⚠️ 考场上有没有 car 包不确定
讲义用 library(car); linearHypothesis(model, C)。考场电脑如果没装 car,就用上面的 GLH 函数(6 行,可以照讲义公式现场写出来),或者用"约束模型 vs 全模型"的 anova。三种方法结果相同。
✅ 本章检查清单
  • 能说出 yij=μ+ai+εijy_{ij} = \mu + a_i + \varepsilon_{ij} 为什么不满秩(第一列 = 其余列之和)
  • 方法 1 / 方法 2 的设计矩阵长什么样、参数是什么意思、R 怎么写(~ group vs ~ group - 1)
  • 能把文字假设写成 C 和 d,会算 F 和自由度 (m,n−p)(m, n-p)
  • 知道 m = 1 时 F = t²,能写出 m = 1 的推导思路

第 20 章 · Logistic 回归(可能考,优先级最低)

本章目标
先说清楚范围:本地 slides(Week 1–10)里没有 logistic 回归,但 Course Schedule 写到了讲义 "8.1 Hypothesis testing in logistic regression",Lab Week 10 Q6 有一道 iris 的 logistic 题,2019 年期末 Q4 也考过(Titanic)。Week 10 还没上完,最终讲不讲、考不考要看老师。时间不够就跳过本章;有时间的话,花 20 分钟会做 Lab 10 Q6 就够了。
配套脚本:R/ch20_logistic.R 原题:Lab Week 10 Q6。

20.1 模型

响应是 0/1(是/否)。线性模型会预测出 0–1 之外的值,所以改为对log odds 建线性模型:

P(yi=1)=pi,log⁡pi1−pi=xi⊤β⟺pi=exi⊤β1+exi⊤β.P(y_i = 1) = p_i,\qquad \log\frac{p_i}{1-p_i} = x_i^\top\beta \quad\Longleftrightarrow\quad p_i = \frac{e^{x_i^\top\beta}}{1 + e^{x_i^\top\beta}}.

p/(1−p)p/(1-p) 叫 odds(几率)。参数用最大似然估计,R 用 glm(..., family = binomial)。

20.2 Lab 10 Q6

📄 原题 · Lab Week 10 Q6
The 'iris' data set … we want to estimate the probability that a particular specimen is from the versicolor specie. (a) Estimate the probability that an iris with Petal.Length = 1.2cm and Petal.Width=2.2cm, Sepal.Length=2.2cm and Sepal.Width=0.5cm belongs to the versicolor specie. (b) Estimate the odds … (c) Test under a 5% level, whether the predictor Sepal.Length is a significant predictor or not. (d) Fit a logistic regression model with only Sepal.Width and Petal.Width as predictors, and test under a 5% level whether the full model is preferred over model with only Sepal.Width and Petal.Width as predictors.
Rch20 · 20.1 + 20.2
data(iris)
iris2 <- iris
iris2$versicolor <- (iris2$Species == "versicolor") * 1
m <- glm(versicolor ~ Sepal.Length + Sepal.Width + Petal.Length + Petal.Width,
         data = iris2, family = binomial)
summary(m)
new <- data.frame(Sepal.Length = 2.2, Sepal.Width = 0.5, Petal.Length = 1.2, Petal.Width = 2.2)
eta <- predict(m, new)
eta
exp(eta)
exp(eta) / (1 + exp(eta))
predict(m, new, type = "response")
Console 输出
Coefficients:
             Estimate Std. Error z value Pr(>|z|)
(Intercept)    7.3785     2.4993   2.952 0.003155 **
Sepal.Length  -0.2454     0.6496  -0.378 0.705634
Sepal.Width   -2.7966     0.7835  -3.569 0.000358 ***
Petal.Length   1.3136     0.6838   1.921 0.054713 .
Petal.Width   -2.7783     1.1731  -2.368 0.017868 *

    Null deviance: 190.95  on 149  degrees of freedom
Residual deviance: 145.07  on 145  degrees of freedom
        1
0.9044331
       1
2.470531
        1
0.7118597
        1
0.7118597

20.3 比较嵌套模型:偏差(deviance)之差 ~ χ²

Rch20 · 20.4
m1 <- glm(versicolor ~ Sepal.Width + Petal.Width, data = iris2, family = binomial)
anova(m1, m, test = "Chisq")
dev_diff <- deviance(m1) - deviance(m)
c(dev_diff, 1 - pchisq(dev_diff, df = 2))
Console 输出
  Resid. Df Resid. Dev Df Deviance Pr(>Chi)
1       147     151.67
2       145     145.07  2   6.5987  0.03691 *
[1] 6.5987244 0.0369067

(d):似然比检验,H0H_0:Sepal.Length 和 Petal.Length 的系数都是 0。统计量 = 两个模型 residual deviance 之差 = 6.60,H0H_0 下近似 χ22\chi^2_2(df = 多出来的参数个数),p = 0.037 < 0.05 → 全模型更好。这和线性模型里"嵌套 F 检验"的角色一样。

✅ 本章检查清单(可选)
  • 会写 log odds = x⊤βx^\top\beta,会从系数算 odds 和概率
  • glm(..., family = binomial);单个系数看 z 检验
  • 嵌套模型:anova(m_small, m_big, test = "Chisq"),deviance 之差 ~ χ²

第 11 章 · 理论题专项:证明模板 + 判断题库(Q1 的 25 分)

本章目标
Q1 = 5 道判断题(10 分)+ 证明题(15 分)。本章把课程里所有可能考的证明整理成固定模板,再给 30 多道判断题让你练理由。
配套脚本:R/ch11_theory_check.R(每个结论都用数字验证一遍,先看到它成立再证明)
考场上可以翻 tut_labs.pdf 里的 tutorial 答案和 Lecture Notes:这些证明都在里面,你练过就知道去哪找、怎么改。

11.1 答题策略(先看这个)

11.2 工具箱:所有证明只用这 12 条

#工具
T1E(aX+bY)=aEX+bEYE(aX+bY) = aEX + bEY;E(AY+c)=A EY+cE(AY + c) = A\,EY + c
T2Cov(U,V)=E[(U−EU)(V−EV)⊤]\mathrm{Cov}(U,V) = E[(U-EU)(V-EV)^\top];Cov(AY,BZ)=A Cov(Y,Z) B⊤\mathrm{Cov}(AY, BZ) = A\,\mathrm{Cov}(Y,Z)\,B^\top;Cov(AY)=A Cov(Y)A⊤\mathrm{Cov}(AY) = A\,\mathrm{Cov}(Y)A^\top
T3(AB)⊤=B⊤A⊤(AB)^\top = B^\top A^\top;(A−1)⊤=(A⊤)−1(A^{-1})^\top = (A^\top)^{-1};X⊤XX^\top X 对称
T4tr(AB)=tr(BA)\mathrm{tr}(AB) = \mathrm{tr}(BA);tr(A+B)=trA+trB\mathrm{tr}(A+B) = \mathrm{tr}A + \mathrm{tr}B;数的迹是它自己
T5模型:y=Xβ+εy = X\beta + \varepsilon,E(ε)=0E(\varepsilon) = 0,Cov(ε)=σ2I\mathrm{Cov}(\varepsilon) = \sigma^2 I ⇒ E(y)=XβE(y) = X\beta,Cov(y)=σ2I\mathrm{Cov}(y) = \sigma^2 I
T6b=(X⊤X)−1X⊤yb = (X^\top X)^{-1}X^\top y;H=X(X⊤X)−1X⊤H = X(X^\top X)^{-1}X^\top;y^=Hy\hat y = Hy;e=(I−H)ye = (I-H)y
T7H⊤=HH^\top = H,H2=HH^2 = H,HX=XHX = X,(I−H)X=0(I-H)X = 0,(I−H)⊤=I−H(I-H)^\top = I-H,(I−H)2=I−H(I-H)^2 = I-H
T8tr(H)=p\mathrm{tr}(H) = p,tr(I−H)=n−p\mathrm{tr}(I-H) = n-p
T9E(y⊤Ay)=tr(AV)+μ⊤AμE(y^\top Ay) = \mathrm{tr}(AV) + \mu^\top A\mu(formula sheet 第 4 页有;证明别的结论时可引用,题目要你证它时必须推导)
T10SLR:b1=∑ciyib_1 = \sum c_iy_i,ci=(xi−xˉ)/Sxxc_i = (x_i - \bar x)/S_{xx},∑ci=0\sum c_i = 0,∑cixi=1\sum c_ix_i = 1,∑ci2=1/Sxx\sum c_i^2 = 1/S_{xx}
T11ei,−i=ei/(1−hii)e_{i,-i} = e_i/(1-h_{ii}),Var(ei)=σ2(1−hii)\mathrm{Var}(e_i) = \sigma^2(1-h_{ii})
T12有截距时,1\mathbf 1(全 1 向量)是 X 的一列 ⇒ H1=1H\mathbf 1 = \mathbf 1,(I−H)1=0(I-H)\mathbf 1 = 0,1⊤e=0\mathbf 1^\top e = 0(残差和为 0)

11.3 证明模板库(按出现概率排序)

P1 · Cov(AY, BZ) = AΣBᵀ 2025 (a) 5 分
Cov(AY,BZ)=E[(AY−EAY)(BZ−EBZ)⊤]=E[A(Y−EY)(Z−EZ)⊤B⊤]=A E[(Y−EY)(Z−EZ)⊤] B⊤=AΣB⊤\mathrm{Cov}(AY,BZ) = E[(AY - E AY)(BZ - E BZ)^\top] = E[A(Y-EY)(Z-EZ)^\top B^\top] = A\,E[(Y-EY)(Z-EZ)^\top]\,B^\top = A\Sigma B^\top

用到:T1(E(AY)=A EYE(AY) = A\,EY)、T3(转置顺序)、常数矩阵提到期望外面。

P2 · Cov((I−H)y, b) = 0 2025 (b) 6 分 = Tutorial Week 5 Q10(a)

记 b=Cyb = Cy,C=(X⊤X)−1X⊤C = (X^\top X)^{-1}X^\top。由 P1(取 A=I−HA = I - H,B=CB = C,Y=Z=yY = Z = y)和 Cov(y)=σ2I\mathrm{Cov}(y) = \sigma^2 I:

Cov((I−H)y, Cy)=(I−H) σ2I C⊤=σ2(I−H)X(X⊤X)−1\mathrm{Cov}\big((I-H)y,\ Cy\big) = (I-H)\,\sigma^2 I\,C^\top = \sigma^2 (I-H)X(X^\top X)^{-1}

(因为 C⊤=X[(X⊤X)−1]⊤=X(X⊤X)−1C^\top = X[(X^\top X)^{-1}]^\top = X(X^\top X)^{-1}。)又 (I−H)X=X−HX=X−X=0(I-H)X = X - HX = X - X = 0,所以协方差是零矩阵。∎

意义:残差和估计量不相关(正态时独立)—— 这正是 σ^2\hat\sigma^2 和 b 独立、t 统计量服从 t 分布的原因。

P3 · RSS = yᵀ(I−H)y 2025 (c) 4 分
e=y−Xb=y−X(X⊤X)−1X⊤y=(I−H)ye = y - Xb = y - X(X^\top X)^{-1}X^\top y = (I-H)y RSS=(y−Xb)⊤(y−Xb)=e⊤e=y⊤(I−H)⊤(I−H)y=y⊤(I−H)y\text{RSS} = (y - Xb)^\top(y-Xb) = e^\top e = y^\top(I-H)^\top(I-H)y = y^\top(I-H)y

最后一步:I−HI-H 对称且幂等(T7)。

P4 · H 的性质 & tr(H) = p 2025 判断题 2

对称:H⊤=(X(X⊤X)−1X⊤)⊤=X[(X⊤X)−1]⊤X⊤=X(X⊤X)−1X⊤=HH^\top = (X(X^\top X)^{-1}X^\top)^\top = X[(X^\top X)^{-1}]^\top X^\top = X(X^\top X)^{-1}X^\top = H。
幂等:HH=X(X⊤X)−1X⊤X(X⊤X)−1X⊤=X(X⊤X)−1X⊤=HHH = X(X^\top X)^{-1}X^\top X(X^\top X)^{-1}X^\top = X(X^\top X)^{-1}X^\top = H。
迹:tr(H)=tr(X [(X⊤X)−1X⊤])=tr((X⊤X)−1X⊤X)=tr(Ip)=p\mathrm{tr}(H) = \mathrm{tr}\big(X\,[(X^\top X)^{-1}X^\top]\big) = \mathrm{tr}\big((X^\top X)^{-1}X^\top X\big) = \mathrm{tr}(I_p) = p。
推论:∑ihii=p\sum_i h_{ii} = p,平均杠杆 p/np/n。

P5 · E(b) = β,Cov(b) = σ²(XᵀX)⁻¹(Tutorial Week 3 Q5)
E(b)=(X⊤X)−1X⊤E(y)=(X⊤X)−1X⊤Xβ=βE(b) = (X^\top X)^{-1}X^\top E(y) = (X^\top X)^{-1}X^\top X\beta = \beta Cov(b)=C Cov(y) C⊤=(X⊤X)−1X⊤(σ2I)X(X⊤X)−1=σ2(X⊤X)−1\mathrm{Cov}(b) = C\,\mathrm{Cov}(y)\,C^\top = (X^\top X)^{-1}X^\top(\sigma^2 I)X(X^\top X)^{-1} = \sigma^2(X^\top X)^{-1}
P6 · 残差的性质(Tutorial Week 5 Q1)

(a) E(e)=(I−H)E(y)=(I−H)Xβ=0E(e) = (I-H)E(y) = (I-H)X\beta = 0。
(b) y^=Xb=X(X⊤X)−1X⊤y=Hy\hat y = Xb = X(X^\top X)^{-1}X^\top y = Hy;H 是 n×nn\times n,对称。
(d) Var(e)=(I−H) σ2I (I−H)⊤=σ2(I−H)2=σ2(I−H)\mathrm{Var}(e) = (I-H)\,\sigma^2 I\,(I-H)^\top = \sigma^2(I-H)^2 = \sigma^2(I-H)。
(e) Var(ei)=σ2(1−hii)\mathrm{Var}(e_i) = \sigma^2(1 - h_{ii}),Cov(ei,ej)=−σ2hij\mathrm{Cov}(e_i, e_j) = -\sigma^2 h_{ij},一般不为 0(残差是相关的)。
(f) e=(I−H)y=(I−H)(Xβ+ε)=(I−H)Xβ+(I−H)ε=(I−H)εe = (I-H)y = (I-H)(X\beta + \varepsilon) = (I-H)X\beta + (I-H)\varepsilon = (I-H)\varepsilon。

P7 · 二次型期望 E(yᵀAy) = tr(AV) + μᵀAμ(Tutorial Week 3 Q7)

y⊤Ay=∑i,jAijyiyjy^\top A y = \sum_{i,j} A_{ij}y_iy_j,且 E(yiyj)=Cov(yi,yj)+Eyi Eyj=Vij+μiμjE(y_iy_j) = \mathrm{Cov}(y_i,y_j) + E y_i\,E y_j = V_{ij} + \mu_i\mu_j,所以

E(y⊤Ay)=∑i,jAijVij+∑i,jAijμiμj=∑i,jAijVji+μ⊤Aμ=tr(AV)+μ⊤AμE(y^\top Ay) = \sum_{i,j}A_{ij}V_{ij} + \sum_{i,j}A_{ij}\mu_i\mu_j = \sum_{i,j} A_{ij}V_{ji} + \mu^\top A\mu = \mathrm{tr}(AV) + \mu^\top A\mu

(V 对称,Vij=VjiV_{ij} = V_{ji};∑i,jAijVji=∑i(AV)ii\sum_{i,j}A_{ij}V_{ji} = \sum_i (AV)_{ii}。)

另一种写法(更短):y⊤Ayy^\top Ay 是一个数,等于它的迹:E(y⊤Ay)=E tr(Ayy⊤)=tr(A E[yy⊤])=tr(A(V+μμ⊤))=tr(AV)+μ⊤AμE(y^\top Ay) = E\,\mathrm{tr}(Ayy^\top) = \mathrm{tr}(A\,E[yy^\top]) = \mathrm{tr}(A(V + \mu\mu^\top)) = \mathrm{tr}(AV) + \mu^\top A\mu。

P8 · σ̂² = yᵀ(I−H)y/(n−p) 是无偏的(Tutorial Week 5 Q10(b))

用 P7,A=I−HA = I-H,V=σ2IV = \sigma^2 I,μ=Xβ\mu = X\beta:

E[y⊤(I−H)y]=tr((I−H)σ2I)+β⊤X⊤(I−H)Xβ=σ2(n−p)+0E[y^\top(I-H)y] = \mathrm{tr}((I-H)\sigma^2 I) + \beta^\top X^\top (I-H)X\beta = \sigma^2(n-p) + 0

因为 tr(I−H)=n−p\mathrm{tr}(I-H) = n - p,(I−H)X=0(I-H)X = 0。所以 E(σ^2)=σ2E(\hat\sigma^2) = \sigma^2。∎ SLR 版本(Tutorial Week 3 Q1)就是 p=2p = 2。

P9 · 最小二乘估计(矩阵 & SLR)

矩阵:S(β)=(y−Xβ)⊤(y−Xβ)=y⊤y−2β⊤X⊤y+β⊤X⊤XβS(\beta) = (y - X\beta)^\top(y-X\beta) = y^\top y - 2\beta^\top X^\top y + \beta^\top X^\top X\beta。∂S/∂β=−2X⊤y+2X⊤Xβ=0\partial S/\partial\beta = -2X^\top y + 2X^\top X\beta = 0 ⇒ X⊤Xb=X⊤yX^\top X b = X^\top y ⇒ b=(X⊤X)−1X⊤yb = (X^\top X)^{-1}X^\top y(满秩时 X⊤XX^\top X 可逆)。

SLR:∂S/∂β0=−2∑(yi−β0−β1xi)=0\partial S/\partial\beta_0 = -2\sum(y_i - \beta_0 - \beta_1x_i) = 0,∂S/∂β1=−2∑xi(yi−β0−β1xi)=0\partial S/\partial\beta_1 = -2\sum x_i(y_i - \beta_0 - \beta_1x_i) = 0。第一式 ⇒ b0=yˉ−b1xˉb_0 = \bar y - b_1\bar x,代入第二式 ⇒ b1=Sxy/Sxxb_1 = S_{xy}/S_{xx}。

P10 · 极大似然估计 MLE(Tutorial Week 3 Q3、Week 5 Q2;老师特别提到 "use the method of maximum likelihood")

ε∼N(0,σ2I)\varepsilon \sim N(0, \sigma^2 I) ⇒ y∼N(Xβ,σ2I)y \sim N(X\beta, \sigma^2 I),似然函数

L(β,σ2)=∏i=1n12πσ2exp⁡ ⁣(−(yi−xi⊤β)22σ2)=(2πσ2)−n/2exp⁡ ⁣(−(y−Xβ)⊤(y−Xβ)2σ2)L(\beta,\sigma^2) = \prod_{i=1}^n \frac{1}{\sqrt{2\pi\sigma^2}}\exp\!\Big(-\frac{(y_i - x_i^\top\beta)^2}{2\sigma^2}\Big) = (2\pi\sigma^2)^{-n/2}\exp\!\Big(-\frac{(y-X\beta)^\top(y-X\beta)}{2\sigma^2}\Big) log⁡L=−n2log⁡(2π)−n2log⁡σ2−12σ2(y−Xβ)⊤(y−Xβ)\log L = -\frac n2\log(2\pi) - \frac n2\log\sigma^2 - \frac{1}{2\sigma^2}(y - X\beta)^\top(y-X\beta)
  1. 对 β:对任意固定的 σ²,最大化 log L ⇔ 最小化 (y−Xβ)⊤(y−Xβ)(y-X\beta)^\top(y-X\beta) ⇒ β^MLE=(X⊤X)−1X⊤y=b\hat\beta_{MLE} = (X^\top X)^{-1}X^\top y = b(就是最小二乘)。
  2. 对 σ²:∂log⁡L∂σ2=−n2σ2+SSres2σ4=0\dfrac{\partial \log L}{\partial\sigma^2} = -\dfrac{n}{2\sigma^2} + \dfrac{\text{SSres}}{2\sigma^4} = 0 ⇒ σ^MLE2=SSresn\hat\sigma^2_{MLE} = \dfrac{\text{SSres}}{n}。
  3. 它是有偏的:E(σ^MLE2)=n−pnσ2<σ2E(\hat\sigma^2_{MLE}) = \frac{n-p}{n}\sigma^2 < \sigma^2(由 P8)。

如果误差协方差是一般的 VV(Tutorial Week 5 Q2a),log L 里的二次型换成 (y−Xβ)⊤V−1(y−Xβ)(y-X\beta)^\top V^{-1}(y-X\beta),同样求导得 β^=(X⊤V−1X)−1X⊤V−1y\hat\beta = (X^\top V^{-1}X)^{-1}X^\top V^{-1}y;当 V=σ2IV = \sigma^2 I 时退化成 b。

P11 · SLR:Var(b₁)、Cov(ȳ, b₁) = 0、Var(b₀)、Cov(b₀, b₁)(Tutorial Week 1 Q5、Q6)

写 b1=∑ciyib_1 = \sum c_iy_i,ci=(xi−xˉ)/Sxxc_i = (x_i-\bar x)/S_{xx}(因为 Sxy=∑(xi−xˉ)yiS_{xy} = \sum(x_i - \bar x)y_i)。yiy_i 独立,Var(yi)=σ2\mathrm{Var}(y_i) = \sigma^2。

  • Var(b1)=σ2∑ci2=σ2⋅SxxSxx2=σ2Sxx\mathrm{Var}(b_1) = \sigma^2\sum c_i^2 = \sigma^2 \cdot \dfrac{S_{xx}}{S_{xx}^2} = \dfrac{\sigma^2}{S_{xx}}
  • Cov(yˉ,b1)=Cov(∑1nyi, ∑cjyj)=∑i1nciσ2=σ2n∑ci=0\mathrm{Cov}(\bar y, b_1) = \mathrm{Cov}\big(\sum \tfrac1n y_i,\ \sum c_jy_j\big) = \sum_i \tfrac1n c_i\sigma^2 = \tfrac{\sigma^2}{n}\sum c_i = 0
  • Var(b0)=Var(yˉ−xˉb1)=σ2n+xˉ2σ2Sxx−2xˉ⋅0=σ2(1n+xˉ2Sxx)\mathrm{Var}(b_0) = \mathrm{Var}(\bar y - \bar x b_1) = \dfrac{\sigma^2}{n} + \bar x^2\dfrac{\sigma^2}{S_{xx}} - 2\bar x\cdot 0 = \sigma^2\Big(\dfrac1n + \dfrac{\bar x^2}{S_{xx}}\Big)
  • Cov(b0,b1)=Cov(yˉ−xˉb1,b1)=0−xˉ Var(b1)=−σ2xˉSxx\mathrm{Cov}(b_0, b_1) = \mathrm{Cov}(\bar y - \bar xb_1, b_1) = 0 - \bar x\,\mathrm{Var}(b_1) = -\dfrac{\sigma^2\bar x}{S_{xx}}
P12 · SLR 杠杆公式 & 0 ≤ hᵢᵢ ≤ 1(Tutorial Week 5 Q11)

(a) SLR 里 X⊤X=(n∑xj∑xj∑xj2)X^\top X = \begin{pmatrix} n & \sum x_j\\ \sum x_j & \sum x_j^2\end{pmatrix},(X⊤X)−1=1nSxx(∑xj2−∑xj−∑xjn)(X^\top X)^{-1} = \dfrac{1}{nS_{xx}}\begin{pmatrix}\sum x_j^2 & -\sum x_j\\ -\sum x_j & n\end{pmatrix}。

hii=(1,xi)(X⊤X)−1(1xi)=∑xj2−2xi∑xj+nxi2nSxx=Sxx+nxˉ2−2nxixˉ+nxi2nSxx=1n+(xi−xˉ)2Sxxh_{ii} = (1, x_i)(X^\top X)^{-1}\binom{1}{x_i} = \frac{\sum x_j^2 - 2x_i\sum x_j + nx_i^2}{nS_{xx}} = \frac{S_{xx} + n\bar x^2 - 2nx_i\bar x + nx_i^2}{nS_{xx}} = \frac1n + \frac{(x_i-\bar x)^2}{S_{xx}}

(b) H=HH=H⊤HH = HH = H^\top H ⇒ hii=∑jhij2=hii2+∑j≠ihij2≥hii2h_{ii} = \sum_j h_{ij}^2 = h_{ii}^2 + \sum_{j\ne i}h_{ij}^2 \ge h_{ii}^2 ⇒ hii(1−hii)≥0h_{ii}(1 - h_{ii}) \ge 0 ⇒ 0≤hii≤10 \le h_{ii} \le 1。并且 hij2≤hii−hii2=hii(1−hii)≤1/4h_{ij}^2 \le h_{ii} - h_{ii}^2 = h_{ii}(1-h_{ii}) \le 1/4。

P13 · 基本恒等式 SStotal = SSreg + SSres(Tutorial Week 5 Q9;SLR 版 Week 1 讲义)

y−yˉ1=(y^−yˉ1)+(y−y^)y - \bar y\mathbf 1 = (\hat y - \bar y\mathbf 1) + (y - \hat y)。只需证交叉项为 0:

(y^−yˉ1)⊤(y−y^)=(Hy−yˉ1)⊤(I−H)y=y⊤H(I−H)y−yˉ 1⊤(I−H)y=0−0(\hat y - \bar y\mathbf 1)^\top(y - \hat y) = (Hy - \bar y\mathbf 1)^\top(I-H)y = y^\top H(I-H)y - \bar y\,\mathbf 1^\top(I-H)y = 0 - 0

因为 H(I−H)=H−H2=0H(I-H) = H - H^2 = 0,且有截距时 (I−H)1=0(I-H)\mathbf 1 = 0(T12)。矩阵写法:∥(I−1nJ)y∥2=∥(H−1nJ)y∥2+∥(I−H)y∥2\|(I - \tfrac1n J)y\|^2 = \|(H - \tfrac1n J)y\|^2 + \|(I-H)y\|^2,J 是全 1 矩阵。

P14 · SSreg = S²ₓᵧ / Sₓₓ(Tutorial Week 1 Q4)

y^i−yˉ=b0+b1xi−yˉ=(yˉ−b1xˉ)+b1xi−yˉ=b1(xi−xˉ)\hat y_i - \bar y = b_0 + b_1x_i - \bar y = (\bar y - b_1\bar x) + b_1x_i - \bar y = b_1(x_i - \bar x),所以 SSreg=b12∑(xi−xˉ)2=b12Sxx=Sxy2Sxx\text{SSreg} = b_1^2\sum(x_i-\bar x)^2 = b_1^2S_{xx} = \dfrac{S_{xy}^2}{S_{xx}}。

P15 · PRESS 相关:标准化 PRESS 残差、R²pred < R²(2025 判断题 3、Tutorial Week 5 Q12)

Var(ei,−i)=Var(ei)/(1−hii)2=σ2/(1−hii)\mathrm{Var}(e_{i,-i}) = \mathrm{Var}(e_i)/(1-h_{ii})^2 = \sigma^2/(1-h_{ii}) ⇒ 标准化 PRESS 残差 =ei/(1−hii)σ/1−hii=eiσ1−hii= \dfrac{e_i/(1-h_{ii})}{\sigma/\sqrt{1-h_{ii}}} = \dfrac{e_i}{\sigma\sqrt{1-h_{ii}}} = 标准化残差。

0<1−hii<10 < 1 - h_{ii} < 1(hii>0h_{ii} > 0)⇒ ei,−i2=ei2/(1−hii)2≥ei2e_{i,-i}^2 = e_i^2/(1-h_{ii})^2 \ge e_i^2 ⇒ PRESS ≥ SSres(有 ei≠0e_i \ne 0 就严格大于)⇒ Rpred2=1−PRESS/SStotal<1−SSres/SStotal=R2R^2_{pred} = 1 - \text{PRESS}/\text{SStotal} < 1 - \text{SSres}/\text{SStotal} = R^2。

P16 · 多元正态的二次型 & 线性组合(Tutorial Week 5 Q3–Q6)

y∼N(μ,V)y \sim N(\mu, V) ⇒ Ay∼N(Aμ,AVA⊤)Ay \sim N(A\mu, AVA^\top)(第 5 章例题)。Z=V−1/2(y−μ)∼N(0,In)Z = V^{-1/2}(y - \mu) \sim N(0, I_n),所以 (y−μ)⊤V−1(y−μ)=Z⊤Z=∑Zi2∼χn2(y-\mu)^\top V^{-1}(y-\mu) = Z^\top Z = \sum Z_i^2 \sim \chi^2_n。

P17 · Gauss–Markov 定理(Tutorial Week 5 Q7 陈述)

Statement:In the linear model y=Xβ+εy = X\beta + \varepsilon with E(ε)=0E(\varepsilon) = 0 and Cov(ε)=σ2I\mathrm{Cov}(\varepsilon) = \sigma^2 I, the least squares estimator b=(X⊤X)−1X⊤yb = (X^\top X)^{-1}X^\top y is the best linear unbiased estimator (BLUE) of β: for any other linear unbiased estimator b~=Ay\tilde b = Ay, Var(c⊤b)≤Var(c⊤b~)\mathrm{Var}(c^\top b) \le \mathrm{Var}(c^\top\tilde b) for all c.
注意:不需要正态假设。

补充模板(tutorial 里出现过的其他证明)

P18 · Gauss–Markov 定理的证明(Tutorial Week 5 Q7(c);slides Week 4 开头)

任取另一个线性估计 b~=Ay\tilde b = Ay,写成 A=(X⊤X)−1X⊤+BA = (X^\top X)^{-1}X^\top + B。

  1. 无偏性逼出 BX = 0:E(b~)=AXβ=β+BXβE(\tilde b) = AX\beta = \beta + BX\beta。要对所有 β 都等于 β,必须 BX=0BX = 0。
  2. 算方差:Cov(b~)=σ2AA⊤=σ2[(X⊤X)−1X⊤+B][X(X⊤X)−1+B⊤]=σ2(X⊤X)−1+σ2BB⊤\mathrm{Cov}(\tilde b) = \sigma^2AA^\top = \sigma^2\big[(X^\top X)^{-1}X^\top + B\big]\big[X(X^\top X)^{-1} + B^\top\big] = \sigma^2(X^\top X)^{-1} + \sigma^2BB^\top(交叉项含 BX=0BX = 0 或 X⊤B⊤=0X^\top B^\top = 0,消失)。
  3. 比较:对任意向量 c,Var(c⊤b~)−Var(c⊤b)=σ2c⊤BB⊤c=σ2∥B⊤c∥2≥0\mathrm{Var}(c^\top\tilde b) - \mathrm{Var}(c^\top b) = \sigma^2c^\top BB^\top c = \sigma^2\|B^\top c\|^2 \ge 0。所以 b 的方差最小:b 是 BLUE。∎

(BB⊤BB^\top 半正定:Tutorial Week 3 Q12,x⊤BB⊤x=∥B⊤x∥2≥0x^\top BB^\top x = \|B^\top x\|^2 \ge 0。)

P19 · SLR:σ̂² = (Syy − b₁²Sxx)/(n−2) 且无偏(Tutorial Week 3 Q1)

(a) yi−b0−b1xi=(yi−yˉ)−b1(xi−xˉ)y_i - b_0 - b_1x_i = (y_i - \bar y) - b_1(x_i - \bar x)(代入 b0=yˉ−b1xˉb_0 = \bar y - b_1\bar x),平方求和:

∑(yi−b0−b1xi)2=Syy−2b1Sxy+b12Sxx=Syy−b12Sxx(因为 Sxy=b1Sxx)\sum(y_i - b_0 - b_1x_i)^2 = S_{yy} - 2b_1S_{xy} + b_1^2S_{xx} = S_{yy} - b_1^2S_{xx}\quad(\text{因为 } S_{xy} = b_1S_{xx})

(b) yi−yˉ=β1(xi−xˉ)+(εi−εˉ)y_i - \bar y = \beta_1(x_i - \bar x) + (\varepsilon_i - \bar\varepsilon),所以 E(Syy)=β12Sxx+(n−1)σ2E(S_{yy}) = \beta_1^2S_{xx} + (n-1)\sigma^2。又 E(b12)=Var(b1)+[Eb1]2=σ2/Sxx+β12E(b_1^2) = \mathrm{Var}(b_1) + [E b_1]^2 = \sigma^2/S_{xx} + \beta_1^2,所以 E(b12Sxx)=σ2+β12SxxE(b_1^2S_{xx}) = \sigma^2 + \beta_1^2S_{xx}。相减:E(Syy−b12Sxx)=(n−2)σ2E(S_{yy} - b_1^2S_{xx}) = (n-2)\sigma^2,除以 n−2n-2 得无偏。∎

P20 · E[SSreg]、E[SSres]、E[SStotal](Tutorial Week 3 Q2)
  1. χm2\chi^2_m 是 m 个标准正态平方和 ⇒ E(χm2)=m⋅E(Z2)=mE(\chi^2_m) = m \cdot E(Z^2) = m。
  2. H0:β1=0H_0: \beta_1 = 0 下 SSreg/σ2∼χ12\text{SSreg}/\sigma^2 \sim \chi^2_1 ⇒ E(SSreg)=σ2E(\text{SSreg}) = \sigma^2。
  3. 一般情况:SSreg=b12Sxx\text{SSreg} = b_1^2S_{xx}(P14),E(SSreg)=Sxx(σ2/Sxx+β12)=σ2+β12SxxE(\text{SSreg}) = S_{xx}\big(\sigma^2/S_{xx} + \beta_1^2\big) = \sigma^2 + \beta_1^2S_{xx}。H0 不成立时更大(多了 β12Sxx>0\beta_1^2S_{xx} > 0)—— 这就是 F = MSreg/MSres 大时拒绝 H0 的原因。
  4. E(SSres)=(n−2)σ2E(\text{SSres}) = (n-2)\sigma^2(P19);E(SStotal)=E(SSreg)+E(SSres)=(n−1)σ2+β12SxxE(\text{SStotal}) = E(\text{SSreg}) + E(\text{SSres}) = (n-1)\sigma^2 + \beta_1^2S_{xx};H0 下为 (n−1)σ2(n-1)\sigma^2。
P21 · mean shift 离群点模型(Tutorial Week 5 Q13)

第 j 个误差均值为 Δ:E(y)=Xβ+ΔujE(y) = X\beta + \Delta u_j(uju_j 是第 j 个位置为 1、其余为 0 的向量)。

E(e)=(I−H)E(y)=(I−H)Xβ+Δ(I−H)uj=Δ(I−H)uj ⇒ E(ej)=Δ(1−hjj)E(e) = (I-H)E(y) = (I-H)X\beta + \Delta(I-H)u_j = \Delta(I-H)u_j \ \Rightarrow\ E(e_j) = \Delta(1 - h_{jj}) E(ej,−j)=E(ej)1−hjj=ΔE(e_{j,-j}) = \frac{E(e_j)}{1-h_{jj}} = \Delta

结论:普通残差把偏移"缩水"了 (1−hjj)(1-h_{jj}) 倍,PRESS 残差不缩水 —— 所以找离群点要用 PRESS/学生化残差。

P22 · 有截距时 hii ≥ 1/n(Tutorial Week 5 Q11(c))

记 J=11⊤J = \mathbf 1\mathbf 1^\top(全 1 矩阵)。有截距 ⇒ H1=1H\mathbf 1 = \mathbf 1 ⇒ HJ=JH=JHJ = JH = J;又 J2=nJJ^2 = nJ。令 M=H−1nJM = H - \frac1nJ:

M2=H−1nHJ−1nJH+1n2J2=H−1nJ−1nJ+1nJ=MM^2 = H - \tfrac1nHJ - \tfrac1nJH + \tfrac1{n^2}J^2 = H - \tfrac1nJ - \tfrac1nJ + \tfrac1nJ = M

M 对称幂等,同 P12(b) 的论证,它的对角线 mii=∑jmij2≥0m_{ii} = \sum_j m_{ij}^2 \ge 0,即 hii−1n≥0h_{ii} - \frac1n \ge 0。∎

P23 · 样本均值与方差(Tutorial Week 1 Q7(b)(c))

(b)

∑(Yi−Yˉ)2=∑[(Yi−μ)−(Yˉ−μ)]2=∑(Yi−μ)2−2(Yˉ−μ)∑(Yi−μ)+n(Yˉ−μ)2=∑(Yi−μ)2−n(Yˉ−μ)2\begin{aligned}\textstyle\sum(Y_i-\bar Y)^2 &= \textstyle\sum\big[(Y_i - \mu) - (\bar Y - \mu)\big]^2 = \sum(Y_i-\mu)^2 - 2(\bar Y-\mu)\sum(Y_i - \mu) + n(\bar Y-\mu)^2\\ &= \textstyle\sum(Y_i-\mu)^2 - n(\bar Y - \mu)^2\end{aligned}

(因为 ∑(Yi−μ)=n(Yˉ−μ)\sum(Y_i - \mu) = n(\bar Y - \mu)),除以 n−1n-1 即得。

(c) 移项:∑(Yi−μ)2/σ2⏟χn2=(n−1)S2/σ2⏟?+n(Yˉ−μ)2/σ2⏟χ12\underbrace{\textstyle\sum(Y_i-\mu)^2/\sigma^2}_{\chi^2_n} = \underbrace{(n-1)S^2/\sigma^2}_{?} + \underbrace{n(\bar Y-\mu)^2/\sigma^2}_{\chi^2_1}。Yˉ\bar Y 与 (Y1−Yˉ,…,Yn−Yˉ)(Y_1 - \bar Y, \dots, Y_n - \bar Y) 联合正态且不相关 ⇒ 独立,所以右边两项独立;用矩母函数(左边的 MGF = 右边两项 MGF 的乘积)⇒ (n−1)S2/σ2∼χn−12(n-1)S^2/\sigma^2 \sim \chi^2_{n-1},且与 Yˉ\bar Y 独立。

P24 · 具体的二次型分布(Tutorial Week 5 Q4–Q5,数字题)

Q4:Y1∼N(0,1)Y_1 \sim N(0,1),Y2∼N(3,4)Y_2 \sim N(3,4) 独立。(a) Y12∼χ12Y_1^2 \sim \chi^2_1。(b) y=(Y1,(Y2−3)/2)⊤y = (Y_1, (Y_2-3)/2)^\top 两个分量都是独立 N(0,1),y⊤y=Y12+(Y2−3)2/4∼χ22y^\top y = Y_1^2 + (Y_2-3)^2/4 \sim \chi^2_2。(c) y=(Y1,Y2−3)⊤∼N(0,V)y = (Y_1, Y_2 - 3)^\top \sim N(0, V),V=diag(1,4)V = \mathrm{diag}(1, 4),y⊤V−1y=Y12+(Y2−3)2/4∼χ22y^\top V^{-1}y = Y_1^2 + (Y_2-3)^2/4 \sim \chi^2_2。

Q5:μ=(2,3)⊤\mu = (2,3)^\top,V=(4119)V = \begin{pmatrix}4&1\\1&9\end{pmatrix},V−1=135(9−1−14)V^{-1} = \frac{1}{35}\begin{pmatrix}9&-1\\-1&4\end{pmatrix},

(y−μ)⊤V−1(y−μ)=9(y1−2)2−2(y1−2)(y2−3)+4(y2−3)235∼χ22(y-\mu)^\top V^{-1}(y-\mu) = \frac{9(y_1-2)^2 - 2(y_1-2)(y_2-3) + 4(y_2-3)^2}{35} \sim \chi^2_2
P25 · 重新参数化的 MLE、共同斜率、投影(Tutorial Week 3 Q3、Q4、Q8–Q11,了解即可)

Q3:yi=α+βxiy_i = \alpha + \beta x_i 与 yi=γ+δ(xi−xˉ)y_i = \gamma + \delta(x_i - \bar x)。正态下 MLE = 最小二乘:δ^=Sxy/Sxx=β^\hat\delta = S_{xy}/S_{xx} = \hat\beta;γ^=yˉ=α^+β^xˉ\hat\gamma = \bar y = \hat\alpha + \hat\beta\bar x。Cov(γ^,δ^)=Cov(yˉ,b1)=0\mathrm{Cov}(\hat\gamma, \hat\delta) = \mathrm{Cov}(\bar y, b_1) = 0(P11),联合正态 ⇒ 独立。

Q4(两组共同斜率、不同截距):最小化 ∑组1(yi−β0(1)−β1xi)2+∑组2(yi−β0(2)−β1xi)2\sum_{\text{组1}}(y_i - \beta_0^{(1)} - \beta_1x_i)^2 + \sum_{\text{组2}}(y_i - \beta_0^{(2)} - \beta_1x_i)^2。对两个截距求导得 β0(g)=yˉg−β1xˉg\beta_0^{(g)} = \bar y_g - \beta_1\bar x_g,代回对 β₁ 求导得 b1=∑xiyi−n1xˉ1yˉ1−n2xˉ2yˉ2∑xi2−n1xˉ12−n2xˉ22b_1 = \dfrac{\sum x_iy_i - n_1\bar x_1\bar y_1 - n_2\bar x_2\bar y_2}{\sum x_i^2 - n_1\bar x_1^2 - n_2\bar x_2^2}。

Q8–Q11:y=(7,0,2)⊤y = (7,0,2)^\top,v1=(1,1,1)⊤v_1 = (1,1,1)^\top,v2=(2,−1,−1)⊤v_2 = (2,-1,-1)^\top 正交。c1=y⊤v1/∥v1∥2=9/3=3c_1 = y^\top v_1/\|v_1\|^2 = 9/3 = 3,c2=y⊤v2/∥v2∥2=12/6=2c_2 = y^\top v_2/\|v_2\|^2 = 12/6 = 2,投影 y^=3v1+2v2=(7,1,1)⊤\hat y = 3v_1 + 2v_2 = (7, 1, 1)^\top;检查 y−y^=(0,−1,1)⊤y - \hat y = (0,-1,1)^\top 与 v1,v2v_1, v_2 都垂直 ✓。这就是"最小二乘 = 投影"(第 5 章演示)。

🖥️ RStudio 跟做:ch11_theory_check.R
脚本把 P2、P3、P4、P6、P7、P8、P13、P15、P11 都用数字验证了一遍。比如 P2:模拟 2 万次,残差和 b 的样本协方差全都接近 0;P8:RSS/(n−p) 的平均值 ≈ σ² = 2.25,而 RSS/n 的平均只有 1.69(有偏)。
Rch11 · 证明 7(要先运行脚本开头到证明 5,才有 rss、n、p)

mean(rss / (n - p))     # 无偏估计的平均:约等于 sigma^2 = 2.25

mean(rss / n)           # MLE 的平均:偏小
Console 输出
[1] 2.24836
[1] 1.68627

11.4 判断题题库(先自己判断,再点按钮看理由)

前 5 道是 2025 年原题,其余是根据课程内容出的同类题(共 39 道)。

1. [2025] It is possible to construct an example dataset for a simple linear model where all leverages hii = 1, i = 1, …, n. (hint: consider n = 2)
n = 2、两个不同的 x:X 是 2×2 可逆矩阵,H=X(X⊤X)−1X⊤=XX−1(X⊤)−1X⊤=I2H = X(X^\top X)^{-1}X^\top = XX^{-1}(X^\top)^{-1}X^\top = I_2,所以 h11=h22=1h_{11} = h_{22} = 1。
2. [2025] The trace of the hat matrix is equal to p, the number of regression parameters β in the general linear model, i.e. tr(H) = p.
tr(H)=tr((X⊤X)−1X⊤X)=tr(Ip)=p\mathrm{tr}(H) = \mathrm{tr}((X^\top X)^{-1}X^\top X) = \mathrm{tr}(I_p) = p(迹的循环性)。
3. [2025] Standardised PRESS residuals (i.e. ei,−i divided by their standard deviation) are identical to standardised ordinary residuals.
ei,−i=ei/(1−hii)e_{i,-i} = e_i/(1-h_{ii}),Var(ei,−i)=σ2/(1−hii)\mathrm{Var}(e_{i,-i}) = \sigma^2/(1-h_{ii}),相除得 ei/(σ1−hii)e_i/(\sigma\sqrt{1-h_{ii}})。
4. [2025] The sum of the sequential sums of squares in an ANOVA table for the general linear model is equal to the regression sum of squares.
R(β1∣β0)+R(β2∣β0,β1)+⋯=R(β1,…,βk∣β0)=SSregR(\beta_1|\beta_0) + R(\beta_2|\beta_0,\beta_1) + \cdots = R(\beta_1,\dots,\beta_k|\beta_0) = \text{SSreg}(按定义逐项相加,中间项抵消)。
5. [2025] The forward-selection and backward-selection algorithms are not guaranteed to find the best predictive model.
路径是贪心、确定的,只检查了所有子集中的一小部分,不保证找到全局最优(两者甚至可能得到不同模型)。
6. The leverage hii depends on the response value yi.
hii=xi⊤(X⊤X)−1xih_{ii} = x_i^\top(X^\top X)^{-1}x_i 只依赖于 X。
7. In a linear model with an intercept, the residuals sum to zero.
正规方程 X⊤e=0X^\top e = 0,X 的第一列是 1\mathbf 1 ⇒ 1⊤e=∑ei=0\mathbf 1^\top e = \sum e_i = 0。没有截距时不一定成立。
8. The residuals e1, …, en are uncorrelated with common variance σ².
Var(e)=σ2(I−H)\mathrm{Var}(e) = \sigma^2(I-H):Var(ei)=σ2(1−hii)\mathrm{Var}(e_i) = \sigma^2(1-h_{ii}) 各不相同,Cov(ei,ej)=−σ2hij≠0\mathrm{Cov}(e_i,e_j) = -\sigma^2h_{ij} \ne 0。
9. Adding a predictor to a linear model can never decrease R².
加变量后 SSres 不会增加(最小化的范围更大了),SStotal 不变,所以 R2=1−SSres/SStotalR^2 = 1 - \text{SSres}/\text{SStotal} 不会减小。
10. Adding a predictor to a linear model can never decrease the adjusted R².
Rˉ2=1−n−1n−p(1−R2)\bar R^2 = 1 - \frac{n-1}{n-p}(1-R^2),p 增大会增加惩罚;加一个没用的变量 Rˉ2\bar R^2 可能下降。
11. The adjusted R² can be negative.
当 R2<(p−1)/(n−1)R^2 < (p-1)/(n-1) 时 Rˉ2<0\bar R^2 < 0(Lab 7 Q1 输出里就有负值)。
12. The PRESS statistic always decreases when a predictor is added to the model.
PRESS 衡量样本外预测误差,加入无用变量会增大方差,PRESS 可能变大(这正是它能用来选模型的原因)。
13. The PRESS statistic is always greater than or equal to the residual sum of squares.
∣ei,−i∣=∣ei∣/(1−hii)≥∣ei∣|e_{i,-i}| = |e_i|/(1-h_{ii}) \ge |e_i|,因为 0<1−hii≤10 < 1-h_{ii} \le 1。
14. The sequential sums of squares do not depend on the order in which predictors are entered into the model.
每一行是"在前面变量存在时"的增量,换顺序会变(讲义 risk 例子:Div 排第 1 时 18.43,排第 4 时 9.74)。只有总和不变。
15. If the overall F-test is significant, then at least one of the partial t-tests must be significant.
Lab 4 Q4:F 检验 p = 0.0157,但三个 partial t 的 p 都 > 0.1。预测变量信息重叠时会出现这种情况。
16. In simple linear regression, the F statistic in the ANOVA table equals the square of the t statistic for testing H0: β₁ = 0.
F=SSreg/σ^2=b12Sxx/σ^2=(b1/se(b1))2=t2F = \text{SSreg}/\hat\sigma^2 = b_1^2S_{xx}/\hat\sigma^2 = (b_1/\mathrm{se}(b_1))^2 = t^2,且 tn−22∼F1,n−2t_{n-2}^2 \sim F_{1,n-2}。
17. For the same x₀ and confidence level, the prediction interval for a new response is always wider than the confidence interval for the mean response.
PI 的标准误是 σ^1+x0⊤(X⊤X)−1x0\hat\sigma\sqrt{1 + x_0^\top(X^\top X)^{-1}x_0},比 CI 的 σ^x0⊤(X⊤X)−1x0\hat\sigma\sqrt{x_0^\top(X^\top X)^{-1}x_0} 多了"1"(新观测自身的误差)。
18. As the sample size n → ∞, the width of the prediction interval tends to zero.
x0⊤(X⊤X)−1x0→0x_0^\top(X^\top X)^{-1}x_0 \to 0,但"1"还在,PI 宽度趋于 2zα/2σ2z_{\alpha/2}\sigma,不趋于 0(CI 的宽度才趋于 0)。
19. The maximum likelihood estimator of σ² in the normal linear model is unbiased.
σ^MLE2=SSres/n\hat\sigma^2_{MLE} = \text{SSres}/n,E=n−pnσ2<σ2E = \frac{n-p}{n}\sigma^2 < \sigma^2。无偏的是 SSres/(n−p)\text{SSres}/(n-p)。
20. Under normal errors, the maximum likelihood estimator of β equals the least squares estimator.
log L 中只有 −(y−Xβ)⊤(y−Xβ)/(2σ2)-(y-X\beta)^\top(y-X\beta)/(2\sigma^2) 含 β,最大化它 ⇔ 最小化残差平方和。
21. The Gauss–Markov theorem requires the errors to be normally distributed.
只需要 E(ε)=0E(\varepsilon) = 0、Cov(ε)=σ2I\mathrm{Cov}(\varepsilon) = \sigma^2 I(不相关、等方差)。
22. The hat matrix H is symmetric and idempotent.
见 P4:H⊤=HH^\top = H,HH=HHH = H。
23. The hat matrix H is invertible whenever X has full column rank.
H 幂等,特征值只有 0 和 1,秩 = tr(H) = p;只有 n = p 时 H = I 才可逆。p < n 时不可逆。
24. For Mallows' Cp computed relative to the full model, the full model always has Cp = p.
Cp=p+(σ^p2−σ^F2)(n−p)/σ^F2C_p = p + (\hat\sigma^2_p - \hat\sigma^2_F)(n-p)/\hat\sigma^2_F,全模型 σ^p2=σ^F2\hat\sigma^2_p = \hat\sigma^2_F,第二项为 0。
25. Under the model assumptions, the externally studentized residual ti follows a t distribution with n − p degrees of freedom.
是 tn−p−1t_{n-p-1}:σ^(−i)\hat\sigma_{(-i)} 是用 n−1 个点估计的。
26. Points with high leverage always have large residuals.
相反:Var(ei)=σ2(1−hii)\mathrm{Var}(e_i) = \sigma^2(1-h_{ii}),高杠杆点把拟合线拉向自己,残差往往很小。
27. The partial t-test for βj tests whether xj is useful in the presence of all the other predictors in the model.
partial t 的原假设是"其他变量都在时 βj = 0";它等价于去掉 xj 的模型 vs 全模型的 F 检验(F = t²)。
28. Forward selection and backward elimination always arrive at the same final model.
它们走不同的路径、检查不同的模型子集,结果可能不同。
29. After choosing a model by stepwise selection, the p-values reported in summary() for the selected model are valid.
同一份数据既用于选模型又用于推断(post-selection inference),显著性会被高估,p 值无效。
30. If each of k confidence intervals is constructed at level 1 − α/k, then the probability that all k intervals simultaneously cover their parameters is at least 1 − α.
Bonferroni 不等式:P(至少一个不覆盖)≤∑jα/k=αP(\text{至少一个不覆盖}) \le \sum_j \alpha/k = \alpha。
31. In the general linear model, Cov(e, ŷ) = 0.
Cov((I−H)y,Hy)=(I−H)σ2IH⊤=σ2(H−H2)=0\mathrm{Cov}((I-H)y, Hy) = (I-H)\sigma^2 I H^\top = \sigma^2(H - H^2) = 0。
32. With an intercept in the model, every leverage satisfies 1/n ≤ hii ≤ 1.
Tutorial Week 5 Q11(c);SLR 里 hii=1/n+(xi−xˉ)2/Sxx≥1/nh_{ii} = 1/n + (x_i-\bar x)^2/S_{xx} \ge 1/n。
33. A 95% confidence interval for β₁ means there is a 95% probability that β₁ lies in the computed interval.
β₁ 是固定的。95% 指的是方法:反复抽样时约 95% 的区间会覆盖 β₁(第 2 章演示)。
34. In the general linear model, the overall F statistic follows Fp−1, n−p under H0: β₁ = ⋯ = βk = 0.
F=SSreg/(p−1)SSres/(n−p)F = \frac{\text{SSreg}/(p-1)}{\text{SSres}/(n-p)},分子分母分别是独立的 χp−12/(p−1)\chi^2_{p-1}/(p-1) 和 χn−p2/(n−p)\chi^2_{n-p}/(n-p)(乘以 σ²)。
35. The Gauss–Markov theorem says the least squares estimator has the smallest variance among all unbiased estimators of β.
只是在线性无偏估计(形如 Ay)中方差最小(BLUE)。非线性的无偏估计不在比较范围内。
36. In simple linear regression, E(SSreg) is larger when β₁ ≠ 0 than when β₁ = 0.
E(SSreg)=σ2+β12SxxE(\text{SSreg}) = \sigma^2 + \beta_1^2S_{xx}(P20):β₁ ≠ 0 时多出 β12Sxx>0\beta_1^2S_{xx} > 0。
37. Under the mean shift outlier model E(εj) = Δ, the expected PRESS residual for observation j is Δ, whereas the expected ordinary residual is (1 − hjj)Δ.
P21:E(e)=Δ(I−H)ujE(e) = \Delta(I-H)u_j ⇒ E(ej)=(1−hjj)ΔE(e_j) = (1-h_{jj})\Delta;E(ej,−j)=E(ej)/(1−hjj)=ΔE(e_{j,-j}) = E(e_j)/(1-h_{jj}) = \Delta。
38. In the general linear model, Cov(ei, ej) = −σ²hij for i ≠ j.
Var(e)=σ2(I−H)\mathrm{Var}(e) = \sigma^2(I-H),非对角元素是 −σ2hij-\sigma^2h_{ij}。
39. In simple linear regression, b₀ and b₁ are always uncorrelated.
Cov(b0,b1)=−σ2xˉ/Sxx\mathrm{Cov}(b_0, b_1) = -\sigma^2\bar x/S_{xx},只有 xˉ=0\bar x = 0 时才不相关(P11)。不相关的是 yˉ\bar y 和 b1b_1。
✅ 本章检查清单
  • P1、P2、P3 能不看答案默写(2025 原题,同类题概率极高)
  • P4–P8、P10 能写出主要步骤;P18(Gauss–Markov)、P19–P21 至少会写框架
  • 判断题错的那几道,把理由抄一遍

第 21 章 · 期末证明题总表 + 新增判断题

本章目标
期末 4–5 道题里有 2–3 道手写证明题(2023 有 2 道:Q3、Q4;2021 有 3 道:Q4、Q5、Q6)。本章先给一张"证明题地图",说清楚近几年考过什么、模板在哪一章;然后把还没讲过的三道 Week 1–5 期末原题(2021 Q4、2020 Q1、2020 Q3)完整写出来;最后是 Week 7–10 新内容的判断题。Week 1–7 的证明模板和 39 道判断题见第 11 章。

21.1 证明题地图

题型出现过模板在优先级
Cook's D、y^i−y^i,−i\hat y_i - \hat y_{i,-i}、DFFITS 捷径公式2014 Q7、2020 Q4、2021 Q6、2023 Q4第 15 章 P15-1 ~ P15-5★★★
无截距模型的 WLS:推导、期望方差、MLE、乘 √r 变换2021 Q5、2023 Q3第 17 章★★★
b=β+Sεb = \beta + S\varepsilon,Var(b),RSS = ε'(I−XS)ε,σ̂² 无偏2021 Q4本章 21.2★★★
(中心化)SLR:推导 b₀ b₁、无偏、不相关、χ² 分布2020 Q1本章 21.3,第 3、11 章★★
SSreg 二次型:X⊤JXX^\top JX、tr(H−J/n)\mathrm{tr}(H - J/n)、E(SSreg)=σ2+β12SxxE(\text{SSreg}) = \sigma^2 + \beta_1^2S_{xx}2020 Q3本章 21.4★★
GLS = MLE,分布 N(β,(X⊤V−1X)−1)N(\beta, (X^\top V^{-1}X)^{-1})Tutorial 9 Q1–Q2第 17 章 17.2★★
Taylor 展开验证方差稳定变换Tutorial 9 Q3第 16 章 16.1★
Var(e) = σ²(I−H)、mean shift 下 E(e_j)Tutorial 5 Q13第 14 章★
Cov(AY,BZ)、Cov((I−H)y, b) = 0、RSS = y'(I−H)y 等2025 Lab Test第 11 章 P1–P21★★
💡 规律
近三年的证明题主干重复,小问有增减:2021 Q5 ≈ 2023 Q3(2023 多了特例 (f),2021 多了 OLS 的期望和方差);影响点题 2020 Q4 只考 Cook's D 部分,2021 Q6 只考 DFFITS 部分,2023 Q4 两部分都考。老师说今年"structure 和以前相似"。所以第 15、17 章的证明务必背熟到能默写。

21.2 2021 Q4:用 b = β + Sε 证明 σ̂² 无偏(15 分)

📄 2021 期末 Q4
Consider the general linear model y=Xβ+εy = X\beta + \varepsilon … the least squares estimate of β given by b=(X⊤X)−1X⊤yb = (X^\top X)^{-1}X^\top y.
(a) [2] Show that we can write b in the form b=β+Sεb = \beta + S\varepsilon, where S=(X⊤X)−1X⊤S = (X^\top X)^{-1}X^\top. Using this form, show that b=Syb = Sy is an unbiased estimator of β.
(b) [4] Use the representation of b from part (a) to find the covariance matrix of b in terms of the error variance and matrix S. (Hint: Var(z)=E[(z−E(z))(z−E(z))⊤]\mathrm{Var}(z) = E[(z - E(z))(z - E(z))^\top].)
(c) [4] Using part (a), show that we can write the residual sum of squares (y−Xb)⊤(y−Xb)(y - Xb)^\top(y - Xb) in the form ε⊤(I−XS)ε\varepsilon^\top(I - XS)\varepsilon.
(d) [5] Apply the results from parts (a) and (c) to show that the usual estimator σ^2=(y−Xb)⊤(y−Xb)n−p\hat\sigma^2 = \frac{(y - Xb)^\top(y - Xb)}{n-p} is unbiased. (Hint: use the formula for E(ε⊤Aε)E(\varepsilon^\top A\varepsilon).)
(a)【2 分】
b=Sy=S(Xβ+ε)=(X⊤X)−1X⊤Xβ+Sε=β+Sε.b = Sy = S(X\beta + \varepsilon) = (X^\top X)^{-1}X^\top X\beta + S\varepsilon = \beta + S\varepsilon. E(b)=β+S E(ε)=β.  So b is unbiased.E(b) = \beta + S\,E(\varepsilon) = \beta. \ \text{ So } b \text{ is unbiased.}
(b)【4 分】
Var(b)=E[(b−β)(b−β)⊤]=E[Sεε⊤S⊤]=S E(εε⊤) S⊤=S(σ2I)S⊤=σ2SS⊤.\mathrm{Var}(b) = E[(b - \beta)(b - \beta)^\top] = E[S\varepsilon\varepsilon^\top S^\top] = S\,E(\varepsilon\varepsilon^\top)\,S^\top = S(\sigma^2 I)S^\top = \sigma^2 SS^\top.

进一步:SS⊤=(X⊤X)−1X⊤X(X⊤X)−1=(X⊤X)−1SS^\top = (X^\top X)^{-1}X^\top X(X^\top X)^{-1} = (X^\top X)^{-1},所以 Var(b)=σ2(X⊤X)−1\mathrm{Var}(b) = \sigma^2(X^\top X)^{-1}。(E(εε⊤)=Var(ε)=σ2IE(\varepsilon\varepsilon^\top) = \mathrm{Var}(\varepsilon) = \sigma^2 I 因为 Eε=0E\varepsilon = 0。)

(c)【4 分】
y−Xb=Xβ+ε−X(β+Sε)=ε−XSε=(I−XS)ε.y - Xb = X\beta + \varepsilon - X(\beta + S\varepsilon) = \varepsilon - XS\varepsilon = (I - XS)\varepsilon.

XS=X(X⊤X)−1X⊤=HXS = X(X^\top X)^{-1}X^\top = H 对称且幂等,所以 I−XSI - XS 也对称幂等:

(y−Xb)⊤(y−Xb)=ε⊤(I−XS)⊤(I−XS)ε=ε⊤(I−XS)2ε=ε⊤(I−XS)ε.(y - Xb)^\top(y - Xb) = \varepsilon^\top(I - XS)^\top(I - XS)\varepsilon = \varepsilon^\top(I - XS)^2\varepsilon = \varepsilon^\top(I - XS)\varepsilon.

(如果时间紧,也可以直接展开验证 (I−XS)2=I−2XS+XSXS=I−2XS+XS=I−XS(I-XS)^2 = I - 2XS + XSXS = I - 2XS + XS = I - XS,因为 SX=ISX = I。)

(d)【5 分】

用 E(ε⊤Aε)=tr(A Var(ε))+E(ε)⊤AE(ε)E(\varepsilon^\top A\varepsilon) = \mathrm{tr}(A\,\mathrm{Var}(\varepsilon)) + E(\varepsilon)^\top A E(\varepsilon),Eε=0E\varepsilon = 0,Var(ε)=σ2I\mathrm{Var}(\varepsilon) = \sigma^2I:

E[ε⊤(I−XS)ε]=σ2 tr(I−XS)=σ2[tr(In)−tr(X(X⊤X)−1X⊤)]=σ2[n−tr((X⊤X)−1X⊤X)]=σ2(n−p).E[\varepsilon^\top(I - XS)\varepsilon] = \sigma^2\,\mathrm{tr}(I - XS) = \sigma^2[\mathrm{tr}(I_n) - \mathrm{tr}(X(X^\top X)^{-1}X^\top)] = \sigma^2[n - \mathrm{tr}((X^\top X)^{-1}X^\top X)] = \sigma^2(n - p).

(迹的循环性:tr(AB)=tr(BA)\mathrm{tr}(AB) = \mathrm{tr}(BA),tr(Ip)=p\mathrm{tr}(I_p) = p。)所以 E(σ^2)=σ2(n−p)n−p=σ2E(\hat\sigma^2) = \dfrac{\sigma^2(n-p)}{n-p} = \sigma^2,unbiased。

21.3 2020 Q1:中心化的 SLR(15 分)

📄 2020 期末 Q1
Consider a modified version of the simple linear regression model yi=β0+β1(xi−xˉ)+εiy_i = \beta_0 + \beta_1(x_i - \bar x) + \varepsilon_i (1), so that xix_i enters the model centered …
i) [2] The model is fitted to the data (y, x) = (3, 10), (5, 8), (24, 12). Write model (1) in matrix form; clearly identify X and y.
ii) [4] Derive the least squares estimators b0b_0 and b1b_1 by minimizing S(β0,β1)=∑(yi−β0−β1(xi−xˉ))2S(\beta_0, \beta_1) = \sum(y_i - \beta_0 - \beta_1(x_i - \bar x))^2.
iii) [3] Show that b0b_0 and b1b_1 are unbiased.
iv) [4] Prove that b0b_0 and b1b_1 are uncorrelated. Then show that Var(b)=(σ2/n00σ2/Sxx)\mathrm{Var}(b) = \begin{pmatrix}\sigma^2/n & 0\\ 0 & \sigma^2/S_{xx}\end{pmatrix}.
v) [2] Assume the errors are iid N(0,σ2)N(0, \sigma^2). Find the distribution of n(b0−β0)2σ2+Sxx(b1−β1)2σ2\frac{n(b_0 - \beta_0)^2}{\sigma^2} + \frac{S_{xx}(b_1 - \beta_1)^2}{\sigma^2}.
完整答案

i) xˉ=10\bar x = 10,xi−xˉ=0,−2,2x_i - \bar x = 0, -2, 2:y=(3,5,24)⊤y = (3, 5, 24)^\top,X=(101−212)X = \begin{pmatrix}1&0\\1&-2\\1&2\end{pmatrix},β=(β0,β1)⊤\beta = (\beta_0, \beta_1)^\top。

ii) 利用 ∑(xi−xˉ)=0\sum(x_i - \bar x) = 0:

∂S∂β0=−2∑(yi−β0−β1(xi−xˉ))=0⇒∑yi−nβ0=0⇒b0=yˉ,\frac{\partial S}{\partial\beta_0} = -2\sum(y_i - \beta_0 - \beta_1(x_i - \bar x)) = 0 \Rightarrow \sum y_i - n\beta_0 = 0 \Rightarrow b_0 = \bar y, ∂S∂β1=−2∑(xi−xˉ)(yi−β0−β1(xi−xˉ))=0⇒b1=∑(xi−xˉ)yi∑(xi−xˉ)2=SxySxx.\frac{\partial S}{\partial\beta_1} = -2\sum(x_i - \bar x)(y_i - \beta_0 - \beta_1(x_i - \bar x)) = 0 \Rightarrow b_1 = \frac{\sum(x_i - \bar x)y_i}{\sum(x_i - \bar x)^2} = \frac{S_{xy}}{S_{xx}}.

iii) E(yi)=β0+β1(xi−xˉ)E(y_i) = \beta_0 + \beta_1(x_i - \bar x):E(b0)=1n∑E(yi)=β0+β1⋅0=β0E(b_0) = \frac1n\sum E(y_i) = \beta_0 + \beta_1\cdot 0 = \beta_0;E(b1)=1Sxx∑(xi−xˉ)[β0+β1(xi−xˉ)]=0+β1SxxSxx=β1E(b_1) = \frac{1}{S_{xx}}\sum(x_i - \bar x)[\beta_0 + \beta_1(x_i - \bar x)] = \frac{0 + \beta_1S_{xx}}{S_{xx}} = \beta_1。

iv) 记 ci=(xi−xˉ)/Sxxc_i = (x_i - \bar x)/S_{xx},b1=∑ciyib_1 = \sum c_iy_i,b0=∑1nyib_0 = \sum\frac1n y_i,yiy_i 不相关:

Cov(b0,b1)=∑i1nci σ2=σ2n∑ci=0.\mathrm{Cov}(b_0, b_1) = \sum_i \frac1n c_i\,\sigma^2 = \frac{\sigma^2}{n}\sum c_i = 0.

Var(b0)=∑1n2σ2=σ2/n\mathrm{Var}(b_0) = \sum\frac{1}{n^2}\sigma^2 = \sigma^2/n;Var(b1)=σ2∑ci2=σ2/Sxx\mathrm{Var}(b_1) = \sigma^2\sum c_i^2 = \sigma^2/S_{xx}。(或用矩阵:X⊤X=diag(n,Sxx)X^\top X = \mathrm{diag}(n, S_{xx}),Var(b)=σ2(X⊤X)−1\mathrm{Var}(b) = \sigma^2(X^\top X)^{-1}。)

v) b 是正态 y 的线性变换 ⇒ b0,b1b_0, b_1 联合正态;不相关 + 联合正态 ⇒ 独立。b0−β0σ/n∼N(0,1)\frac{b_0 - \beta_0}{\sigma/\sqrt n} \sim N(0,1),b1−β1σ/Sxx∼N(0,1)\frac{b_1 - \beta_1}{\sigma/\sqrt{S_{xx}}} \sim N(0,1),平方各 ~ χ12\chi^2_1,独立相加 ⇒ χ22\chi^2_2。

21.4 2020 Q3:SSreg 的期望(15 分)

📄 2020 期末 Q3(J 表示全 1 的 n×n 矩阵)
It can be proved that SSreg=y⊤(H−1nJ)y\text{SSreg} = y^\top(H - \frac1n J)y …
i) [2] For the ordinary SLR, what is X? What is X⊤XX^\top X?
ii) [3] Show that 1nX⊤JX=(n∑xi∑xi1n(∑xi)2)\frac1n X^\top JX = \begin{pmatrix}n & \sum x_i\\ \sum x_i & \frac1n(\sum x_i)^2\end{pmatrix}.
iii) [3] Hence show that X⊤(H−1nJ)X=(000Sxx)X^\top(H - \frac1n J)X = \begin{pmatrix}0 & 0\\ 0 & S_{xx}\end{pmatrix}.
iv) [2] Find tr(H−1nJ)\mathrm{tr}(H - \frac1n J).
v) [5] Prove that E(SSreg)=σ2+β12SxxE(\text{SSreg}) = \sigma^2 + \beta_1^2S_{xx}. (Hint: use the formula for E(y⊤Ay)E(y^\top Ay).)
完整答案

i) X 的第 i 行是 (1,xi)(1, x_i);X⊤X=(n∑xi∑xi∑xi2)X^\top X = \begin{pmatrix}n & \sum x_i\\ \sum x_i & \sum x_i^2\end{pmatrix}。

ii) J=11⊤J = \mathbf 1\mathbf 1^\top,X⊤1=(n,∑xi)⊤X^\top\mathbf 1 = (n, \sum x_i)^\top,所以 X⊤JX=(X⊤1)(X⊤1)⊤=(n2n∑xin∑xi(∑xi)2)X^\top JX = (X^\top\mathbf 1)(X^\top\mathbf 1)^\top = \begin{pmatrix}n^2 & n\sum x_i\\ n\sum x_i & (\sum x_i)^2\end{pmatrix},除以 n 即得。

iii) HX=XHX = X ⇒ X⊤HX=X⊤XX^\top HX = X^\top X。X⊤(H−1nJ)X=X⊤X−1nX⊤JX=(000∑xi2−1n(∑xi)2)=(000Sxx)X^\top(H - \frac1nJ)X = X^\top X - \frac1n X^\top JX = \begin{pmatrix}0 & 0\\ 0 & \sum x_i^2 - \frac1n(\sum x_i)^2\end{pmatrix} = \begin{pmatrix}0&0\\0&S_{xx}\end{pmatrix}。

iv) tr(H)=p=2\mathrm{tr}(H) = p = 2,tr(J)=n\mathrm{tr}(J) = n ⇒ tr(H−1nJ)=2−1=1\mathrm{tr}(H - \frac1nJ) = 2 - 1 = 1。

v) A=H−1nJA = H - \frac1nJ,E(y)=XβE(y) = X\beta,Var(y)=σ2I\mathrm{Var}(y) = \sigma^2I:

E(SSreg)=tr(Aσ2I)+β⊤X⊤AXβ=σ2⋅1+(β0,β1)(000Sxx)(β0β1)=σ2+β12Sxx.E(\text{SSreg}) = \mathrm{tr}(A\sigma^2I) + \beta^\top X^\top AX\beta = \sigma^2\cdot 1 + (\beta_0, \beta_1)\begin{pmatrix}0&0\\0&S_{xx}\end{pmatrix}\begin{pmatrix}\beta_0\\\beta_1\end{pmatrix} = \sigma^2 + \beta_1^2S_{xx}.

21.5 判断题:Week 7–10 新内容

和第 11 章同样的用法:先自己判断并写理由,再点按钮看答案。

1. In the general linear model the residuals e₁, …, eₙ have the same variance as the errors, σ².
Var(ei)=σ2(1−hii)<σ2\mathrm{Var}(e_i) = \sigma^2(1 - h_{ii}) < \sigma^2(hii>0h_{ii} > 0),而且各不相同。
2. In the mean shift outlier model for observation k, the partial t statistic of the dummy variable equals the externally studentized residual tk of the original model.
加入哑变量后第 k 个点被完美拟合,其余估计等于删去第 k 点后的估计;两者都 ~ tn−p−1t_{n-p-1},数值相同(第 14 章验证过)。
3. Under the mean shift model E(εj) = Δ, the expected PRESS residual for observation j is Δ, whereas the expected ordinary residual is Δ(1 − hjj).
E(e)=(I−H)E(ε)=Δ(I−H)ujE(e) = (I-H)E(\varepsilon) = \Delta(I-H)u_j,第 j 个分量 Δ(1−hjj)\Delta(1 - h_{jj});PRESS 残差再除以 1−hjj1 - h_{jj}。
4. An observation with a high leverage is always influential.
高杠杆点如果顺着其他点的趋势,删掉它拟合几乎不变。杠杆高且外学生化残差大才最有影响(Di∝ri2hii/(1−hii)D_i \propto r_i^2 h_{ii}/(1-h_{ii}),两者都要大)。
5. Cook's distance can be computed without refitting the model with the i-th observation deleted.
Di=ri2phii1−hiiD_i = \frac{r_i^2}{p}\frac{h_{ii}}{1 - h_{ii}},只需要全模型的 rir_i 和 hiih_{ii}。
6. DFFITSi measures the number of standard errors by which the fitted value at the i-th point changes when the i-th case is deleted.
定义 (y^i−y^i,−i)/(σ^−ihii)(\hat y_i - \hat y_{i,-i})/(\hat\sigma_{-i}\sqrt{h_{ii}}),σhii\sigma\sqrt{h_{ii}} 是 y^i\hat y_i 的标准误。
7. A COVRATIO value much smaller than 1 means that deleting the i-th observation would reduce the precision of the estimated coefficients.
反了:COVRATIO < 1 − 3p/n 表示删掉后协方差矩阵行列式变小,即精度提高(讲义 fish biomass:0.006,删掉后 σ̂ 从 138 降到 31)。> 1 + 3p/n 才是删掉后精度变差。
8. E(ŷi − ŷi,−i) = 0 and Var(ŷi − ŷi,−i) = σ²hii²/(1 − hii).
y^i−y^i,−i=hiiei/(1−hii)\hat y_i - \hat y_{i,-i} = h_{ii}e_i/(1 - h_{ii}),E(ei)=0E(e_i) = 0,Var(ei)=σ2(1−hii)\mathrm{Var}(e_i) = \sigma^2(1 - h_{ii})(第 15 章 P15-4)。
9. If Var(y) is proportional to E(y), the square root transformation of the response approximately stabilises the variance.
一阶 Taylor:Var(y)≈14E(y)Var(y)=\mathrm{Var}(\sqrt y) \approx \frac{1}{4E(y)}\mathrm{Var}(y) = 常数。
10. To decide between a model for y and a model for log(y), it is enough to compare their R² values.
响应尺度不同,R² 和 σ̂ 不可比。看各自的诊断图,或在原尺度上比较 PRESS(第 16 章)。
11. The weighted least squares estimator gives smaller weight to observations with larger error variance.
wi∝1/σi2w_i \propto 1/\sigma_i^2:方差大的观测在 ∑wi(yi−xi⊤β)2\sum w_i(y_i - x_i^\top\beta)^2 中权重小。
12. If the errors are normal with covariance matrix V, the maximum likelihood estimator of β is (XᵀV⁻¹X)⁻¹XᵀV⁻¹y.
对数似然中含 β 的部分是 −12(y−Xβ)⊤V−1(y−Xβ)-\frac12(y - X\beta)^\top V^{-1}(y - X\beta),最大化它就是 GLS(第 17 章)。
13. When the error variances are not constant, the ordinary least squares estimator is biased.
OLS 仍然无偏(E(b)=βE(b) = \beta 只用到 Eε=0E\varepsilon = 0),只是不再是最有效的;方差公式 σ2(X⊤X)−1\sigma^2(X^\top X)^{-1} 也不对了。
14. In the no-intercept model with Var(εi) = xi²σ², the weighted least squares estimator of β is the average of yi/xi.
ri=1/xi2r_i = 1/x_i^2,bw=∑yixi/nb_w = \sum\frac{y_i}{x_i}/n(2023 Q3(f))。
15. A categorical predictor with r levels should be coded using r dummy variables in a model with an intercept.
r 个哑变量之和 = 全 1 列,X 不满秩。应该用 r − 1 个,剩下的那组是参照组。
16. In the model y = β₀ + β₁x + β₂w + β₃xw + ε with a 0/1 dummy w, β₃ is the difference between the slopes of the two groups.
w = 1:斜率 β₁ + β₃;w = 0:斜率 β₁。
17. In a model with a three-level factor, the partial t-tests in summary() can be used to test whether the factor has any effect.
"有没有效应"是 H0:β2=β3=0H_0: \beta_2 = \beta_3 = 0(两个参数),要用嵌套 F 检验;partial t 每次只检验一个组 vs 参照组。
18. Changing the reference group of a factor changes the fitted values of the model.
只是重新参数化,X 的列空间不变,拟合值、残差、RSS、overall F 都不变;变的是系数的含义和数值。
19. The one-way classification model yij = μ + ai + εij written with an intercept column and k group indicator columns has a design matrix that is not of full rank.
k 个指示列之和等于截距列。
20. For the general linear hypothesis H₀: Cβ = d with C an m × p matrix of full row rank, the F statistic has an Fm, n−p distribution under H₀.
F=(Cb−d)⊤[C(X⊤X)−1C⊤]−1(Cb−d)/(mσ^2)F = (Cb-d)^\top[C(X^\top X)^{-1}C^\top]^{-1}(Cb-d)/(m\hat\sigma^2);m = 1 时 F = t²。
21. The LASSO can set some regression coefficients exactly equal to zero.
L1 惩罚 λ∑∣βj∣\lambda\sum|\beta_j| 的几何形状(有"角")使解常落在坐标轴上,所以同时做变量选择。
22. For a linear model, the leave-one-out cross-validation error equals PRESS/n.
LOOCV 的第 i 个预测误差就是 PRESS 残差 ei/(1−hii)e_i/(1-h_{ii})。
23. The validation set approach gives the same estimate of the test error regardless of how the data are split.
依赖随机划分,可能差很多(第 13 章:同一模型 2.5 vs 36.4)。
24. Deleting an influential observation can make both the confidence interval for the mean response and the prediction interval narrower.
讲义 fish biomass:删掉观测 3、4 后 σ̂ 大幅下降,两个区间都变窄。
✅ 本章检查清单
  • 看到题目能马上对上"证明题地图"里的题型,知道模板在哪章
  • 能默写 21.2(2021 Q4),这是 Week 3–5 最核心的证明
  • 24 道判断题全部能说出理由

第 25 章 · 诊断图图鉴:四张图"坏了"分别长什么样

本章目标
期末 R 题和 2020 Q2 都要你看诊断图、说出哪个假设被违反、点名是哪张图。光背"U 形 = 不线性"不够,要能一眼认出来。
本章用模拟数据:我们自己故意破坏一个假设,然后看四张图各自怎么反应。每一节都是:
左边 = 数据 + 拟合线(每个点到线的竖线就是残差;红点 = 在线上方,残差为正;蓝点 = 在线下方,残差为负)
右边 = 对应的诊断图(就是 plot(model) 画出来的那张)
配套脚本:R/ch25_diagnostic_gallery.R(运行一遍就能重新生成本章所有图)。
💡 读懂残差图的一句话
残差图 = 把拟合线"拉平"成 y = 0 之后的散点图。
左图里点在线上方(红),右图里就在 0 上方;左图里点在线下方(蓝),右图里就在 0 下方。所以左图里红蓝点的排列规律,会原样出现在右图里。看诊断图其实就是在找这种规律:理想情况下红蓝点应该随机交错,没有任何规律。

25.1 线性假设 → 看 Residuals vs Fitted(左上)

线性假设:正常、弯曲数据硬用直线、加二次项补救,三种情况的数据图和 Residuals vs Fitted 图
行左图(数据 + 拟合线)右图(Residuals vs Fitted)
A 正常真实关系就是直线。红蓝点在线两侧随机交错点在 0 上下随机散开,红线基本是平的 ✅
B 违反真实关系是弯的,却硬用直线拟合。两头的点都在线上方(红),中间的点都在线下方(蓝)拉平之后就是"红—蓝—红":U 形 ❌
C 补救模型加上 x2x^2,拟合线能弯了,红蓝点又随机交错U 形消失,红线又变平 ✅
✅ 考试写法
The Residuals vs Fitted plot shows a clear U-shaped (curved) pattern: the residuals are mostly positive at both ends and negative in the middle. Hence the linearity assumption is violated.
对照:2020 期末 Figure 1 的左上图就是 B 这种情况(第 24 章)。
Rch25 · 25.1(简化版)
set.seed(1)
x <- runif(50, 0, 10)
y <- 2 + 0.4 * (x - 5)^2 + x + rnorm(50, sd = 1.2)   # 真实关系是弯的
m_line <- lm(y ~ x)
plot(x, y); abline(m_line)          # 直线穿不过弯的数据
plot(m_line, which = 1)             # which = 1:Residuals vs Fitted,出现 U 形
m_quad <- lm(y ~ x + I(x^2))        # 加二次项
plot(m_quad, which = 1)             # U 形消失

25.2 正态性 → 看 Normal Q-Q(右上)

Q-Q 图在做什么:把标准化残差从小到大排好(纵轴),和"如果残差真的服从正态,排第几的那个应该在哪"(横轴,理论分位数)对比。点落在虚线上 = 和正态一致。所以看 Q-Q 图主要看两端往哪个方向偏离。

下图左边是残差的直方图(帮你看分布的形状),右边是对应的 Q-Q 图:

正态性:正态、重尾、右偏、轻尾四种误差的直方图和 Q-Q 图
行直方图Q-Q 图的样子结论
A 正态对称的钟形几乎全部贴着虚线正态 ✅
B 重尾中间很尖,两边有离得很远的点中间贴线;左端往下翘、右端往上翘(两端比虚线更远离 0)尾巴太重 ❌(有极端残差 / 离群点)
C 右偏左边堆积,右边拖一条长尾巴整体向上弯:左端在线上方变平,右端远远在线上方右偏 ❌(常见于价格、收入,log 常能修好)
D 轻尾平平的,没有尾巴左端在线上方、右端在线下方,两端被"压平"(两端比虚线更靠近 0)尾巴太轻 ❌
💡 记法
看两端的点和虚线比:比虚线离 0 更远 → 实际的极端值比正态更极端 → 重尾;比虚线离 0 更近 → 轻尾;一端平、一端翘得厉害 → 偏态(翘在右上 = 右偏)。
2020 期末 Figure 1 的 Q-Q 图:左端一排点在 −1.4 附近变平(在线上方),右端在线下方 → 就是 D 这种轻尾形状。
✅ 考试写法
In the Normal Q-Q plot the points deviate systematically from the straight line at both tails (an S-shape), so the normality assumption is questionable.
如果只是一两个端点偏离:The points lie close to the line apart from one or two points at the tails, so the normality assumption is reasonable.

25.3 方差齐性 → 看 Scale-Location(左下),Residuals vs Fitted 也能看

Scale-Location 的纵轴是 ∣ri∣\sqrt{|r_i|}(标准化残差取绝对值再开方):只看残差有多大,不管正负。所以 Residuals vs Fitted 里向右张开的"喇叭",在这里就变成了一条往上走的红线,更容易看出来。

方差齐性:方差恒定、方差随 x 变大、WLS 补救三种情况的数据图、Residuals vs Fitted 图和 Scale-Location 图
行左图中图(Residuals vs Fitted)右图(Scale-Location)
A 正常点到线的竖线长短差不多上下宽度处处一样,像一条水平的带子红线水平 ✅
B 违反x 越大,竖线越长:点离线越来越远左边窄、右边宽:喇叭形(funnel)红线明显往上走 ❌
C 补救WLS,权重 wi=1/xi2w_i = 1/x_i^2:噪声大的点权重小加权残差 wiei\sqrt{w_i}e_i 的宽度变均匀红线又变平 ✅
⚠️ WLS 模型的陷阱
对 WLS 模型直接 plot(m, which = 1),画的是没有加权的残差,喇叭形还在(数据本身没变)。要看加权残差 weighted.residuals(m),或者看 Scale-Location(它用的是标准化残差,已经考虑了权重)。
另一种常见补救是对 y 做变换:方差随均值变大时,log(y) 或 sqrt(y) 常常能让方差变稳定(第 16 章)。
✅ 考试写法
The Residuals vs Fitted plot shows a funnel shape (the spread of the residuals increases with the fitted values), and the red line in the Scale-Location plot has a clear increasing trend. Hence the constant variance assumption is violated.
没问题时:The Scale-Location plot shows no clear trend, so the constant variance assumption looks reasonable.
Rch25 · 25.3(简化版)
set.seed(85)
x <- runif(80, 1, 10)
y <- 2 + 1.5 * x + rnorm(80, sd = 0.5 * x)   # 标准差和 x 成正比
m <- lm(y ~ x)
plot(m, which = 1)                           # 喇叭形
plot(m, which = 3)                           # which = 3:Scale-Location,红线上升
m_w <- lm(y ~ x, weights = 1 / x^2)          # WLS
plot(fitted(m_w), weighted.residuals(m_w))   # 加权残差:喇叭形消失
plot(m_w, which = 3)                         # 红线变平

25.4 影响点 → 看 Residuals vs Leverage(右下)

下面每一行都是同一组 20 个正常的点,再加一个红色的点。左图里黑色实线 = 包含红点的拟合,蓝色虚线 = 去掉红点后的拟合。两条线差得越多,红点的影响越大,这正是 Cook's D 在量的东西。

影响点:无异常点、大残差低杠杆、高杠杆在线上、高杠杆加大残差四种情况的数据图和 Residuals vs Leverage 图
行红点hiih_{ii}rir_iCook's DiD_i右图里的位置影响点?
A没有加点———所有点都在虚线(Cook's 0.5、1)里面,虚线几乎看不到没有 ✅
Bx 在中间,y 离谱0.05(低)3.87(大)0.39很高但在最左边,没越过虚线离群点,但不是影响点:线几乎没动
Cx 很远,但正好落在直线上0.62(高)0(小)0在最右边,但纵坐标是 0不是:高杠杆但"听话",线没动
Dx 很远,y 也偏离直线0.62(高)−4.15(大)13.8右下角,越过 Cook's 1 的虚线是 ❌:一个点把整条线拽歪了
💡 为什么要"两个都大"
Di=ri2p⋅hii1−hiiD_i = \dfrac{r_i^2}{p}\cdot\dfrac{h_{ii}}{1 - h_{ii}}(第 15 章证明过):残差大(ri2r_i^2 大)乘以杠杆高(hii/(1−hii)h_{ii}/(1-h_{ii}) 大)。B 只有残差大,C 只有杠杆高,乘起来都不大;只有 D 两个都大。
所以 Residuals vs Leverage 图的危险区在右上角和右下角,Cook's 虚线也正是画在那里。读法:有没有点越过 0.5 或 1 的虚线。
✅ 考试写法
In the Residuals vs Leverage plot, observation 21 has a high leverage and a large standardized residual, and it lies outside the Cook's distance contour of 1, so it is an influential observation.
没有影响点时:No observation lies outside the Cook's distance contour of 0.5, so there are no influential observations.
Console 输出
A. no unusual point : h = 0.071  r = 1.08  D = 0.044
B. large residual, low leverage : h = 0.049  r = 3.87  D = 0.386
C. high leverage, on the line : h = 0.616  r = 0  D = 0
D. high leverage AND large residual : h = 0.616  r = -4.15  D = 13.829

25.5 速查表

图检查"坏了"的样子常见补救
Residuals vs Fitted(左上)线性(也能看方差)U 形 / 倒 U 形;喇叭形加 x2x^2;log / sqrt 变换
Normal Q-Q(右上)正态性两端系统性偏离直线:重尾、偏态、轻尾对 y 做变换(右偏用 log)
Scale-Location(左下)方差齐性红线明显上升(或下降)log(y)、sqrt(y);WLS
Residuals vs Leverage(右下)影响点有点越过 Cook's 0.5 / 1 的虚线检查这个点(录入错误?),比较删掉前后的模型
✅ 本章检查清单
  • 能解释"残差图 = 把拟合线拉平",能从数据图想象出残差图
  • 看到 U 形 → linearity violated,并能说出补救(x2x^2 或变换)
  • 能区分 Q-Q 图的重尾、轻尾、右偏三种形状
  • 喇叭形 / Scale-Location 红线上升 → constant variance violated
  • 离群点 ≠ 影响点:影响点要残差大 + 杠杆高,看有没有越过 Cook's 虚线
  • 答题时一定点名是哪张图

第 22 章 · 真题精讲:2023 和 2021 期末的 R 上机题

怎么用
  • 老师说今年结构和 2023 相似:2 小时、4–5 题。2023 是 4 题 × 15 分 = 2 道 R 题(Möbius 填数)+ 2 道证明题(答题本)。2021 是 6 题(3 道 R + 3 道证明),时间 3 小时。
  • 原卷在 past_final_exams/。先自己限时做,再看这里。数据和完整代码在 R/ch22_past_exams.R。
  • 证明题(2023 Q3、Q4,2021 Q4、Q5、Q6)的答案分别在第 17、15、21 章。
  • 整张卷子的完整详细解答:2023 见第 26 章,2021 见第 27 章,2020 见第 24 章,2019 见第 28 章,2014 见第 29 章。本章是速查表。
  • ⚠️ 2023 卷子是扫描件,数据是我照图抄的(log 列和原卷逐个核对过),个别数字可能有出入。2021 的数据清晰,可以放心对照。

22.1 2023 Q1 [15 分]:变换 + SLR 推断 + 哑变量离群点

📄 题目概要
29 automobiles: mpg, disp, log.mpg, log.disp (data given; create data frame carsdat).
PART I (a) [2] Examine diagnostic plots for mpg ~ disp and log.mpg ~ log.disp; comment on which model is better and why.
PART II (model log.mpg ~ log.disp) (b) [4] Is this model better than the intercept-only model? H0/H1 of an F test, F statistic, null distribution, p-value, conclusion at 1%. (c) [1] Estimated expected change in log.mpg for a one unit change in log.disp. (d) [1] 99% CI for the true slope. (e) [1] 99% CI for the mean log.mpg when disp is 240 (cu.in.).
PART III The 6th observation is suspicious … mean shift outlier model, carsdat$dummy = c(rep(0,5),1,rep(0,23)). (a) [2] Refit with dummy added; copy the summary output. (b) [4] Is the dummy significant according to a partial t-test? Test statistic, null distribution, p-value, conclusion at 5%.
Rch22 · 22.1 – 22.4(数据见脚本)

m_raw <- lm(mpg ~ disp, data = carsdat)
m_log <- lm(log.mpg ~ log.disp, data = carsdat)
par(mfrow = c(2, 2)); plot(m_raw); par(mfrow = c(1, 1))   # 原始尺度

par(mfrow = c(2, 2)); plot(m_log); par(mfrow = c(1, 1))   # log 尺度

summary(m_log)
confint(m_log, "log.disp", level = 0.99)
predict(m_log, newdata = data.frame(log.disp = log(240)),
        interval = "confidence", level = 0.99)
carsdat$dummy <- c(rep(0, 5), 1, rep(0, 23))
m_dummy <- lm(log.mpg ~ log.disp + dummy, data = carsdat)
summary(m_dummy)
rstudent(m_log)[6]
Console 输出
            Estimate Std. Error t value Pr(>|t|)
(Intercept)  4.21709    0.22674  18.599  < 2e-16 ***
log.disp    -0.24151    0.04294  -5.625 5.71e-06 ***
Residual standard error: 0.2316 on 27 degrees of freedom
Multiple R-squared:  0.5396,	Adjusted R-squared:  0.5225
F-statistic: 31.64 on 1 and 27 DF,  p-value: 5.715e-06
              0.5 %     99.5 %
log.disp -0.3604691 -0.1225489
      fit      lwr      upr
1 2.89347 2.769225 3.017715
            Estimate Std. Error t value Pr(>|t|)
(Intercept)  4.19833    0.22780  18.430  < 2e-16 ***
log.disp    -0.23942    0.04303  -5.564 7.65e-06 ***
dummy        0.22960    0.23626   0.972     0.34
Residual standard error: 0.2319 on 26 degrees of freedom
       6
0.971828
小题答案要点
(a)log 模型更好模板见第 16 章 16.3:原模型 U 形 + 方差随拟合值增大;log 模型改善;指出 obs 26 高杠杆、有影响
(b)H0:β1=0H_0: \beta_1 = 0 vs H1:β1≠0H_1: \beta_1 \ne 0;F = 31.64;F1,27F_{1,27};p = 5.715e-06p < 0.01 → reject H0:log.disp 模型比只有截距的模型好。df 看 summary 最后一行 "on 1 and 27 DF"
(c)−0.24就是斜率;减少就填负数
(d)(−0.36, −0.12)confint(..., level = 0.99)
(e)(2.77, 3.02)newdata 要填 log(240),因为模型里的预测变量是 log.disp
III (a)复制整个 summary
III (b)t = 0.972,t26t_{26},p = 0.340p > 0.05 → do not reject H0:Δ6=0H_0: \Delta_6 = 0,no evidence that obs 6 is an outlier。t 值 = rstudent(m_log)[6](第 14 章)

22.2 2023 Q2 [15 分]:regsubsets + PRESS + F 检验 + 预测区间

📄 题目概要
32 automobiles: mpg, wt, cyl, disp, hp.
PART I (a) [2] Best subset regression using regsubsets() with mpg as response and wt, cyl, disp, hp as predictors. Identify the best model with i) one, ii) two, iii) three predictors. (b) [4] For each model compute the adjusted R² and the PRESS statistic. What is the best model based on PRESS, and in terms of adjusted R²? (c) [1] Explain briefly the role of PRESS in model selection.
PART II (full model) (d) [3] Is the model better than the intercept-only model? (5%) (e) [3] Compare the model with all four predictors to the model including only weight (wt). (f) [2] 98% prediction interval for mpg when wt = 3.6, cyl = 6, disp = 220, hp = 160.
Rch22 · 22.6 + 22.7

library(leaps)
best <- regsubsets(mpg ~ wt + cyl + disp + hp, data = mpgdat)
summary(best)
PRESS <- function(model) sum((residuals(model) / (1 - hatvalues(model)))^2)
m1 <- lm(mpg ~ cyl, data = mpgdat)
m2 <- lm(mpg ~ wt + cyl, data = mpgdat)
m3 <- lm(mpg ~ wt + cyl + disp, data = mpgdat)
data.frame(model = c("cyl", "wt+cyl", "wt+cyl+disp"),
           adjR2 = c(summary(m1)$adj.r.squared, summary(m2)$adj.r.squared,
                     summary(m3)$adj.r.squared),
           PRESS = c(PRESS(m1), PRESS(m2), PRESS(m3)))
full <- lm(mpg ~ wt + cyl + disp + hp, data = mpgdat)
summary(full)
anova(full)
anova(lm(mpg ~ wt, data = mpgdat), full)
predict(full, data.frame(wt = 3.6, cyl = 6, disp = 220, hp = 160),
        interval = "prediction", level = 0.98)
Console 输出
         wt  cyl disp hp
1  ( 1 ) " " "*" " "  " "
2  ( 1 ) "*" "*" " "  " "
3  ( 1 ) "*" "*" "*"  " "
4  ( 1 ) "*" "*" "*"  "*"
        model     adjR2    PRESS
1         cyl 0.5996692 558.1794
2      wt+cyl 0.6091114 551.3762
3 wt+cyl+disp 0.6976197 443.6182
F-statistic: 20.51 on 4 and 27 DF,  p-value: 7.294e-08
          Df Sum Sq Mean Sq F value    Pr(&gt;F)
wt         1 610.61  610.61 53.0457 7.809e-08 ***
cyl        1 185.65  185.65 16.1284 0.0004242 ***
disp       1 116.18  116.18 10.0929 0.0037075 **
hp         1  32.04   32.04  2.7837 0.1067875
Residuals 27 310.80   11.51
  Res.Df    RSS Df Sum of Sq      F    Pr(>F)
1     30 644.67
2     27 310.80  3    333.88 9.6683 0.0001668 ***
      fit      lwr      upr
1 17.8289 9.123288 26.53452
小题答案
(a)i) mpg ~ cyl;ii) mpg ~ wt + cyl;iii) mpg ~ wt + cyl + disp(照 * 号读)
(b)PRESS 最小的是 wt + cyl + disp(443.6);adjusted R² 最大的也是它(0.698)
(c)模板见第 13 章 13.2
(d)H0:β1=⋯=β4=0H_0: \beta_1 = \dots = \beta_4 = 0 vs 至少一个 ≠ 0;F = 20.51;F4,27F_{4,27};p = 7.294e-08 → reject,模型比只有截距的好
(e)H0:βcyl=βdisp=βhp=0H_0: \beta_{cyl} = \beta_{disp} = \beta_{hp} = 0;F = 9.668;F3,27F_{3,27};p = 0.000167 → reject:cyl、disp、hp 里至少一个在有 wt 的模型里有用
(f)(9.12, 26.53)
💡 anova(full) 和嵌套 F 的关系
anova(full) 是按顺序加变量的平方和:wt 先进,然后 cyl、disp、hp 依次加入。后三行的 Sum Sq 加起来 185.65 + 116.18 + 32.04 = 333.87,正好是嵌套 F 检验里的 "Sum of Sq 333.88"。所以 (e) 也可以直接从 anova 表手算:F=333.87/311.51=9.67F = \frac{333.87/3}{11.51} = 9.67。
⚠️ 2023 Q2 的三个坑
① 1 个变量的最优是 cyl 不是 wt(看 * 号!);② (e) 的分布是 F3,27F_{3,27}:分子 df = 多出的参数个数 3,分母 = 全模型残差 df 27;③ (f) 是 98% 的预测区间,interval = "prediction", level = 0.98 两个都别漏。

22.3 2021 Q1 + Q2 [10 + 10 分]:同样的题型

2021 Q1 和 2023 Q1 Part I–II 几乎一样(换了数据、换了置信水平),2021 Q2 就是 2023 Q1 Part III,多问了一句"和外学生化残差检验是不是同一个"(第 14 章)。

Rch22 · 22.8

m21 <- lm(log.mpg ~ log.disp, data = cars)
summary(m21)
confint(m21, "log.disp", level = 0.97)
predict(m21, data.frame(log.disp = log(290)), interval = "confidence", level = 0.99)
cars$dummy <- c(rep(0, 24), 1, rep(0, 7))
summary(lm(log.mpg ~ log.disp + dummy, data = cars))$coefficients["dummy", ]
t25 <- rstudent(m21)[25]; t25
2 * pt(-abs(t25), df = nrow(cars) - 2 - 1)
Console 输出
            Estimate Std. Error t value Pr(>|t|)
(Intercept)  4.38377    0.26310  16.662  < 2e-16 ***
log.disp    -0.27539    0.05004  -5.504 5.62e-06 ***
Multiple R-squared:  0.5024,	Adjusted R-squared:  0.4858
F-statistic: 30.29 on 1 and 30 DF,  p-value: 5.617e-06
              1.5 %     98.5 %
log.disp -0.3893795 -0.1613927
       fit      lwr      upr
1 2.822368 2.698533 2.946202
  Estimate Std. Error    t value   Pr(>|t|)
 0.2211603  0.2247333  0.9841012  0.3332054
       25
0.9841012
       25
0.3332054

2021 Q1:(b) R² = 0.5024;(c) F = 30.29,F1,30F_{1,30},p = 5.617e-06 → 1% 水平拒绝;(d) −0.28;(e) 97% CI (−0.389, −0.161);(f) (2.70, 2.95)。2021 Q2:(b) t = 0.984,t29t_{29},p = 0.333 → 1% 水平不拒绝;(c) 是同一个检验,t25t_{25} = 0.9841,p 值相同,命令 2*pt(-abs(rstudent(m21)[25]), df = 29)。

22.4 2021 Q3 [10 分]:MLR 的 F 检验家族 + 预测区间

Rch22 · 22.9

full21 <- lm(mpg ~ wt + cyl + disp + hp, data = mpg21)
summary(full21)
anova(lm(mpg ~ wt, data = mpg21), full21)
anova(lm(mpg ~ wt, data = mpg21), lm(mpg ~ wt + disp, data = mpg21))
predict(full21, data.frame(wt = 3.8, cyl = 6, disp = 220, hp = 160),
        interval = "prediction", level = 0.92)
Console 输出
F-statistic: 25.21 on 4 and 27 DF,  p-value: 8.912e-09
  Res.Df    RSS Df Sum of Sq      F    Pr(>F)
1     30 468.46
2     27 247.73  3    220.74 8.0194 0.0005578 ***
  Res.Df    RSS Df Sum of Sq      F Pr(>F)
1     30 468.46
2     29 456.02  1    12.439 0.7911 0.3811
       fit      lwr      upr
1 17.42047 11.60024 23.24071

(a) F = 25.21,F4,27F_{4,27},p = 8.9e-09 → reject。(b) wt vs 全模型:F = 8.019,F3,27F_{3,27},p = 0.00056 → reject。(c) wt vs wt + disp:F = 0.791,F1,29F_{1,29},p = 0.381 → 不拒绝,有 wt 时 disp 没有额外作用。(注意 (c) 的分母 df 是 29,因为"大模型"是 wt + disp,不是全模型。)(d) 92% PI (11.60, 23.24)。

22.5 2020 Q2 [15 分]:只给输出,不用 R(clock auction)

📄 2020 期末 Q2(图和完整输出见 past_final_exams/MATH2831_2020.pdf 第 3–6 页)
The selling price (in pounds) at auction of 30 antique grandfather clocks were recorded, as well as the age (in years) of the clock and number of individuals participating in the bidding.
i) [3] A multiple linear regression model was fitted with Price as the response and Age and Bidders as predictors. Examine diagnostic plots on Figure 1 and comment on whether you think this model is adequate and if not state what assumptions you think are being violated; name the residual plots where you see this violation.
ii) A new model involving log-transformed Price and log-transformed Age, while Bidders is kept un-transformed, was fitted.
a) [3] Examine diagnostic plots for the new model log(Price) ~ log(Age) + Bidders and comment on why the new model is better suited. Using the fitted model predict the selling price (in log units) of a 177 years old grandfather clock when there are 7 participants bidding.
b) [3] State whether you think that this linear regression model is better than the model containing only an intercept term (hypotheses, test statistic, conclusion at 5%).
c) [3] Perform a hypothesis test to compare the model involving both predictors, log(Age) and Bidders, to the model including only log(Age).
d) [3] The externally studentized residual for 20th observation was found to be t20=−2.2504t_{20} = -2.2504. State whether you think this observation is an unusual one, with an appropriate hypothesis test (5%). You may use: qt(0.95,26) = 1.705618, qt(0.95,27) = 1.703288, qt(0.975,26) = 2.055529, qt(0.975,27) = 2.051831.

题目给的输出(节选):

            Estimate Std. Error t value Pr(>|t|)
(Intercept) -0.669082   0.447817  -1.494    0.147
log(Age)     1.449734   0.087463  16.575 1.12e-15 ***
Bidders      0.066160   0.006235  10.611 3.92e-11 ***
Residual standard error: 0.08659 on 27 degrees of freedom
F-statistic: 167.2 on 2 and 27 DF,  p-value: 6.189e-16

> anova(model)
          Df  Sum Sq Mean Sq F value    Pr(>F)
log(Age)   1 1.66267 1.66267  221.74 1.535e-14 ***
Bidders    1 0.84424 0.84424  112.59 3.919e-11 ***
Residuals 27 0.20245 0.00750
Rch22 · 22.10

b <- c(-0.669082, 1.449734, 0.066160)
sum(b * c(1, log(177), 7))
qf(0.95, 2, 27); qf(0.95, 1, 27)
2 * pt(-2.2504, df = 26)
Console 输出
[1] 7.298078
[1] 3.354131
[1] 4.210008
[1] 0.03310697
小题答案
i)Not adequate. Residuals vs Fitted 有明显的 U 形 → 线性假设被违反;Normal Q-Q 两端偏离直线 → 正态性存疑。Scale-Location 没有明显喇叭形。完整解答和原图见第 24 章。
ii a)新模型的残差图没有明显规律、方差大致恒定,Q-Q 图接近直线 → 更合适。预测:−0.669082+1.449734log⁡(177)+0.06616×7=7.298-0.669082 + 1.449734\log(177) + 0.06616 \times 7 = 7.298(log 单位;log⁡\log 是自然对数)。
ii b)H0:β1=β2=0H_0: \beta_1 = \beta_2 = 0 vs H1H_1:至少一个 ≠ 0。F = 167.2 ~ F2,27F_{2,27},p = 6.2e-16 < 0.05 → reject,比只有截距的模型好。
ii c)H0:βBidders=0H_0: \beta_{Bidders} = 0(在有 log(Age) 的模型里)vs ≠0\ne 0。看 anova 表的 Bidders 那一行(它就是在 log(Age) 之后加入 Bidders):F = 112.59 ~ F1,27F_{1,27},p = 3.9e-11 → reject,Bidders 有用。也等于 summary 里 t2=10.6112=112.6t^2 = 10.611^2 = 112.6。
ii d)H0H_0:第 20 个观测不是离群点(均值漂移 Δ=0\Delta = 0)。统计量 t20=−2.2504∼tn−p−1=t26t_{20} = -2.2504 \sim t_{n-p-1} = t_{26}(n = 30,p = 3)。∣t20∣=2.2504>|t_{20}| = 2.2504 > qt(0.975, 26) = 2.0555 → reject at 5%(p ≈ 0.033),第 20 个观测是 unusual。
⚠️ 2020 Q2 的坑:题目同时给了 26 和 27 两个 df
外学生化残差的 df 是 n − p − 1 = 30 − 3 − 1 = 26,比模型残差 df 27 少 1(因为算 tit_i 时去掉了第 i 个观测)。双侧检验用 0.975 分位数。所以选 qt(0.975, 26)。

22.6 Möbius 下拉选项怎么选

真题里 "Null and alternative hypothesis" 和 "Null distribution" 是下拉列表(Select from the list)。你要能一眼认出正确选项:

检验H0Null distribution
SLR 的 F 检验β1=0\beta_1 = 0F1,n−2F_{1,n-2}
overall F(k 个预测变量)β1=⋯=βk=0\beta_1 = \dots = \beta_k = 0Fk,n−k−1F_{k,n-k-1}
嵌套 F(去掉 q 个变量)这 q 个系数都 = 0Fq, n−pfullF_{q,\,n-p_{full}}
partial tβj=0\beta_j = 0tn−pt_{n-p}
外学生化残差 / 哑变量Δk=0\Delta_k = 0tn−p−1t_{n-p-1}(原模型的 p)
✅ 本章检查清单
  • 2023 Q1、Q2 和 2021 Q1–Q3 能在不看答案的情况下 40 分钟内全部做完
  • 每个 F/t 检验都能写出 H0、统计量、分布(带自由度)、p 值、结论五件套
  • CI 还是 PI、置信水平多少、newdata 填原值还是 log 值,做完每题都核对一遍

第 26 章 · 2023 T3 期末完整解答(4 题 × 15 分)

本章目标
把 2023 T3 期末整张卷子逐题、逐小问做一遍。老师说今年的结构和 2023 最像,所以这一份最值得限时完整做一遍。
卷子结构:4 题 × 15 分。Q1、Q2 在 Möbius 上用 R 做,把数字填进空格或下拉框;Q3、Q4 是证明题,写在答题本上。
每一问都按同一个顺序写:考什么 → 需要的知识(Lab Test 之后才学的内容会先补)→ 完整步骤 → 可以直接写的答案 → 得分点和坑。
原卷:past_final_exams/MATH2831_2023_Mobius.pdf 配套脚本:R/ch26_2023_final.R(每个要填的数都能跑出来)。
以前的章节里也有这份卷子的部分解答(第 22 章 R 题速查表、第 17 章 WLS、第 15 章影响点证明),保留不动;本章是完整版,不用再跳去别的章节。
📚 做这份卷子要用到的知识
题知识点Lab Test 学过?详细讲解
Q1 (a)看诊断图、log 变换诊断图学过一半第 25 章(图鉴)、第 16 章
Q1 (b)–(e)SLR 的 F 检验、斜率、置信区间✅ 学过第 4 章
Q1 Part III均值漂移离群点模型(哑变量)❌ 新内容第 14 章,本章会先补
Q2 (a)–(c)regsubsets、adjusted R²、PRESS部分学过第 9、13 章,本章会先补
Q2 (d)–(f)overall F、嵌套 F、预测区间✅ 学过第 6、7 章
Q3加权最小二乘 WLS、最大似然❌ 新内容第 17 章,本章会先补
Q4Cook's D、DFFITS 的证明❌ 新内容第 15 章,本章会先补

26.1 Q1 [15 分]:log 变换 + SLR 推断 + 用哑变量检验离群点

📄 2023 期末 Q1(Möbius,数据见下面的代码)
To answer the following question, copy and paste the data below into RStudio and create a data frame called carsdat. […]
The weight (in 1000 lbs), number of cylinders, displacement (cu.in.), gross horsepower and the fuel consumption measured in mpg (miles per gallon) were recorded for 29 automobiles (1973–74 models) in the US. It was desired to predict the mpg in terms of the other variables.
PART I. In one study, a simple linear regression model was fitted to the data with mpg as the response and the displacement disp as the predictor. After examining the diagnostic plots, it was suggested to transform the response and predictor variables. A new model involving log-transformed mpg and log-transformed disp was fitted to the data.
(a) [2 marks] Examine diagnostic plots for the two fitted simple linear regression models, one with mpg as the response and disp as the predictor, and another with log.mpg as the response and log.disp as the predictor. Comment on which model is better suited for analyzing the data set and why. Type your comments in a few sentences in the box below.
PART II. Obtain R summary output generated by fitting a simple linear regression model with log.mpg as the response and log.disp as the predictor and answer the following questions. You can simply copy and paste numerical answers from the R output.
(b) [4 marks] Is there evidence that this simple linear regression model with log.disp as the predictor is better than the model containing only an intercept term? State the null and alternative hypothesis of an appropriate F test. Also state the value of the test statistic, the distribution of the test statistic under the null hypothesis, the p-value and the conclusion using a 1% level of significance.
(c) [1 mark] What is the estimated expected change in log.mpg for a one unit change in log.disp? (enter negative number if decreasing)
(d) [1 mark] Obtain a 99% confidence interval for the true slope coefficient in this model.
(e) [1 mark] Obtain a 99% confidence interval for the mean log.mpg when disp is 240 (cu.in.).
PART III. The 6th observation in this study was thought to be suspicious on the basis of prior knowledge. Researcher decided to test whether this observation is an unusual one using indicator variables as described below. Follow the same steps as what the researcher used. To test H0:Δ6=0H_0: \Delta_6 = 0 against the alternative H1:Δ6≠0H_1: \Delta_6 \ne 0 in the mean shift outlier model with E(ε6)=Δ6E(\varepsilon_6) = \Delta_6, construct a new predictor dummy variable which is 1 for the 6th observation and 0 otherwise. Hint: carsdat$dummy = c(rep(0,5),1,rep(0,23))
(a) [2 marks] Now refit the linear model with this new predictor dummy variable added to the existing predictor log.disp. Obtain R summary output generated by fitting a multiple linear model with log.mpg as the response and log.disp and dummy as the predictors and copy as a text in the box below.
(b) [4 marks] Is the dummy predictor significant according to a partial t-test? State the value of the test statistic, the distribution of the test statistic under the null hypothesis, the p-value and the conclusion using a 5% level of significance in the box below.

第 0 步:把数据贴进 RStudio。考场上直接复制题目给的几行,最后一行 carsdat = data.frame(...) 建数据框。log 两列题目已经算好了,不用自己取 log。

Rch26 · 26.1
mpg <- c(15.7,16.1,14.3,18.4,30.8,25.7,30.7,16.4,19.2,15.7,24.4,22.8,19.9,19.5,14.2,
         22.9,23.2,19.1,18.8,18.4,17.1,15.8,8.3,10.6,13.8,33.0,32.2,34.8,21.6)
disp <- c(341.1,303.3,331.1,416.0,54.7,136.8,95.6,340.5,103.3,295.1,85.0,192.9,358.4,
          244.2,409.2,216.3,112.1,136.2,162.7,250.1,286.5,345.2,490.4,476.8,472.7,2.8,
          110.5,80.7,88.9)
log.mpg <- c(2.75,2.78,2.66,2.91,3.43,3.25,3.42,2.80,2.95,2.75,3.19,3.13,2.99,2.97,2.65,
             3.13,3.14,2.95,2.93,2.91,2.84,2.76,2.12,2.36,2.62,3.50,3.47,3.55,3.07)
log.disp <- c(5.83,5.71,5.80,6.03,4.00,4.92,4.56,5.83,4.64,5.69,4.44,5.26,5.88,5.50,6.01,
              5.38,4.72,4.91,5.09,5.52,5.66,5.84,6.20,6.17,6.16,1.03,4.71,4.39,4.49)
carsdat <- data.frame(mpg, disp, log.mpg, log.disp)
nrow(carsdat)      # 检查:应该是 29
✍️ Part I (a) [2 分] 两个模型哪个更合适

考什么:会画诊断图,并能说出哪个假设被违反、在哪张图上看到的(读图方法见第 25 章)。

Rch26 · 26.2
m_raw <- lm(mpg ~ disp, data = carsdat)
m_log <- lm(log.mpg ~ log.disp, data = carsdat)
par(mfrow = c(2, 2)); plot(m_raw); par(mfrow = c(1, 1))    # 原模型的四张图
par(mfrow = c(2, 2)); plot(m_log); par(mfrow = c(1, 1))    # log 模型的四张图

原模型 mpg ~ disp:

2023 Q1 原模型 mpg ~ disp 的四张诊断图
  • Residuals vs Fitted:红线先下后上,是一个浅 U 形:两头残差偏正、中间偏负 ⇒ 线性关系不完全成立。
  • Scale-Location:红线从左到右明显上升;左上图里拟合值大的地方点也散得更开 ⇒ 方差随拟合值变大,等方差假设不成立。
  • Normal Q-Q 大致在线上,Residuals vs Leverage 没有点越过 Cook's 0.5。

log 模型 log.mpg ~ log.disp:

2023 Q1 log 模型的四张诊断图

这张图看起来反而更乱,原因只有一个:第 26 辆车。它的 disp = 2.8,其他车都在 50–500 之间,取 log 后 log.disp = 1.03,离其他点(4–6.2)非常远。所以:

  • Residuals vs Leverage:26 号杠杆 0.63、标准化残差 −3.31,越过了 Cook's distance = 1 的虚线(D26=9.26D_{26} = 9.26)⇒ 强影响点。
  • 其他三张图里红线被 26 号一个点拉歪(左上图最右边那一段斜线就是它造成的)。

看除了 26 号以外的大部分点:残差在 0 上下随机,没有 U 形;Scale-Location 也没有原模型那种持续上升。为了确认,可以把 26 号去掉再画一次(题目没要求,只是帮你理解):

去掉第 26 辆车后 log 模型的四张诊断图

去掉 26 号后四张图都很好:没有 U 形、Scale-Location 基本平、Q-Q 贴线、没有点越过 Cook's 0.5。

可以直接写的答案:

For the model mpg ~ disp, the Residuals vs Fitted plot shows a curved (U-shaped) pattern and the Scale-Location plot shows the spread of the residuals increasing with the fitted values, so the linearity and constant variance assumptions are violated. For the log model, apart from observation 26, the residuals are randomly scattered around zero with roughly constant spread and the Q-Q plot is close to a straight line, so the log model is better suited for analysing the data. However, observation 26 (disp = 2.8, a very unusual value) has a very high leverage and lies outside the Cook's distance contour of 1 in the log model, so it is highly influential and should be checked (it may be a recording error).

得分点:2 分 = 选 log 模型 + 理由里点名图和假设。提到 26 号是加分项,能显示你真的看了图。不要因为 log 模型的图被 26 号拉乱就选原模型。

✍️ Part II (b) [4 分] F 检验:比只有截距的模型好吗

考什么:SLR 的 overall F 检验(Lab Test 学过)。"只有截距的模型"就是 yi=β0+εiy_i = \beta_0 + \varepsilon_i,也就是说 x 完全没用;所以"比它好吗"就是检验斜率是不是 0。

Rch26 · 26.3
summary(m_log)
Console 输出
Coefficients:
            Estimate Std. Error t value Pr(>|t|)
(Intercept)  4.21709    0.22674  18.599  < 2e-16 ***
log.disp    -0.24151    0.04294  -5.625 5.71e-06 ***
---
Residual standard error: 0.2316 on 27 degrees of freedom
Multiple R-squared:  0.5396,	Adjusted R-squared:  0.5225
F-statistic: 31.64 on 1 and 27 DF,  p-value: 5.715e-06

答案全在 summary 的最后一行:

空格填什么为什么
Null and alternative hypothesis(下拉)H0:β1=0H_0: \beta_1 = 0 vs H1:β1≠0H_1: \beta_1 \ne 0β1\beta_1 是 log.disp 的系数
F statistic31.64"F-statistic: 31.64"
Null distribution(下拉)F1,27F_{1,27}"on 1 and 27 DF":分子 df = 预测变量个数 1,分母 df = n − 2 = 29 − 2 = 27
p-value5.715E-6"p-value: 5.715e-06",Möbius 接受科学计数法
ConclusionSince the p-value 5.715e-06 < 0.01, we reject H0 at the 1% level. There is strong evidence that the model with log.disp is better than the intercept-only model, i.e. log.disp is useful for predicting log.mpg.

小知识:SLR 里 F = t²:(−5.625)2=31.64(-5.625)^2 = 31.64,p 值也和 log.disp 那一行的 t 检验相同。

坑:注意这题是 1% 水平,不是 5%。结论一定要写比较(p < 0.01)+ 拒绝 H0 + 用题目的语言说结论。

✍️ Part II (c) [1 分] log.disp 增加 1,log.mpg 的期望变化

这就是斜率:模型 E(log.mpg)=β0+β1 log.dispE(\text{log.mpg}) = \beta_0 + \beta_1\,\text{log.disp},log.disp 增加 1,期望增加 β1\beta_1。估计值在 summary 里 log.disp 那一行的 Estimate:−0.24151(题目说减少就填负数)。

✍️ Part II (d) [1 分] 斜率的 99% 置信区间
Rch26 · 26.3
confint(m_log, "log.disp", level = 0.99)
Console 输出
              0.5 %     99.5 %
log.disp -0.3604691 -0.1225489

填 (−0.3605, −0.1225)。

手算核对(明白 R 在算什么):b1±t0.005, 27⋅se(b1)=−0.24151±2.771×0.04294b_1 \pm t_{0.005,\,27}\cdot \text{se}(b_1) = -0.24151 \pm 2.771 \times 0.04294,其中 qt(0.995, 27) = 2.771。99% 双侧,每边留 0.5%,所以分位数是 0.995。

坑:level = 0.99 别忘了写,默认是 95%。

✍️ Part II (e) [1 分] disp = 240 时 log.mpg 均值的 99% 置信区间
Rch26 · 26.3
predict(m_log, newdata = data.frame(log.disp = log(240)),
        interval = "confidence", level = 0.99)
Console 输出
      fit      lwr      upr
1 2.89347 2.769225 3.017715

填 (2.7692, 3.0177)。

三个要点,每一个都容易错:

  1. newdata 里要填 log(240),不是 240。模型的预测变量是 log.disp,所以给它的必须是 log 尺度的值(log(240) = 5.48)。填 240 会得到荒唐的结果。
  2. 问的是均值的区间 ⇒ interval = "confidence";如果问"一辆车"的 log.mpg,才用 "prediction"。
  3. level = 0.99。

结果是 log 尺度的区间(题目问的就是 mean log.mpg,所以不用再取 exp)。

📚 Part III 需要先补:均值漂移离群点模型(第 14 章)

怀疑第 6 个观测"不正常",做法是给它单独加一个截距:

log.mpgi=β0+β1 log.dispi+Δ6 dummyi+εi,dummyi={1i=60i≠6\text{log.mpg}_i = \beta_0 + \beta_1\,\text{log.disp}_i + \Delta_6\,\text{dummy}_i + \varepsilon_i,\qquad \text{dummy}_i = \begin{cases}1 & i = 6\\ 0 & i \ne 6\end{cases}
  • 对其他观测,dummy = 0,模型和原来一样。
  • 对第 6 个观测,均值多了一个 Δ6\Delta_6:它可以"单独往上或往下挪"。
  • 如果第 6 个观测本来就符合模型,就不需要挪,Δ6=0\Delta_6 = 0;如果它是离群点,Δ6≠0\Delta_6 \ne 0。

所以"检验第 6 个观测是不是离群点"就变成了一个普通的 partial t 检验:检验 dummy 的系数是不是 0。

重要结论:这个 t 值正好等于原模型里第 6 个观测的外学生化残差 t6t_6 = rstudent(m_log)[6](2021 Q2(c) 专门考过这一点)。

✍️ Part III (a) [2 分] 加入 dummy 重新拟合,复制 summary
Rch26 · 26.4
carsdat$dummy <- c(rep(0, 5), 1, rep(0, 23))     # 5 个 0、一个 1、23 个 0,共 29 个
m_dummy <- lm(log.mpg ~ log.disp + dummy, data = carsdat)
summary(m_dummy)
Console 输出
Call:
lm(formula = log.mpg ~ log.disp + dummy, data = carsdat)

Residuals:
     Min       1Q   Median       3Q      Max
-0.59394 -0.08605 -0.00323  0.15536  0.40271

Coefficients:
            Estimate Std. Error t value Pr(>|t|)
(Intercept)  4.19833    0.22780  18.430  < 2e-16 ***
log.disp    -0.23942    0.04303  -5.564 7.65e-06 ***
dummy        0.22960    0.23626   0.972     0.34
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 0.2319 on 26 degrees of freedom
Multiple R-squared:  0.5557,	Adjusted R-squared:  0.5215
F-statistic: 16.26 on 2 and 26 DF,  p-value: 2.629e-05

把整个输出(从 Call 到最后一行)复制进答题框。2 分就是给"跑对了"的:dummy 放对位置(第 6 个是 1)、模型里同时有 log.disp 和 dummy。

✍️ Part III (b) [4 分] dummy 显著吗(partial t 检验)

看 summary 里 dummy 那一行:

要写的答案说明
HypothesesH0:Δ6=0H_0: \Delta_6 = 0 vs H1:Δ6≠0H_1: \Delta_6 \ne 0题目已经给了
Test statistict = 0.972dummy 行的 t value
Null distributiont26t_{26}新模型有 3 个参数,df = n − 3 = 29 − 3 = 26(也就是原模型的 n − p − 1 = 29 − 2 − 1);summary 里 "on 26 degrees of freedom"
p-value0.34dummy 行的 Pr(>|t|)

可以直接写的答案:

The partial t statistic for dummy is t = 0.972, which follows a t distribution with 26 degrees of freedom under H0. The p-value is 0.34 > 0.05, so we do not reject H0: Δ6 = 0 at the 5% level. The dummy predictor is not significant, so there is no evidence that the 6th observation is an outlier (it is not unusual).

核对:rstudent(m_log)[6] = 0.9718,和 dummy 的 t 值相同。也可以用临界值判断:qt(0.975, 26) = 2.056,|0.972| < 2.056,不拒绝。

坑:df 写成 27(原模型的残差 df)是最常见的错误;加了 dummy 以后多了一个参数,df 少 1。

26.2 Q2 [15 分]:最优子集 + PRESS + F 检验 + 预测区间

📄 2023 期末 Q2(Möbius)
To answer the following question, copy and paste the data below into RStudio and create a data frame mpg. […]
The weight (in 1000 lbs), number of cylinders, displacement (cu.in.), gross horsepower and the fuel consumption measured in mpg were recorded for 32 automobiles (1973–74 models) in the US. It was desired to predict the mpg in terms of the other variables. A multiple linear regression model was fitted with mpg as the response and the remaining variables as predictors. The variables wt, cyl, disp and hp in the regression output below refer to weight, number of cylinders, displacement and gross horsepower respectively.
PART I. Carry out a best subset linear regression analysis using the regsubsets() function on the mpg data set, where the full model has mpg as the response and wt, cyl, disp and hp as the predictors. (Hint: run the library(leaps) first)
(a) [2 marks] Copy your regsubsets summary output in the box below. Identify the best model obtained with: i) only one predictor; ii) with two predictors; iii) with three predictors.
(b) [4 marks] For each model identified in i), ii) and iii) above, compute the adjusted R² and the PRESS statistic. Copy these values in the box below. What is the best model based on PRESS statistic, what is the best model in terms of the adjusted R² from among the chosen models by the regsubsets() function and why?
(c) [1 mark] Explain briefly the role of the PRESS statistic in model selection.
PART II. Now obtain R summary and anova outputs generated by fitting a multiple linear regression model with mpg as the response and wt, cyl, disp and hp as the predictors, and answer the following questions.
(d) [3 marks] State whether you think that this linear regression model is better than the model containing only an intercept term. You should refer to an appropriate hypothesis test to support your answer: state the null and alternative hypothesis, the value of the test statistic, the distribution of the test statistic under the null hypothesis, and the conclusion of the test at the 5% level of significance.
(e) [3 marks] It was felt that weight (wt) should be included in any model for mpg, but that the other three predictors, number of cylinders (cyl), displacement (disp) and gross horsepower (hp) might not be related to mpg in the model involving weight. Perform a hypothesis test to compare the model involving all four predictors to the model including only weight (wt). State the null and alternative hypothesis, the value of the test statistic, the distribution of the test statistic under the null hypothesis and the conclusion of the test at the 5% level of significance.
(f) [2 marks] Obtain a 98% prediction interval for the fuel consumption in mpg when the weight of a car is 3.6 (in 1000 lbs), it has 6 cylinders and the displacement equals 220 (cu.in.) with gross horsepower of 160.
Rch26 · 26.5
mpg <- c(18.0,24.2,22.5,22.7,22.1,16.0,13.7,23.9,24.1,17.7,15.5,17.4,15.1,15.8,13.1,7.5,
         15.8,30.2,30.0,33.0,18.8,15.7,16.9,9.0,19.1,25.7,24.9,34.0,15.4,22.3,15.5,23.0)
wt <- c(2.220,3.305,2.284,3.393,3.896,3.174,3.486,3.118,3.324,3.240,3.128,4.208,3.436,
        3.860,5.614,5.032,5.489,1.908,1.567,1.713,2.105,3.540,3.667,3.266,3.831,1.721,
        1.988,1.997,3.114,3.110,3.638,2.996)
disp <- c(100.0,224.5,102.6,284.7,428.4,182.1,347.4,135.9,166.9,137.6,120.8,296.5,231.7,
          287.8,526.6,401.2,461.6,34.9,68.5,52.8,66.1,321.0,338.8,263.9,397.9,46.9,97.5,
          167.7,342.6,196.0,311.2,153.4)
cyl <- c(6,6,4,6,8,6,8,4,4,6,6,8,8,8,8,8,8,4,4,4,4,8,8,8,8,4,4,4,8,6,8,4)
hp <- c(110,110,93,110,175,105,245,62,95,123,123,180,180,180,205,215,230,66,52,65,97,
        150,150,245,175,66,91,113,264,175,335,109)
mpg <- data.frame(mpg, wt, cyl, disp, hp)     # 原卷就叫 mpg,和列名同名也没关系
📚 Part I 需要先补:最优子集、adjusted R²、PRESS(第 9、13 章)
  • regsubsets(leaps 包):对每一个"变量个数"(1 个、2 个、3 个……)把所有组合都试一遍,挑出 RSS 最小(等价于 R² 最大)的那个。同样个数的变量,RSS 小的就是"最好"的。
  • 为什么不能直接用 R² 比较不同个数的模型:加变量 R² 只会变大,永远选最大的模型。所以要用会"惩罚变量个数"的标准:
  • adjusted R² =1−SSres/(n−p)SStotal/(n−1)= 1 - \dfrac{\text{SSres}/(n-p)}{\text{SStotal}/(n-1)}:变量没用时会下降。越大越好。
  • PRESS =∑i=1n(yi−y^i,−i)2=∑i=1n(ei1−hii)2= \sum_{i=1}^n \big(y_i - \hat y_{i,-i}\big)^2 = \sum_{i=1}^n \Big(\dfrac{e_i}{1 - h_{ii}}\Big)^2:每次去掉一个点,用剩下的点拟合,再去预测这个被去掉的点,把预测误差平方加起来。衡量的是预测新数据的能力。越小越好。第二个等号是捷径公式,R 里一行就能算。
✍️ Part I (a) [2 分] 每个大小的最优模型
Rch26 · 26.6
library(leaps)
best <- regsubsets(mpg ~ wt + cyl + disp + hp, data = mpg)
summary(best)
Console 输出
Selection Algorithm: exhaustive
         wt  cyl disp hp
1  ( 1 ) " " "*" " "  " "
2  ( 1 ) "*" "*" " "  " "
3  ( 1 ) "*" "*" "*"  " "
4  ( 1 ) "*" "*" "*"  "*"

读法:每一行是一个变量个数,有 * 的列就是被选中的变量。

  • i) 1 个变量:mpg ~ cyl
  • ii) 2 个变量:mpg ~ wt + cyl
  • iii) 3 个变量:mpg ~ wt + cyl + disp

坑:凭直觉会以为 1 个变量最好的是 wt,但这份数据里是 cyl。一定照 * 号读,不要猜。答题框里要把 summary 输出也复制进去。

✍️ Part I (b) [4 分] adjusted R² 和 PRESS
Rch26 · 26.6
PRESS <- function(model) sum((residuals(model) / (1 - hatvalues(model)))^2)
m1 <- lm(mpg ~ cyl, data = mpg)
m2 <- lm(mpg ~ wt + cyl, data = mpg)
m3 <- lm(mpg ~ wt + cyl + disp, data = mpg)
data.frame(model = c("cyl", "wt+cyl", "wt+cyl+disp"),
           adjR2 = c(summary(m1)$adj.r.squared, summary(m2)$adj.r.squared,
                     summary(m3)$adj.r.squared),
           PRESS = c(PRESS(m1), PRESS(m2), PRESS(m3)))
Console 输出
        model  adjR2  PRESS
1         cyl 0.5997 558.18
2      wt+cyl 0.6091 551.38
3 wt+cyl+disp 0.6976 443.62

可以直接写的答案:

Adjusted R²: 0.5997 (cyl), 0.6091 (wt + cyl), 0.6976 (wt + cyl + disp). PRESS: 558.18, 551.38, 443.62. The model mpg ~ wt + cyl + disp is the best in terms of both criteria: it has the smallest PRESS statistic (443.62), so it has the smallest leave-one-out prediction error, and it has the largest adjusted R² (0.6976), so it explains the most variation after adjusting for the number of predictors.

得分点:6 个数(各 0.5 分左右)+ 两个结论 + "why"(PRESS 越小越好、adjusted R² 越大越好)。只写"model 3"不写理由会扣分。

✍️ Part I (c) [1 分] PRESS 在模型选择中的作用

The PRESS statistic is the sum of squared prediction errors ∑i(yi−y^i,−i)2\sum_i (y_i - \hat y_{i,-i})^2, where each observation is predicted from the model fitted without that observation. It measures how well a model predicts new data (out-of-sample prediction error) rather than how well it fits the data used to build it, so it penalises overfitting. A smaller PRESS indicates a better model.

✍️ Part II (d) [3 分] overall F 检验
Rch26 · 26.7
full <- lm(mpg ~ wt + cyl + disp + hp, data = mpg)
summary(full)
anova(full)
Console 输出
            Estimate Std. Error t value Pr(>|t|)
(Intercept) 45.57510    3.46699  13.145    3e-13 ***
wt          -4.76702    1.35738  -3.512  0.00158 **
cyl         -2.65396    0.79601  -3.334  0.00250 **
disp         0.04403    0.01289   3.417  0.00202 **
hp          -0.02718    0.01629  -1.668  0.10679
Residual standard error: 3.393 on 27 degrees of freedom
Multiple R-squared:  0.7524,	Adjusted R-squared:  0.7157
F-statistic: 20.51 on 4 and 27 DF,  p-value: 7.294e-08

          Df Sum Sq Mean Sq F value    Pr(>F)
wt         1 610.61  610.61 53.0457 7.809e-08 ***
cyl        1 185.65  185.65 16.1284 0.0004242 ***
disp       1 116.18  116.18 10.0929 0.0037075 **
hp         1  32.04   32.04  2.7837 0.1067875
Residuals 27 310.80   11.51
空格填什么
HypothesesH0:β1=β2=β3=β4=0H_0: \beta_1 = \beta_2 = \beta_3 = \beta_4 = 0 vs H1H_1: at least one βj≠0\beta_j \ne 0(j = 1, …, 4)
F statistic20.51
Null distributionF4,27F_{4,27}(分子 = 预测变量个数 4;分母 = n − p = 32 − 5 = 27)
p-value7.294E-8
Conclusionp-value < 0.05, so reject H0. At least one of the predictors is related to mpg, so the model is better than the intercept-only model.

注意:H0 里不含 β0\beta_0(截距)。"只有截距的模型"就是 β0\beta_0 留下、其他全是 0。

✍️ Part II (e) [3 分] 嵌套 F 检验:全模型 vs 只有 wt

考什么:比较两个嵌套模型(一个是另一个的一部分)。小模型(只有 wt)就是在大模型里令 cyl、disp、hp 的系数都为 0。

Rch26 · 26.7
reduced <- lm(mpg ~ wt, data = mpg)
anova(reduced, full)
Console 输出
Model 1: mpg ~ wt
Model 2: mpg ~ wt + cyl + disp + hp
  Res.Df    RSS Df Sum of Sq      F    Pr(>F)
1     30 644.67
2     27 310.80  3    333.88 9.6683 0.0001668 ***
空格填什么
HypothesesH0:βcyl=βdisp=βhp=0H_0: \beta_{cyl} = \beta_{disp} = \beta_{hp} = 0(在含 wt 的模型里)vs H1H_1: at least one of them ≠0\ne 0
F statistic9.6683
Null distributionF3,27F_{3,27}
p-value0.0001668
Conclusionp-value < 0.05, so reject H0. At least one of cyl, disp and hp is related to mpg in the model that already contains wt; the full model is preferred over the model with weight only.

F 是怎么算出来的(Lab Test 的公式):

F=(RSSsmall−RSSfull)/qRSSfull/(n−p)=(644.67−310.80)/3310.80/27=111.2911.51=9.67.F = \frac{(\text{RSS}_{\text{small}} - \text{RSS}_{\text{full}})/q}{\text{RSS}_{\text{full}}/(n - p)} = \frac{(644.67 - 310.80)/3}{310.80/27} = \frac{111.29}{11.51} = 9.67.

q = 3 是被检验的系数个数(分子 df),n − p = 27 是全模型的残差 df(分母 df)。

另一种算法:anova(full) 是按顺序加变量的,wt 之后 cyl、disp、hp 三行的 Sum Sq 加起来 185.65 + 116.18 + 32.04 = 333.87,正好是上面的 "Sum of Sq"。所以题目让你看 anova 输出,也能手算出这个 F。

✍️ Part II (f) [2 分] 98% 预测区间
Rch26 · 26.7
predict(full, newdata = data.frame(wt = 3.6, cyl = 6, disp = 220, hp = 160),
        interval = "prediction", level = 0.98)
Console 输出
      fit      lwr      upr
1 17.8289 9.123288 26.53452

填 (9.1233, 26.5345)。

坑:① 是 prediction(一辆车),不是 confidence;② 是 98%;③ newdata 的列名要和模型里的变量名完全一样(wt、cyl、disp、hp)。这个模型没有取 log,所以直接填原值。

26.3 Q3 [15 分]:无截距模型的加权最小二乘(答题本)

📄 2023 期末 Q3(must be completed in the exam booklet)
Consider the simple linear regression model with no intercept yi=βxi+εi,i=1,…,n,(1)y_i = \beta x_i + \varepsilon_i,\quad i = 1, \dots, n, \qquad (1) where εi\varepsilon_i are uncorrelated errors with zero mean, but with non-constant variance given by Var(εi)=σ2ri\mathrm{Var}(\varepsilon_i) = \dfrac{\sigma^2}{r_i} for some positive weights rir_i, i = 1, …, n. We need to take account of the weights rir_i when estimating the parameter β.
(a) [2 marks] Derive the so called weighted least squares estimator bwb_w of β by minimizing the weighted version of the sum of squares Sw(β)=∑i=1nri(yi−βxi)2S_w(\beta) = \sum_{i=1}^n r_i(y_i - \beta x_i)^2 with respect to β.
(b) [2 marks] Find the E(bw)E(b_w) and Var(bw)\mathrm{Var}(b_w) for the estimator bwb_w obtained in part (a).
(c) [3 marks] Find the maximum likelihood estimator (mle) of β if, in addition, the errors εi\varepsilon_i are normally distributed. Does the mle of β coincide with bwb_w from part (a)?
(d) [3 marks] Multiply both sides of the equation (1) by ri\sqrt{r_i} and get ri yi=ri βxi+ri εi\sqrt{r_i}\,y_i = \sqrt{r_i}\,\beta x_i + \sqrt{r_i}\,\varepsilon_i. Denote ynew,i=ri yiy_{new,i} = \sqrt{r_i}\,y_i, xnew,i=ri xix_{new,i} = \sqrt{r_i}\,x_i and εnew,i=ri εi\varepsilon_{new,i} = \sqrt{r_i}\,\varepsilon_i. Show that the new model ynew,i=βxnew,i+εnew,i,i=1,…,n,(2)y_{new,i} = \beta x_{new,i} + \varepsilon_{new,i},\quad i = 1, \dots, n, \qquad (2) is the ordinary least squares regression model with no intercept, that is, the errors εnew,i\varepsilon_{new,i} are i) uncorrelated, ii) with zero mean and iii) with common variance σ².
(e) [2 marks] Prove that the least squares estimator of β for the model (2) is equal to the weighted least squares estimator bwb_w from part (a).
(f) [3 marks] Using the results from the previous parts, find an expression for the weighted least squares estimator of the parameter β from the model (1) when Var(εi)=xi2σ2\mathrm{Var}(\varepsilon_i) = x_i^2\sigma^2, xi>0x_i > 0. Write down the model (2) in this case and comment on your findings.
📚 需要先补:为什么要"加权"(第 17 章)

普通最小二乘假设所有误差的方差都是 σ²。这里第 i 个误差的方差是 σ2/ri\sigma^2/r_i:rir_i 大 ⇒ 方差小 ⇒ 这个点更可靠。所以在平方和里给它更大的权重 rir_i,让拟合更"听"可靠的点。rir_i 全是 1 时就回到普通最小二乘。

整道题只用到四个工具,Lab Test 都学过:① 求导令为 0 求最小值;② E(∑ciyi)=∑ciE(yi)E(\sum c_iy_i) = \sum c_iE(y_i);③ 不相关时 Var(∑ciyi)=∑ci2 Var(yi)\mathrm{Var}(\sum c_iy_i) = \sum c_i^2\,\mathrm{Var}(y_i)(交叉项是 0,展开方法见第 24 章 Q1 iv);④ Var(aZ)=a2Var(Z)\mathrm{Var}(aZ) = a^2\mathrm{Var}(Z)、Cov(aU,bW)=ab Cov(U,W)\mathrm{Cov}(aU, bW) = ab\,\mathrm{Cov}(U, W)。

模型里的 xix_i 和 rir_i 都是已知的常数,只有 εi\varepsilon_i(所以 yiy_i)是随机的。由 (1):E(yi)=βxiE(y_i) = \beta x_i,Var(yi)=Var(εi)=σ2/ri\mathrm{Var}(y_i) = \mathrm{Var}(\varepsilon_i) = \sigma^2/r_i,yiy_i 之间互不相关。

✍️ (a) [2 分] 推导 bwb_w

对 β 求导(链式法则:括号对 β 求导得 −xi-x_i)并令其为 0:

dSwdβ=∑i=1nri⋅2(yi−βxi)⋅(−xi)=−2∑i=1nrixiyi+2β∑i=1nrixi2=0.\frac{dS_w}{d\beta} = \sum_{i=1}^n r_i\cdot 2(y_i - \beta x_i)\cdot(-x_i) = -2\sum_{i=1}^n r_ix_iy_i + 2\beta\sum_{i=1}^n r_ix_i^2 = 0.

移项,β 提出来:

β∑rixi2=∑rixiyi⇒bw=∑i=1nrixiyi∑i=1nrixi2.\beta\sum r_ix_i^2 = \sum r_ix_iy_i \quad\Rightarrow\quad b_w = \frac{\sum_{i=1}^n r_ix_iy_i}{\sum_{i=1}^n r_ix_i^2}.

二阶导 d2Swdβ2=2∑rixi2>0\dfrac{d^2S_w}{d\beta^2} = 2\sum r_ix_i^2 > 0(ri>0r_i > 0),所以这是最小值。

得分点:求导正确 1 分,解出 bwb_w 1 分。二阶导写一句更完整。

✍️ (b) [2 分] E(bw)E(b_w) 和 Var(bw)\mathrm{Var}(b_w)

先把 bwb_w 写成"常数 × yiy_i"的和:分母 ∑rjxj2\sum r_jx_j^2 是常数,记作 WW,

bw=∑i=1nciyi,ci=rixiW,W=∑j=1nrjxj2.b_w = \sum_{i=1}^n c_iy_i,\qquad c_i = \frac{r_ix_i}{W},\quad W = \sum_{j=1}^n r_jx_j^2.

期望(期望可以穿过常数和求和):

E(bw)=∑ciE(yi)=1W∑rixi⋅βxi=β∑rixi2W=β.E(b_w) = \sum c_iE(y_i) = \frac{1}{W}\sum r_ix_i\cdot\beta x_i = \frac{\beta\sum r_ix_i^2}{W} = \beta.

方差(yiy_i 互不相关,交叉项为 0,只剩 ci2Var(yi)c_i^2\mathrm{Var}(y_i)):

Var(bw)=∑ci2 Var(yi)=1W2∑ri2xi2⋅σ2ri=σ2∑rixi2W2=σ2WW2=σ2∑i=1nrixi2.\mathrm{Var}(b_w) = \sum c_i^2\,\mathrm{Var}(y_i) = \frac{1}{W^2}\sum r_i^2x_i^2\cdot\frac{\sigma^2}{r_i} = \frac{\sigma^2\sum r_ix_i^2}{W^2} = \frac{\sigma^2 W}{W^2} = \frac{\sigma^2}{\sum_{i=1}^n r_ix_i^2}.

得分点:写出"uncorrelated"这个理由。bwb_w 无偏。

✍️ (c) [3 分] 最大似然估计

思路:MLE = 让"观测到这组数据的概率(密度)"最大的参数值。步骤固定:写似然 → 取 log → 求导令为 0。

第 1 步:误差正态 + 不相关 ⇒ 独立(正态时不相关等价于独立)。所以 yi∼N(βxi,σ2/ri)y_i \sim N(\beta x_i, \sigma^2/r_i) 相互独立,似然是各自密度的乘积(正态密度见 formula sheet):

L(β)=∏i=1n12πσ2/riexp⁡{−(yi−βxi)22σ2/ri}.L(\beta) = \prod_{i=1}^n \frac{1}{\sqrt{2\pi\sigma^2/r_i}}\exp\Big\{-\frac{(y_i - \beta x_i)^2}{2\sigma^2/r_i}\Big\}.

第 2 步:取 log(乘积变成求和,exp 消失):

log⁡L(β)=−12∑i=1nlog⁡(2πσ2ri)⏟与 β 无关−12σ2∑i=1nri(yi−βxi)2=const−12σ2Sw(β).\log L(\beta) = \underbrace{-\frac12\sum_{i=1}^n\log\Big(\frac{2\pi\sigma^2}{r_i}\Big)}_{\text{与 } \beta \text{ 无关}} - \frac{1}{2\sigma^2}\sum_{i=1}^n r_i(y_i - \beta x_i)^2 = \text{const} - \frac{1}{2\sigma^2}S_w(\beta).

第 3 步:前面有个负号,所以最大化 log L ⇔ 最小化 Sw(β)S_w(\beta),这正是 (a) 的问题。(也可以直接求导:dlog⁡Ldβ=1σ2∑rixi(yi−βxi)=0\frac{d\log L}{d\beta} = \frac{1}{\sigma^2}\sum r_ix_i(y_i - \beta x_i) = 0,得到和 (a) 一样的方程。)

β^MLE=∑rixiyi∑rixi2=bw.\hat\beta_{\text{MLE}} = \frac{\sum r_ix_iy_i}{\sum r_ix_i^2} = b_w.

Yes, the mle of β coincides with bwb_w.

得分点:似然写对 1 分;log 后指出与 SwS_w 的关系 1 分;结论 1 分。

✍️ (d) [3 分] 变换后的误差满足普通最小二乘假设

εnew,i=ri εi\varepsilon_{new,i} = \sqrt{r_i}\,\varepsilon_i,ri\sqrt{r_i} 是常数。三条逐一验证:

  • ii) zero mean:E(εnew,i)=ri E(εi)=ri⋅0=0E(\varepsilon_{new,i}) = \sqrt{r_i}\,E(\varepsilon_i) = \sqrt{r_i}\cdot 0 = 0。
  • iii) common variance:Var(εnew,i)=(ri)2 Var(εi)=ri⋅σ2ri=σ2\mathrm{Var}(\varepsilon_{new,i}) = (\sqrt{r_i})^2\,\mathrm{Var}(\varepsilon_i) = r_i\cdot\dfrac{\sigma^2}{r_i} = \sigma^2,对所有 i 都一样。
  • i) uncorrelated:i≠ji \ne j 时 Cov(εnew,i,εnew,j)=rirj Cov(εi,εj)=rirj⋅0=0\mathrm{Cov}(\varepsilon_{new,i}, \varepsilon_{new,j}) = \sqrt{r_i}\sqrt{r_j}\,\mathrm{Cov}(\varepsilon_i, \varepsilon_j) = \sqrt{r_ir_j}\cdot 0 = 0。

所以模型 (2) 的误差不相关、均值为 0、方差都是 σ²,正是普通(无截距)最小二乘模型的假设。

这一步的意义:乘以 ri\sqrt{r_i} 正好把"方差不同"的问题消掉了:方差大的点(rir_i 小)被缩小,方差小的点被放大。

✍️ (e) [2 分] 模型 (2) 的最小二乘估计 = bwb_w

无截距模型 y=βx+εy = \beta x + \varepsilon 的普通最小二乘估计是 ∑xiyi∑xi2\dfrac{\sum x_iy_i}{\sum x_i^2}(就是 (a) 中 ri≡1r_i \equiv 1 的情形:最小化 ∑(yi−βxi)2\sum(y_i - \beta x_i)^2)。对模型 (2) 用这个公式,把 xx、yy 换成 xnewx_{new}、ynewy_{new}:

β^=∑xnew,i ynew,i∑xnew,i2=∑rixi⋅riyi∑(rixi)2=∑rixiyi∑rixi2=bw.\hat\beta = \frac{\sum x_{new,i}\,y_{new,i}}{\sum x_{new,i}^2} = \frac{\sum \sqrt{r_i}x_i\cdot\sqrt{r_i}y_i}{\sum(\sqrt{r_i}x_i)^2} = \frac{\sum r_ix_iy_i}{\sum r_ix_i^2} = b_w.

另一种写法:模型 (2) 的普通平方和 ∑(ynew,i−βxnew,i)2=∑ri(yi−βxi)2=Sw(β)\sum(y_{new,i} - \beta x_{new,i})^2 = \sum r_i(y_i - \beta x_i)^2 = S_w(\beta),和 (a) 最小化的是同一个函数,所以解相同。

✍️ (f) [3 分] 特例 Var(εi)=xi2σ2\mathrm{Var}(\varepsilon_i) = x_i^2\sigma^2

第 1 步:找权重。对比 Var(εi)=σ2/ri=xi2σ2\mathrm{Var}(\varepsilon_i) = \sigma^2/r_i = x_i^2\sigma^2 ⇒ ri=1xi2r_i = \dfrac{1}{x_i^2}。

第 2 步:代入 (a):

bw=∑1xi2 xiyi∑1xi2 xi2=∑yi/xi∑1=1n∑i=1nyixi.b_w = \frac{\sum \frac{1}{x_i^2}\,x_iy_i}{\sum \frac{1}{x_i^2}\,x_i^2} = \frac{\sum y_i/x_i}{\sum 1} = \frac1n\sum_{i=1}^n\frac{y_i}{x_i}.

第 3 步:写出模型 (2)。ri=1/xi\sqrt{r_i} = 1/x_i(xi>0x_i > 0),所以 ynew,i=yi/xiy_{new,i} = y_i/x_i,xnew,i=xi/xi=1x_{new,i} = x_i/x_i = 1,εnew,i=εi/xi\varepsilon_{new,i} = \varepsilon_i/x_i:

yixi=β⋅1+εixi,i.e.ynew,i=β+εnew,i,Var(εnew,i)=σ2.\frac{y_i}{x_i} = \beta\cdot 1 + \frac{\varepsilon_i}{x_i},\qquad\text{i.e.}\quad y_{new,i} = \beta + \varepsilon_{new,i},\quad \mathrm{Var}(\varepsilon_{new,i}) = \sigma^2.

Comment(可以直接写):After the transformation the model is an intercept-only model for the ratios yi/xiy_i/x_i with constant variance σ², so the least squares estimate of β is simply the sample mean of the ratios yi/xiy_i/x_i. Observations with large xix_i have large error variance and are down-weighted (weight 1/xi21/x_i^2).

得分点:ri=1/xi2r_i = 1/x_i^2 1 分;bwb_w 的表达式 1 分;模型 (2) 和评论 1 分。

Rch26 · 26.8:数值验证 (a)(e)(f)(考试不用)
set.seed(3)
x <- runif(30, 1, 10); r <- 1 / x^2          # Var = x^2 sigma^2 的情形
y <- 2 * x + rnorm(30, sd = x)
c(formula = sum(r * x * y) / sum(r * x^2),                    # (a) 的公式
  lm_weights = unname(coef(lm(y ~ x - 1, weights = r))),      # R 的加权回归
  ols_on_new = unname(coef(lm(I(sqrt(r) * y) ~ I(sqrt(r) * x) - 1))),   # (e)
  mean_ratio = mean(y / x))                                   # (f)
Console 输出
 formula lm_weights ols_on_new mean_ratio
2.077146   2.077146   2.077146   2.077146

四种算法完全一致。

26.4 Q4 [15 分]:Cook's D 和 DFFITS 的捷径公式(答题本)

📄 2023 期末 Q4(must be completed in the exam booklet)
Consider the full rank general linear model y=Xβ+εy = X\beta + \varepsilon (with usual assumptions discussed in lectures: y is an n × 1 vector of responses, X is an n × p design matrix and ε is a vector of zero mean errors uncorrelated with variance σ²). In this question, you are asked to derive easy computational formulas for the influence measures for the ith observation, namely, Cook's distance DiD_i, and the DFFITSi\text{DFFITS}_i.
PART I. Recall that the Cook's distance for the ith observation is the influence measure given by Di=(b−b−i)⊤(X⊤X)(b−b−i)p σ^2.(1)D_i = \frac{(b - b_{-i})^\top(X^\top X)(b - b_{-i})}{p\,\hat\sigma^2}. \qquad (1) (a) [2 marks] Use the definition of b−ib_{-i} given in lectures to explain in words what does b−b−ib - b_{-i} represent. What does the Cook's distance DiD_i measure?
In part (b) below, you can make use of the following result (you are not asked to prove this): b−i=b−(X⊤X)−1xiei1−hii,(2)b_{-i} = b - \frac{(X^\top X)^{-1}x_ie_i}{1 - h_{ii}}, \qquad (2) where xi⊤x_i^\top is the ith row of design matrix X, eie_i is the ith raw residual and hiih_{ii} is the ith leverage.
(b) [4 marks] Show that the Cook's distance DiD_i, defined in (1), can be computed using the following formula Di=ri2phii1−hiiD_i = \dfrac{r_i^2}{p}\dfrac{h_{ii}}{1 - h_{ii}}, where rir_i is the ith internally studentized residual.
PART II. Recall that the ith DFFITS value is defined as DFFITSi=y^i−y^i,−iσ^−ihii.(3)\text{DFFITS}_i = \frac{\hat y_i - \hat y_{i,-i}}{\hat\sigma_{-i}\sqrt{h_{ii}}}. \qquad (3) (c) [2 marks] Use the definition of y^i,−i\hat y_{i,-i} given in lectures to explain in words what does the numerator in (3), y^i−y^i,−i\hat y_i - \hat y_{i,-i} represent.
(d) [1 mark] Explain in words why we can express y^i\hat y_i and y^i,−i\hat y_{i,-i} as y^i=xi⊤b\hat y_i = x_i^\top b and y^i,−i=xi⊤b−i\hat y_{i,-i} = x_i^\top b_{-i}?
(e) [4 marks] Show that y^i−y^i,−i=hiiei1−hii\hat y_i - \hat y_{i,-i} = \dfrac{h_{ii}e_i}{1 - h_{ii}} and hence compute E(y^i−y^i,−i)E(\hat y_i - \hat y_{i,-i}) and Var(y^i−y^i,−i)\mathrm{Var}(\hat y_i - \hat y_{i,-i}). In your answer, you can use the result (2).
(f) [2 marks] Show that the influence measure DFFITSi\text{DFFITS}_i, defined in (3), can be computed using the following formula DFFITSi=tihii1−hii\text{DFFITS}_i = t_i\sqrt{\dfrac{h_{ii}}{1 - h_{ii}}}, where tit_i is the ith externally studentized residual.
📚 需要先补:这道题里每个符号是什么(第 8、10、15 章)
符号意思公式
bb用全部 n 个点得到的最小二乘估计(X⊤X)−1X⊤y(X^\top X)^{-1}X^\top y
b−ib_{-i}去掉第 i 个点后重新拟合得到的估计题目给的 (2)
xi⊤x_i^\topX 的第 i 行(第 i 个点的预测变量,含开头的 1)1 × p 行向量;xix_i 是 p × 1 列向量
eie_i第 i 个普通残差yi−y^iy_i - \hat y_i
hiih_{ii}第 i 个杠杆值(帽子矩阵 H 的对角元)xi⊤(X⊤X)−1xix_i^\top(X^\top X)^{-1}x_i(一个数)
rir_i内学生化残差(rstandard)eiσ^1−hii\dfrac{e_i}{\hat\sigma\sqrt{1 - h_{ii}}}
tit_i外学生化残差(rstudent)eiσ^−i1−hii\dfrac{e_i}{\hat\sigma_{-i}\sqrt{1 - h_{ii}}},σ^−i\hat\sigma_{-i} 是去掉第 i 点后的 σ 估计

证明里反复用的三条矩阵规则:① (AB)⊤=B⊤A⊤(AB)^\top = B^\top A^\top;② (X⊤X)−1(X^\top X)^{-1} 是对称矩阵,转置不变;③ 数(1×1)可以随便提到前面。formula sheet 上有 rir_i、tit_i、DiD_i、DFFITS 的定义,不用背定义,要会的是推导。

✍️ (a) [2 分] b−b−ib - b_{-i} 和 Cook's D 的含义

bb is the least squares estimate of β based on all n observations, and b−ib_{-i} is the least squares estimate obtained by fitting the model without the i-th observation. So b−b−ib - b_{-i} is the change in the estimated regression coefficients caused by deleting the i-th observation.

Cook's distance DiD_i measures the overall influence of the i-th observation: it is a scaled (by pσ^2p\hat\sigma^2) squared distance between bb and b−ib_{-i}, i.e. how much all the estimated coefficients (equivalently, all the fitted values, since (b−b−i)⊤X⊤X(b−b−i)=∥Xb−Xb−i∥2(b - b_{-i})^\top X^\top X(b - b_{-i}) = \|Xb - Xb_{-i}\|^2) change when the i-th observation is deleted. A large DiD_i (e.g. Di>1D_i > 1) indicates an influential observation.

中文要点:b−b−ib - b_{-i} = 删掉第 i 点后系数变了多少;DiD_i = 这个变化"有多大"(标准化后的长度平方)。各 1 分。

✍️ (b) [4 分] 证明 Di=ri2phii1−hiiD_i = \dfrac{r_i^2}{p}\dfrac{h_{ii}}{1 - h_{ii}}

第 1 步:由 (2) 得到 b−b−ib - b_{-i}(移项):

b−b−i=(X⊤X)−1xiei1−hii.b - b_{-i} = \frac{(X^\top X)^{-1}x_ie_i}{1 - h_{ii}}.

第 2 步:写出它的转置。eie_i、1−hii1 - h_{ii} 是数,转置不变;((X⊤X)−1xi)⊤=xi⊤((X⊤X)−1)⊤=xi⊤(X⊤X)−1\big((X^\top X)^{-1}x_i\big)^\top = x_i^\top\big((X^\top X)^{-1}\big)^\top = x_i^\top(X^\top X)^{-1}(规则 ① ②):

(b−b−i)⊤=ei xi⊤(X⊤X)−11−hii.(b - b_{-i})^\top = \frac{e_i\,x_i^\top(X^\top X)^{-1}}{1 - h_{ii}}.

第 3 步:代入 (1) 的分子,数提到前面,中间的 (X⊤X)−1(X⊤X)=I(X^\top X)^{-1}(X^\top X) = I 消掉:

(b−b−i)⊤(X⊤X)(b−b−i)=ei2(1−hii)2  xi⊤(X⊤X)−1(X⊤X)(X⊤X)−1xi=ei2(1−hii)2  xi⊤(X⊤X)−1xi=ei2 hii(1−hii)2.\begin{aligned} (b - b_{-i})^\top(X^\top X)(b - b_{-i}) &= \frac{e_i^2}{(1 - h_{ii})^2}\;x_i^\top(X^\top X)^{-1}(X^\top X)(X^\top X)^{-1}x_i\\ &= \frac{e_i^2}{(1 - h_{ii})^2}\;x_i^\top(X^\top X)^{-1}x_i = \frac{e_i^2\,h_{ii}}{(1 - h_{ii})^2}. \end{aligned}

第 4 步:除以 pσ^2p\hat\sigma^2,凑出 ri2r_i^2。把 (1−hii)2(1 - h_{ii})^2 拆成两个 (1−hii)(1 - h_{ii}),一个给 ri2r_i^2,一个留下:

Di=ei2 hiip σ^2(1−hii)2=ei2σ^2(1−hii)⏟= ri2⋅hiip(1−hii)=ri2p hii1−hii,D_i = \frac{e_i^2\,h_{ii}}{p\,\hat\sigma^2(1 - h_{ii})^2} = \underbrace{\frac{e_i^2}{\hat\sigma^2(1 - h_{ii})}}_{=\,r_i^2}\cdot\frac{h_{ii}}{p(1 - h_{ii})} = \frac{r_i^2}{p}\,\frac{h_{ii}}{1 - h_{ii}},

因为 ri=eiσ^1−hiir_i = \dfrac{e_i}{\hat\sigma\sqrt{1 - h_{ii}}},平方得 ri2=ei2σ^2(1−hii)r_i^2 = \dfrac{e_i^2}{\hat\sigma^2(1 - h_{ii})}。∎

得分点:第 1 步 1 分,第 3 步(消掉中间、认出 hiih_{ii})2 分,第 4 步 1 分。第一行先写出 (1) 和 (2),就算后面卡住也有分。

✍️ (c) [2 分] y^i−y^i,−i\hat y_i - \hat y_{i,-i} 的含义

y^i\hat y_i is the fitted value for the i-th observation from the model fitted to all n observations. y^i,−i\hat y_{i,-i} is the predicted value at the i-th observation's predictor values xix_i from the model fitted without the i-th observation. So y^i−y^i,−i\hat y_i - \hat y_{i,-i} is the change in the fitted (predicted) value at the i-th point when the i-th observation is deleted from the data; a large change means the i-th observation pulls the fitted surface towards itself.

✍️ (d) [1 分] 为什么 y^i=xi⊤b\hat y_i = x_i^\top b、y^i,−i=xi⊤b−i\hat y_{i,-i} = x_i^\top b_{-i}

A fitted/predicted value is obtained by plugging the predictor values of the i-th observation, xi⊤x_i^\top (the i-th row of X), into the estimated regression equation. Using all the data the estimated coefficients are bb, so y^i=xi⊤b\hat y_i = x_i^\top b; using the data without the i-th observation the estimated coefficients are b−ib_{-i}, and we evaluate that fitted equation at the same xix_i, so y^i,−i=xi⊤b−i\hat y_{i,-i} = x_i^\top b_{-i}.

✍️ (e) [4 分] 证明 y^i−y^i,−i=hiiei1−hii\hat y_i - \hat y_{i,-i} = \dfrac{h_{ii}e_i}{1 - h_{ii}},并求期望和方差

证明:由 (d) 和 (2):

y^i−y^i,−i=xi⊤b−xi⊤b−i=xi⊤(b−b−i)=(2)xi⊤(X⊤X)−1xiei1−hii=xi⊤(X⊤X)−1xi⏞= hii  ei1−hii=hiiei1−hii.\hat y_i - \hat y_{i,-i} = x_i^\top b - x_i^\top b_{-i} = x_i^\top(b - b_{-i}) \overset{(2)}{=} x_i^\top\frac{(X^\top X)^{-1}x_ie_i}{1 - h_{ii}} = \frac{\overbrace{x_i^\top(X^\top X)^{-1}x_i}^{=\,h_{ii}}\;e_i}{1 - h_{ii}} = \frac{h_{ii}e_i}{1 - h_{ii}}.

求期望和方差要用残差的两个性质(第 14 章;如果不记得,下面是推导):残差向量 e=(I−H)ye = (I - H)y,E(y)=XβE(y) = X\beta,Var(y)=σ2I\mathrm{Var}(y) = \sigma^2 I,而 HX=XHX = X、(I−H)(I - H) 对称且 (I−H)2=I−H(I - H)^2 = I - H:

E(e)=(I−H)Xβ=Xβ−Xβ=0,Var(e)=(I−H) σ2I (I−H)⊤=σ2(I−H).E(e) = (I - H)X\beta = X\beta - X\beta = 0,\qquad \mathrm{Var}(e) = (I - H)\,\sigma^2 I\,(I - H)^\top = \sigma^2(I - H).

取第 i 个分量:E(ei)=0E(e_i) = 0,Var(ei)=σ2(1−hii)\mathrm{Var}(e_i) = \sigma^2(1 - h_{ii})。

期望(hiih_{ii} 只由 X 决定,是常数):

E(y^i−y^i,−i)=hii1−hii E(ei)=0.E(\hat y_i - \hat y_{i,-i}) = \frac{h_{ii}}{1 - h_{ii}}\,E(e_i) = 0.

方差(常数提出来要平方):

Var(y^i−y^i,−i)=(hii1−hii)2Var(ei)=hii2(1−hii)2 σ2(1−hii)=σ2hii21−hii.\mathrm{Var}(\hat y_i - \hat y_{i,-i}) = \Big(\frac{h_{ii}}{1 - h_{ii}}\Big)^2\mathrm{Var}(e_i) = \frac{h_{ii}^2}{(1 - h_{ii})^2}\,\sigma^2(1 - h_{ii}) = \frac{\sigma^2h_{ii}^2}{1 - h_{ii}}.

得分点:证明 2 分,期望 1 分,方差 1 分。最容易丢分的是方差里忘了平方。

✍️ (f) [2 分] 证明 DFFITSi=tihii1−hii\text{DFFITS}_i = t_i\sqrt{\dfrac{h_{ii}}{1 - h_{ii}}}

把 (e) 代入定义 (3),然后把分母拆开凑出 tit_i:

DFFITSi=y^i−y^i,−iσ^−ihii=hiiei(1−hii) σ^−ihii.\text{DFFITS}_i = \frac{\hat y_i - \hat y_{i,-i}}{\hat\sigma_{-i}\sqrt{h_{ii}}} = \frac{h_{ii}e_i}{(1 - h_{ii})\,\hat\sigma_{-i}\sqrt{h_{ii}}}.

用两个拆分:hiihii=hii\dfrac{h_{ii}}{\sqrt{h_{ii}}} = \sqrt{h_{ii}},11−hii=11−hii⋅11−hii\dfrac{1}{1 - h_{ii}} = \dfrac{1}{\sqrt{1 - h_{ii}}}\cdot\dfrac{1}{\sqrt{1 - h_{ii}}}:

DFFITSi=eiσ^−i1−hii⏟= ti⋅hii1−hii=tihii1−hii.  ∎\text{DFFITS}_i = \underbrace{\frac{e_i}{\hat\sigma_{-i}\sqrt{1 - h_{ii}}}}_{=\,t_i}\cdot\frac{\sqrt{h_{ii}}}{\sqrt{1 - h_{ii}}} = t_i\sqrt{\frac{h_{ii}}{1 - h_{ii}}}.\ \ ∎

就算 (e) 没证出来,这一问也可以直接用 (e) 的结论,照样拿满分。

Rch26 · 26.9:用一个真实模型数值验证三个公式(考试不用)
mq <- lm(mpg ~ wt + disp, data = mpg)
p <- length(coef(mq)); h <- hatvalues(mq); r <- rstandard(mq); tt <- rstudent(mq)
e <- residuals(mq); X <- model.matrix(mq)
i <- which.max(cooks.distance(mq))                       # 挑 Cook's D 最大的点
b_minus_i <- coef(lm(mpg ~ wt + disp, data = mpg[-i, ])) # 真的去掉第 i 点重新拟合
D_def <- t(coef(mq) - b_minus_i) %*% crossprod(X) %*% (coef(mq) - b_minus_i) /
  (p * summary(mq)$sigma^2)
c(D_def = D_def, D_short = r[i]^2 / p * h[i] / (1 - h[i]))
c(diff_def = fitted(mq)[i] - sum(X[i, ] * b_minus_i), diff_short = h[i] * e[i] / (1 - h[i]))
c(DFFITS_short = tt[i] * sqrt(h[i] / (1 - h[i])), DFFITS_R = dffits(mq)[i])
Console 输出
     D_def    D_short
 0.2053734  0.2053734
  diff_def diff_short
  1.368005   1.368005
DFFITS_short     DFFITS_R
   0.8288662    0.8288662

用定义(真的删掉一个点重新拟合)和用捷径公式算出来完全相同。

✅ 2023 卷检查清单
  • Q1:log 模型更好,但要指出第 26 辆车是强影响点;F = 31.64 ~ F1,27F_{1,27};(e) newdata 填 log(240);dummy 的 t = 0.972 ~ t<b>26</b>t_{<b>26</b>},p = 0.34,不拒绝
  • Q2:1 个变量最优是 cyl;PRESS 最小、adjusted R² 最大都是 wt + cyl + disp;嵌套 F = 9.668 ~ F3,27F_{3,27};98% prediction 区间 (9.12, 26.53)
  • Q3:bw=∑rixiyi/∑rixi2b_w = \sum r_ix_iy_i/\sum r_ix_i^2,Var(bw)=σ2/∑rixi2\mathrm{Var}(b_w) = \sigma^2/\sum r_ix_i^2;MLE = bwb_w;(f) bwb_w = yi/xiy_i/x_i 的平均
  • Q4:每问第一行先写定义;(b) 的关键是中间的 (X⊤X)−1X⊤X(X⊤X)−1=(X⊤X)−1(X^\top X)^{-1}X^\top X(X^\top X)^{-1} = (X^\top X)^{-1};(e) 要用 Var(ei)=σ2(1−hii)\mathrm{Var}(e_i) = \sigma^2(1 - h_{ii})
  • 限时练习:Q1 + Q2 共 45 分钟(R 题),Q3 + Q4 共 50 分钟(手写),留 25 分钟检查

第 27 章 · 2021 T3 期末完整解答(6 题:3 道 R + 3 道证明)

本章目标
把 2021 T3 期末整张卷子逐题、逐小问做一遍。2021 是线上 Möbius 考试,3 小时,6 题:Q1–Q3(各 10 分)是 R 上机题,在 Möbius 里填;Q4–Q6(各 15 分)是手写证明,拍照转成 PDF 上传。
2021 和 2023 的题型几乎一样(同样的汽车数据、同样的检验),所以做完第 26 章再做这一章,正好检验你是不是真的会了,而不是记住了答案。
原卷:past_final_exams/MATH2831_2021_Mobius.pdf 配套脚本:R/ch27_2021_final.R。
以前的章节里有这份卷子的部分解答(第 22 章速查表、第 21 章 Q4、第 17 章 Q5、第 15 章 Q6),保留不动;本章是完整版。
📚 做这份卷子要用到的知识
题知识点Lab Test 学过?详细讲解
Q1诊断图、log 变换、R²、F 检验、置信区间大部分学过第 4、16、25 章
Q2均值漂移离群点模型、外学生化残差外学生化残差学过;哑变量是新内容第 10、14 章,本章会先补
Q3overall F、嵌套 F、预测区间✅ 学过第 6、7 章
Q4矩阵形式的 b 的期望、方差、E(ε⊤Aε)E(\varepsilon^\top A\varepsilon)学过一部分第 5、11 章,本章会先补
Q5无截距 OLS、WLS、MLE❌ WLS 是新内容第 17 章;和 2023 Q3 几乎相同
Q6影响点、DFFITS❌ 新内容第 15 章;和 2023 Q4 Part II 几乎相同

27.1 Q1 [10 分]:log 变换 + SLR 推断

📄 2021 期末 Q1(Möbius,数据见下面的代码)
To answer the following question, copy and paste the data below into RStudio and create a data frame called cars. […] The weight (in 1000 lbs), number of cylinders, displacement (cu.in.), gross horsepower and the fuel consumption measured in mpg (miles per gallon) were recorded for 32 automobiles (1973–74 models) in the US. It was desired to predict the mpg in terms of the other variables.
PART I. In one study, a simple linear regression model was fitted to the data with mpg as the response and the displacement disp as the predictor. After examining the diagnostic plots, it was suggested to transform the response and predictor variables. A new model involving log-transformed mpg and log-transformed disp was fitted to the data.
(a) [2 marks] Examine diagnostic plots for the two fitted simple linear regression models, one with mpg as the response and disp as the predictor, and another with log.mpg as the response and log.disp as the predictor. Comment on which model is better suited for analyzing the data set and why. Type your comments in a few sentences in the box below.
PART II. Obtain R summary output generated by fitting a simple linear regression model with log.mpg as the response and log.disp as the predictor and answer the following questions.
(b) [1 mark] What proportion of variation in the response is explained by the predictor?
(c) [4 marks] Is there evidence that this simple linear regression model with log.disp as the predictor is better than the model containing only an intercept term? State the null and alternative hypothesis of an appropriate F test. Also state the value of the test statistic, the distribution of the test statistic under the null hypothesis, the p-value and the conclusion using a 1% level of significance.
(d) [1 mark] What is the estimated expected change in log.mpg for a one unit change in log.disp? (enter negative number if decreasing)
(e) [1 mark] Obtain a 97% confidence interval for the true slope coefficient in this model.
(f) [1 mark] Obtain a 99% confidence interval for the mean log.mpg when disp is 290 (cu.in.).
Rch27 · 27.1
mpg <- c(20.5,20.3,23.0,20.1,17.3,17.3,13.9,24.2,26.6,19.3,17.5,14.9,18.6,14.7,14.2,12.1,
         15.9,32.0,30.6,31.1,21.4,14.4,14.7,11.6,19.2,28.0,27.4,32.4,13.2,18.9,12.4,22.7)
disp <- c(129.7,152.0,11.6,234.8,328.3,230.1,381.9,146.8,174.5,193.1,147.1,304.3,251.3,
          266.3,442.0,436.4,461.2,43.6,118.2,65.3,79.7,306.4,329.0,336.6,385.7,108.5,
          162.9,101.0,347.3,141.0,292.5,105.7)
log.mpg <- c(3.02,3.01,3.14,3.00,2.85,2.85,2.63,3.19,3.28,2.96,2.86,2.70,2.92,2.69,2.65,
             2.49,2.77,3.47,3.42,3.44,3.06,2.67,2.69,2.45,2.95,3.33,3.31,3.48,2.58,2.94,
             2.52,3.12)
log.disp <- c(4.87,5.02,2.45,5.46,5.79,5.44,5.95,4.99,5.16,5.26,4.99,5.72,5.53,5.58,6.09,
              6.08,6.13,3.78,4.77,4.18,4.38,5.72,5.80,5.82,5.96,4.69,5.09,4.62,5.85,4.95,
              5.68,4.66)
cars <- data.frame(mpg, disp, log.mpg, log.disp)
nrow(cars)      # 应该是 32
✍️ (a) [2 分] 两个模型哪个更合适
Rch27 · 27.2
m_raw <- lm(mpg ~ disp, data = cars)
m21 <- lm(log.mpg ~ log.disp, data = cars)
par(mfrow = c(2, 2)); plot(m_raw); par(mfrow = c(1, 1))
par(mfrow = c(2, 2)); plot(m21); par(mfrow = c(1, 1))

原模型 mpg ~ disp:

2021 Q1 原模型 mpg ~ disp 的四张诊断图
  • Residuals vs Fitted:明显的 U 形(两头残差为正,中间为负)⇒ 线性假设不成立。
  • Scale-Location:红线在拟合值大于 20 以后明显上升 ⇒ 方差随拟合值变大。
  • Normal Q-Q:两端偏离直线(左端变平、右端在线下方,轻尾形状)⇒ 正态性也值得怀疑。

log 模型 log.mpg ~ log.disp:

2021 Q1 log 模型的四张诊断图

和 2023 一样,这里也有一个特别的点:第 3 辆车,disp = 11.6(其他车都在 40–510),取 log 后 log.disp = 2.45,远离其他点。它在 log 模型里杠杆 0.43、标准化残差约 −3.5、Cook's D = 4.57,越过了 Cook's 1 的虚线。三张图右端那段被拉下去的红线都是它造成的。除了这个点,大部分残差在 0 上下随机散开,U 形没有了,Q-Q 图也基本在线上。

可以直接写的答案:

In the model mpg ~ disp, the Residuals vs Fitted plot shows a clear U-shaped pattern (non-linearity) and the Scale-Location plot shows the spread increasing with the fitted values (non-constant variance); the Q-Q plot also departs from the line at both tails. In the log model these problems are largely removed: apart from observation 3 the residuals are randomly scattered around zero with roughly constant spread and the Q-Q plot is close to a straight line. So the log model is better suited. Observation 3 (disp = 11.6) has a high leverage and lies outside the Cook's distance contour of 1 in the log model, so it is influential and should be investigated.

✍️ (b)–(f) [8 分] 全部从 summary、confint、predict 读
Rch27 · 27.3
summary(m21)
confint(m21, "log.disp", level = 0.97)
predict(m21, newdata = data.frame(log.disp = log(290)),
        interval = "confidence", level = 0.99)
Console 输出
Coefficients:
            Estimate Std. Error t value Pr(>|t|)
(Intercept)  4.38377    0.26310  16.662  < 2e-16 ***
log.disp    -0.27539    0.05004  -5.504 5.62e-06 ***
---
Residual standard error: 0.2176 on 30 degrees of freedom
Multiple R-squared:  0.5024,	Adjusted R-squared:  0.4858
F-statistic: 30.29 on 1 and 30 DF,  p-value: 5.617e-06

              1.5 %     98.5 %
log.disp -0.3893795 -0.1613927

       fit      lwr      upr
1 2.822368 2.698533 2.946202
小问答案从哪读 / 为什么
(b) [1]0.5024"proportion of variation explained" 就是 R²(Multiple R-squared),不是 adjusted R²。也可以写 50.24%
(c) [4]H0:β1=0H_0: \beta_1 = 0 vs H1:β1≠0H_1: \beta_1 \ne 0;F = 30.29;F1,30F_{1,30};p = 5.617E-6summary 最后一行。分母 df = n − 2 = 32 − 2 = 30
(c) 结论p-value 5.617e-06 < 0.01, so we reject H0 at the 1% level: there is strong evidence that the model with log.disp is better than the intercept-only model.
(d) [1]−0.27539斜率。log.disp 增加 1,log.mpg 的期望减少 0.275
(e) [1](−0.3894, −0.1614)97%:level = 0.97,两边各留 1.5%,所以 R 的列名是 1.5% 和 98.5%
(f) [1](2.6985, 2.9462)newdata 填 log(290);均值 ⇒ "confidence";99%

和 2023 的区别:多了 (b) 问 R²;置信水平换成了 97% 和 99%,disp 换成 290。每次都看清置信水平,这是 Möbius 最容易白丢的分。

手算 (e):−0.27539±t0.015, 30×0.05004-0.27539 \pm t_{0.015,\,30}\times 0.05004,qt(0.985, 30) = 2.278,得 (−0.3894, −0.1614)。

27.2 Q2 [10 分]:用哑变量检验第 25 个观测

📄 2021 期末 Q2(Möbius)
To answer the following question, load data frame cars from the previous question (Question 1). Fit a simple linear regression model with log.mpg as the response and log.disp as the predictor and answer the following questions. The 25th observation was thought to be suspicious on the basis of prior knowledge. Researcher decided to test whether this observation is an unusual one using indicator variables as described below. Follow the same steps as what the researcher used. To test H0:Δ25=0H_0: \Delta_{25} = 0 against the alternative H1:Δ25≠0H_1: \Delta_{25} \ne 0 in the mean shift outlier model with E(ε25)=Δ25E(\varepsilon_{25}) = \Delta_{25}, construct a new predictor dummy variable which is 1 for the 25th observation and 0 otherwise. Hint: cars$dummy = c(rep(0,24),1,rep(0,7))
(a) [2 marks] Now refit the linear model with this new predictor dummy variable added to the existing predictor log.disp. Obtain R summary output generated by fitting a multiple linear model with log.mpg as the response and log.disp and dummy as the predictors and copy as a text in the box below.
(b) [4 marks] Is the dummy predictor significant according to a partial t-test? State the value of the test statistic, the distribution of the test statistic under the null hypothesis, the p-value and the conclusion using a 1% level of significance in the box below.
(c) [4 marks] Is the above partial t-test in part (b) the same as the test based on the externally studentized residuals discussed in the lectures? State the value of the externally studentized residual for the 25th observation in model with log.mpg as the response and log.disp as the predictor. Find the p-value of an appropriate hypothesis test based on the externally studentized residuals. What R command did you use to find this p-value? Type your answers in the box below.
📚 需要先补:均值漂移离群点模型 和 外学生化残差(第 10、14 章)

哑变量做法:给第 25 个观测单独加一个"挪动量" Δ25\Delta_{25}:

log.mpgi=β0+β1 log.dispi+Δ25 dummyi+εi,dummyi=1 只当 i=25.\text{log.mpg}_i = \beta_0 + \beta_1\,\text{log.disp}_i + \Delta_{25}\,\text{dummy}_i + \varepsilon_i,\qquad \text{dummy}_i = 1 \text{ 只当 } i = 25.

如果第 25 个观测符合模型,就不需要挪,Δ25=0\Delta_{25} = 0。所以检验"是不是离群点"= 检验 dummy 的系数是否为 0 = 一个普通的 partial t 检验。

外学生化残差(Lab Test 学过):ti=eiσ^−i1−hiit_i = \dfrac{e_i}{\hat\sigma_{-i}\sqrt{1 - h_{ii}}},R 里是 rstudent(model)。如果第 i 个观测不是离群点,ti∼tn−p−1t_i \sim t_{n-p-1}(p 是原模型的参数个数)。

关键定理(讲义里证明过):上面 partial t 检验的 t 统计量正好等于 tit_i,自由度也相同(新模型有 p + 1 个参数,残差 df = n − p − 1)。所以两种做法是同一个检验。

✍️ (a) [2 分] 加 dummy 重新拟合,复制 summary
Rch27 · 27.4
cars$dummy <- c(rep(0, 24), 1, rep(0, 7))      # 24 个 0、一个 1、7 个 0,共 32 个
m_dummy <- lm(log.mpg ~ log.disp + dummy, data = cars)
summary(m_dummy)
Console 输出
Call:
lm(formula = log.mpg ~ log.disp + dummy, data = cars)

Residuals:
     Min       1Q   Median       3Q      Max
-0.58657 -0.12023 -0.00934  0.12338  0.37026

Coefficients:
            Estimate Std. Error t value Pr(>|t|)
(Intercept)  4.42299    0.26624  16.613 2.34e-16 ***
log.disp    -0.28425    0.05087  -5.588 4.95e-06 ***
dummy        0.22116    0.22473   0.984    0.333
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 0.2177 on 29 degrees of freedom
Multiple R-squared:  0.5185,	Adjusted R-squared:  0.4853
F-statistic: 15.61 on 2 and 29 DF,  p-value: 2.498e-05

整个输出复制进答题框。

✍️ (b) [4 分] dummy 显著吗(1% 水平)

The partial t statistic for dummy is t = 0.984. Under H0: Δ25 = 0 it follows a t distribution with 29 degrees of freedom (n − 3 = 32 − 3). The p-value is 0.333 > 0.01, so we do not reject H0 at the 1% level: the dummy predictor is not significant and there is no evidence that the 25th observation is an outlier.

四样东西各约 1 分:t = 0.984、t29t_{29}、p = 0.333、结论。用临界值也行:qt(0.995, 29) = 2.756,|0.984| < 2.756。

✍️ (c) [4 分] 和外学生化残差的检验是同一个吗
Rch27 · 27.4
t25 <- rstudent(m21)[25]; t25                  # 原模型(没有 dummy)的外学生化残差
2 * pt(-abs(t25), df = 32 - 2 - 1)            # 双侧 p 值,df = n - p - 1 = 29
Console 输出
       25
0.9841012
       25
0.3332054

可以直接写的答案:

Yes, it is the same test. The externally studentized residual for the 25th observation in the model log.mpg ~ log.disp is t25t_{25} = 0.9841, which is exactly the t statistic of the dummy variable in part (b). Under H0 (the 25th observation is not an outlier) t25∼tn−p−1=t32−2−1=t29t_{25} \sim t_{n-p-1} = t_{32-2-1} = t_{29}, and the two-sided p-value is 0.3332, the same as in part (b). R command: 2*pt(-abs(rstudent(m21)[25]), df = 29) (equivalently 2*(1-pt(abs(rstudent(m21)[25]), 29))).

得分点:说"是同一个"+ t25t_{25} 的值 + p 值 + R 命令,各 1 分。

坑:① 用的是原模型(没有 dummy)的 rstudent;② df 是 n − p − 1 = 29,不是 30;③ 双侧检验要乘 2,而且用 -abs(...) 保证取的是尾部概率。

27.3 Q3 [10 分]:多元回归的 F 检验家族 + 预测区间

📄 2021 期末 Q3(Möbius)
To answer the following question, copy and paste the data below into RStudio and create a data frame mpg. […] A multiple linear regression model was fitted with mpg as the response and the remaining variables as predictors. The variables wt, cyl, disp and hp in the regression output below refer to weight, number of cylinders, displacement and gross horsepower respectively. Obtain R summary and anova outputs generated by fitting a multiple linear regression model with mpg as the response and wt, cyl, disp and hp as the predictors, and answer the following questions.
(a) [3 marks] State whether you think that this linear regression model is better than the model containing only an intercept term. You should refer to an appropriate hypothesis test to support your answer: state the null and alternative hypothesis, the value of the test statistic, the distribution of the test statistic under the null hypothesis, and the conclusion of the test at the 5% level of significance.
(b) [3 marks] It was felt that weight (wt) should be included in any model for mpg, but that the other three predictors, number of cylinders (cyl), displacement (disp) and gross horsepower (hp) might not be related to mpg in the model involving weight. Perform a hypothesis test to compare the model involving all four predictors to the model including only weight (wt). State the null and alternative hypothesis, the value of the test statistic, the distribution of the test statistic under the null hypothesis and the conclusion of the test at the 5% level of significance.
(c) [3 marks] Perform a hypothesis test to compare the model involving weight (wt) and displacement (disp) to the model involving only weight (wt). State the null and alternative hypothesis, the value of the test statistic, the distribution of the test statistic under the null hypothesis and the conclusion of the test at the 5% level of significance.
(d) [1 mark] Obtain a 92% prediction interval for the fuel consumption in mpg when the weight of a car is 3.8 (in 1000 lbs), it has 6 cylinders and the displacement equals 220 (cu.in.) with gross horsepower of 160.
Rch27 · 27.5
mpg <- c(21.9,21.3,21.6,21.2,18.0,17.3,17.2,22.6,18.5,19.2,16.3,17.6,14.4,16.5,10.5,12.8,
         14.0,32.8,28.7,33.4,24.0,14.8,14.2,11.5,17.8,27.9,29.8,29.8,13.0,19.9,16.2,21.8)
wt <- c(2.740,2.915,2.154,3.185,3.340,3.350,3.950,2.952,2.580,3.444,3.244,4.230,3.346,
        3.958,5.260,5.742,5.251,2.248,1.383,1.763,2.793,3.428,3.299,3.606,3.663,2.017,
        2.642,1.437,2.800,2.790,3.724,2.828)
disp <- c(178.0,166.0,83.1,253.5,345.0,208.5,417.0,111.0,55.3,168.2,138.2,299.8,218.2,
          302.5,473.5,507.7,425.9,85.9,40.9,60.3,169.3,304.2,283.6,314.9,372.7,91.3,195.6,
          83.7,295.5,148.0,324.1,128.2)
cyl <- c(6,6,4,6,8,6,8,4,4,6,6,8,8,8,8,8,8,4,4,4,4,8,8,8,8,4,4,4,8,6,8,4)
hp <- c(110,110,93,110,175,105,245,62,95,123,123,180,180,180,205,215,230,66,52,65,97,
        150,150,245,175,66,91,113,264,175,335,109)
mpg <- data.frame(mpg, wt, cyl, disp, hp)
full <- lm(mpg ~ wt + cyl + disp + hp, data = mpg)
summary(full)
anova(full)
Console 输出
            Estimate Std. Error t value Pr(>|t|)
(Intercept) 43.67842    3.18573  13.711 1.11e-13 ***
wt          -4.06476    1.22240  -3.325  0.00255 **
cyl         -2.39820    0.70630  -3.395  0.00214 **
disp         0.02960    0.01275   2.321  0.02806 *
hp          -0.01834    0.01480  -1.239  0.22588
Residual standard error: 3.029 on 27 degrees of freedom
Multiple R-squared:  0.7888,	Adjusted R-squared:  0.7575
F-statistic: 25.21 on 4 and 27 DF,  p-value: 8.912e-09

          Df Sum Sq Mean Sq F value    Pr(>F)
wt         1 704.42  704.42 76.7758 2.232e-09 ***
cyl        1 166.84  166.84 18.1843 0.0002192 ***
disp       1  39.80   39.80  4.3379 0.0468734 *
hp         1  14.09   14.09  1.5360 0.2258820
Residuals 27 247.73    9.18
✍️ (a) [3 分] overall F 检验

H0:β1=β2=β3=β4=0H_0: \beta_1 = \beta_2 = \beta_3 = \beta_4 = 0 vs H1H_1: at least one βj≠0\beta_j \ne 0;F = 25.21;F4,27F_{4,27};p = 8.912E-9。

Since the p-value < 0.05, we reject H0: at least one predictor is related to mpg, so this model is better than the intercept-only model.

✍️ (b) [3 分] 全模型 vs 只有 wt
Rch27 · 27.6
m_wt <- lm(mpg ~ wt, data = mpg)
anova(m_wt, full)
Console 输出
  Res.Df    RSS Df Sum of Sq      F    Pr(>F)
1     30 468.46
2     27 247.73  3    220.74 8.0194 0.0005578 ***

H0:βcyl=βdisp=βhp=0H_0: \beta_{cyl} = \beta_{disp} = \beta_{hp} = 0 vs H1H_1: at least one of them ≠0\ne 0;F = 8.0194;F3,27F_{3,27};p = 0.0005578。

p-value < 0.05, reject H0: at least one of cyl, disp, hp is related to mpg in the model that already contains wt, so the full model is preferred.

手算核对:F=(468.46−247.73)/3247.73/27=73.589.175=8.02F = \dfrac{(468.46 - 247.73)/3}{247.73/27} = \dfrac{73.58}{9.175} = 8.02。也等于 anova(full) 里 cyl、disp、hp 三行 Sum Sq 之和 166.84 + 39.80 + 14.09 = 220.73 除以 3、再除以 9.18。

✍️ (c) [3 分] wt + disp vs 只有 wt
Rch27 · 27.6
anova(m_wt, lm(mpg ~ wt + disp, data = mpg))
Console 输出
  Res.Df    RSS Df Sum of Sq      F Pr(>F)
1     30 468.46
2     29 456.02  1    12.439 0.7911 0.3811

H0:βdisp=0H_0: \beta_{disp} = 0(在只含 wt 和 disp 的模型里)vs H1:βdisp≠0H_1: \beta_{disp} \ne 0;F = 0.7911;F1,29F_{1,29};p = 0.3811。

p-value 0.3811 > 0.05, so we do not reject H0: once weight is in the model, displacement does not significantly improve the fit; the model with wt only is adequate compared with wt + disp.

最大的坑:这里的"大模型"是 wt + disp,不是全模型,所以分母 df = 32 − 3 = 29,要重新拟合 lm(mpg ~ wt + disp)。不能用 anova(full) 里 disp 那一行(那一行是在 wt 和 cyl 之后加 disp,而且分母用的是全模型的 MSE),也不能用 summary(full) 里 disp 的 t 检验(那是在其他三个都在的情况下)。

有意思的对比:在全模型里 disp 是显著的(p = 0.028),但在只有 wt 的模型里加 disp 不显著。同一个变量有没有用,取决于模型里已经有谁,这就是为什么检验时一定要说清楚"在哪个模型里"。

✍️ (d) [1 分] 92% 预测区间
Rch27 · 27.6
predict(full, newdata = data.frame(wt = 3.8, cyl = 6, disp = 220, hp = 160),
        interval = "prediction", level = 0.92)
Console 输出
       fit      lwr      upr
1 17.42047 11.60024 23.24071

填 (11.6002, 23.2407)。"prediction"、0.92 两个参数都别漏;wt 是 3.8(2023 是 3.6)。

27.4 Q4 [15 分]:用 b=β+Sεb = \beta + S\varepsilon 证明无偏性(手写)

📄 2021 期末 Q4
Consider the general linear model y=Xβ+εy = X\beta + \varepsilon, where as usual y is an n × 1 vector of responses, X is an n × p design matrix and ε is a vector of zero mean errors uncorrelated with variance σ² and the least squares estimate of β given by b=(X⊤X)−1X⊤yb = (X^\top X)^{-1}X^\top y.
(a) [2 marks] Show that we can write b in the form b=β+Sεb = \beta + S\varepsilon, where S=(X⊤X)−1X⊤S = (X^\top X)^{-1}X^\top. Using this form, show that b=Syb = Sy is an unbiased estimator of β.
(b) [4 marks] Use the representation of b from part (a) to find the covariance matrix of b in terms of the error variance and matrix S. (Hint: Covariance matrix of a random vector z is Var(z)=E[(z−E(z))(z−E(z))⊤]\mathrm{Var}(z) = E[(z - E(z))(z - E(z))^\top].)
(c) [4 marks] Using part (a), show that we can write the residual sum of squares (y−Xb)⊤(y−Xb)(y - Xb)^\top(y - Xb) in the form ε⊤(I−XS)ε\varepsilon^\top(I - XS)\varepsilon, where I denotes the n × n identity matrix.
(d) [5 marks] Apply the results from parts (a) and (c) to show that the usual estimator of σ² in the general linear model σ^2=(y−Xb)⊤(y−Xb)n−p\hat\sigma^2 = \dfrac{(y - Xb)^\top(y - Xb)}{n - p} is unbiased. (Hint: use the formula for E(ε⊤Aε)E(\varepsilon^\top A\varepsilon).)
📚 需要的矩阵工具(第 5、11 章)
  • "uncorrelated with variance σ²" 写成矩阵:E(ε)=0E(\varepsilon) = 0,Var(ε)=E(εε⊤)=σ2I\mathrm{Var}(\varepsilon) = E(\varepsilon\varepsilon^\top) = \sigma^2 I(对角线是方差 σ²,非对角线是协方差 0)。
  • 常数矩阵可以穿过期望:E(Az)=A E(z)E(A z) = A\,E(z),E(AZB)=A E(Z) BE(A Z B) = A\,E(Z)\,B。
  • 转置规则 (AB)⊤=B⊤A⊤(AB)^\top = B^\top A^\top;(X⊤X)−1(X^\top X)^{-1} 对称。
  • SX=(X⊤X)−1X⊤X=IpSX = (X^\top X)^{-1}X^\top X = I_p(p × p 单位矩阵),这是全题最常用的一步。
  • E(ε⊤Aε)=tr(A Var(ε))+E(ε)⊤A E(ε)E(\varepsilon^\top A\varepsilon) = \mathrm{tr}(A\,\mathrm{Var}(\varepsilon)) + E(\varepsilon)^\top A\,E(\varepsilon)(formula sheet 有)。
  • 迹的性质:tr(A+B)=tr(A)+tr(B)\mathrm{tr}(A + B) = \mathrm{tr}(A) + \mathrm{tr}(B),tr(cA)=c tr(A)\mathrm{tr}(cA) = c\,\mathrm{tr}(A),tr(AB)=tr(BA)\mathrm{tr}(AB) = \mathrm{tr}(BA)(乘法顺序可以"转一圈")。
✍️ (a) [2 分] b=β+Sεb = \beta + S\varepsilon,且无偏

把 y=Xβ+εy = X\beta + \varepsilon 代入 b=Syb = Sy,展开:

b=Sy=S(Xβ+ε)=(X⊤X)−1X⊤X⏟= I β+Sε=β+Sε.b = Sy = S(X\beta + \varepsilon) = \underbrace{(X^\top X)^{-1}X^\top X}_{=\,I}\,\beta + S\varepsilon = \beta + S\varepsilon.

取期望(β、S 都是常数,E(ε)=0E(\varepsilon) = 0):

E(b)=β+S E(ε)=β+S⋅0=β.E(b) = \beta + S\,E(\varepsilon) = \beta + S\cdot 0 = \beta.

所以 b 是 β 的无偏估计。各 1 分。

✍️ (b) [4 分] Var(b)=σ2SS⊤\mathrm{Var}(b) = \sigma^2SS^\top

按提示的定义,E(b)=βE(b) = \beta,所以 b−E(b)=Sεb - E(b) = S\varepsilon:

Var(b)=E[(b−β)(b−β)⊤]=E[Sε (Sε)⊤]=E[S εε⊤S⊤]=S E(εε⊤) S⊤=S (σ2I) S⊤=σ2 SS⊤.\begin{aligned} \mathrm{Var}(b) &= E\big[(b - \beta)(b - \beta)^\top\big] = E\big[S\varepsilon\,(S\varepsilon)^\top\big] = E\big[S\,\varepsilon\varepsilon^\top S^\top\big]\\ &= S\,E(\varepsilon\varepsilon^\top)\,S^\top = S\,(\sigma^2 I)\,S^\top = \sigma^2\,SS^\top. \end{aligned}

每一步的理由:(Sε)⊤=ε⊤S⊤(S\varepsilon)^\top = \varepsilon^\top S^\top(转置规则);S 是常数矩阵,可以提到期望外面;E(εε⊤)=Var(ε)=σ2IE(\varepsilon\varepsilon^\top) = \mathrm{Var}(\varepsilon) = \sigma^2 I 因为 E(ε)=0E(\varepsilon) = 0。

(可以再化简一步,加分)SS⊤=(X⊤X)−1X⊤X(X⊤X)−1=(X⊤X)−1SS^\top = (X^\top X)^{-1}X^\top X(X^\top X)^{-1} = (X^\top X)^{-1},所以 Var(b)=σ2(X⊤X)−1\mathrm{Var}(b) = \sigma^2(X^\top X)^{-1},和讲义的结果一致。题目要求"in terms of σ² and S",所以写到 σ2SS⊤\sigma^2SS^\top 就已经满分。

✍️ (c) [4 分] RSS =ε⊤(I−XS)ε= \varepsilon^\top(I - XS)\varepsilon

第 1 步:残差向量。用 (a) 的 b=β+Sεb = \beta + S\varepsilon:

y−Xb=Xβ+ε−X(β+Sε)=Xβ+ε−Xβ−XSε=(I−XS)ε.y - Xb = X\beta + \varepsilon - X(\beta + S\varepsilon) = X\beta + \varepsilon - X\beta - XS\varepsilon = (I - XS)\varepsilon.

第 2 步:平方和:

(y−Xb)⊤(y−Xb)=ε⊤(I−XS)⊤(I−XS) ε.(y - Xb)^\top(y - Xb) = \varepsilon^\top(I - XS)^\top(I - XS)\,\varepsilon.

第 3 步:证明 (I−XS)⊤(I−XS)=I−XS(I - XS)^\top(I - XS) = I - XS。

  • 对称:(XS)⊤=(X(X⊤X)−1X⊤)⊤=X(X⊤X)−1X⊤=XS(XS)^\top = \big(X(X^\top X)^{-1}X^\top\big)^\top = X(X^\top X)^{-1}X^\top = XS,所以 (I−XS)⊤=I−XS(I - XS)^\top = I - XS。
  • 幂等:(I−XS)(I−XS)=I−2XS+XSX⏟= IS=I−2XS+XS=I−XS(I - XS)(I - XS) = I - 2XS + X\underbrace{SX}_{=\,I}S = I - 2XS + XS = I - XS。

所以 (y−Xb)⊤(y−Xb)=ε⊤(I−XS)ε(y - Xb)^\top(y - Xb) = \varepsilon^\top(I - XS)\varepsilon。∎

(XSXS 就是帽子矩阵 H,所以这一步其实是"I−HI - H 对称且幂等"。)

✍️ (d) [5 分] σ^2\hat\sigma^2 无偏

第 1 步:套公式,A=I−XSA = I - XS,E(ε)=0E(\varepsilon) = 0,Var(ε)=σ2I\mathrm{Var}(\varepsilon) = \sigma^2 I:

E[ε⊤(I−XS)ε]=tr((I−XS) σ2I)+0⊤(I−XS) 0=σ2 tr(I−XS).E\big[\varepsilon^\top(I - XS)\varepsilon\big] = \mathrm{tr}\big((I - XS)\,\sigma^2 I\big) + 0^\top(I - XS)\,0 = \sigma^2\,\mathrm{tr}(I - XS).

第 2 步:算迹。注意 I 是 n × n,迹是 n:

tr(In−XS)=tr(In)−tr(X(X⊤X)−1X⊤)=n−tr((X⊤X)−1X⊤X)=n−tr(Ip)=n−p.\mathrm{tr}(I_n - XS) = \mathrm{tr}(I_n) - \mathrm{tr}\big(X(X^\top X)^{-1}X^\top\big) = n - \mathrm{tr}\big((X^\top X)^{-1}X^\top X\big) = n - \mathrm{tr}(I_p) = n - p.

中间一步用 tr(AB)=tr(BA)\mathrm{tr}(AB) = \mathrm{tr}(BA),取 A=XA = X、B=(X⊤X)−1X⊤B = (X^\top X)^{-1}X^\top:把 X 从最前面"转"到最后面,得到 p × p 的单位矩阵,迹是 p。

第 3 步:结论。由 (c):

E(σ^2)=E[(y−Xb)⊤(y−Xb)]n−p=σ2(n−p)n−p=σ2.E(\hat\sigma^2) = \frac{E\big[(y - Xb)^\top(y - Xb)\big]}{n - p} = \frac{\sigma^2(n - p)}{n - p} = \sigma^2.

所以 σ^2\hat\sigma^2 是 σ² 的无偏估计。

得分点:套公式并写出 Var(ε) = σ²I(2 分);迹 = n − p 并说明用了 tr(AB) = tr(BA)(2 分);结论(1 分)。

Rch27 · 27.7:模拟验证(考试不用)
set.seed(4)
n <- 20; X <- cbind(1, runif(n, 0, 10), runif(n, 0, 5)); beta <- c(1, 2, -1); sigma <- 2
S <- solve(t(X) %*% X) %*% t(X)
sims <- replicate(20000, {
  eps <- rnorm(n, sd = sigma); y <- X %*% beta + eps
  b <- S %*% y
  c(b, sum((y - X %*% b)^2) / (n - 3))
})
rowMeans(sims)           # 前三个 ≈ beta = (1, 2, -1),最后一个 ≈ sigma^2 = 4
Console 输出
[1]  0.9926575  2.0004237 -0.9987113  3.9930384

27.5 Q5 [15 分]:无截距模型的 OLS 和 WLS(手写)

📄 2021 期末 Q5
Consider the simple linear regression model with no intercept yi=βxi+εiy_i = \beta x_i + \varepsilon_i, i = 1, …, n, (1) where εi\varepsilon_i are uncorrelated errors with zero mean and common variance σ².
(a) [3 marks] Show that the least squares estimate of β is given by b=∑i=1nxiyi∑i=1nxi2b = \dfrac{\sum_{i=1}^n x_iy_i}{\sum_{i=1}^n x_i^2}. Show that E(b)=βE(b) = \beta and Var(b)=σ2/∑i=1nxi2\mathrm{Var}(b) = \sigma^2/\sum_{i=1}^n x_i^2.
Suppose now that in the model (1), the errors εi\varepsilon_i are uncorrelated with zero mean, but the error variance is not constant and it is given by Var(εi)=σ2ki\mathrm{Var}(\varepsilon_i) = \dfrac{\sigma^2}{k_i} for some positive weights kik_i, i = 1, …, n.
(b) [2 marks] Find the weighted least squares estimate bwb_w of β by minimizing Sw(β)=∑i=1nki(yi−βxi)2S_w(\beta) = \sum_{i=1}^n k_i(y_i - \beta x_i)^2 with respect to β.
(c) [3 marks] Find the maximum likelihood estimator (mle) of β if, in addition, the errors εi\varepsilon_i are normally distributed. Does the mle of β coincide with bwb_w from part (b)?
(d) [2 marks] Find E(bw)E(b_w) and Var(bw)\mathrm{Var}(b_w) for the estimate bwb_w obtained in part (b).
(e) [5 marks] Multiply both sides of the equation (1) by ki\sqrt{k_i} and get ki yi=ki βxi+ki εi\sqrt{k_i}\,y_i = \sqrt{k_i}\,\beta x_i + \sqrt{k_i}\,\varepsilon_i. Denote ynew,i=ki yiy_{new,i} = \sqrt{k_i}\,y_i, xnew,i=ki xix_{new,i} = \sqrt{k_i}\,x_i and εnew,i=ki εi\varepsilon_{new,i} = \sqrt{k_i}\,\varepsilon_i. Show that the errors εnew,i\varepsilon_{new,i} are uncorrelated with zero mean and common variance σ², therefore ynew,i=βxnew,i+εnew,iy_{new,i} = \beta x_{new,i} + \varepsilon_{new,i}, i = 1, …, n, (2) is the ordinary least squares regression model. Find the least squares estimate for β for the model (2) and confirm that it is equal to the weighted least squares estimate bwb_w from part (b).

这道题和 2023 Q3 几乎一模一样(权重叫 kik_i 而不是 rir_i,小问顺序不同)。区别是:2021 多了 (a) 普通 OLS;2023 多了 (f) 特例。下面把每一问写完整,详细的每一步解释见第 26 章 Q3。

✍️ (a) [3 分] 普通最小二乘估计及其期望、方差

推导:S(β)=∑(yi−βxi)2S(\beta) = \sum(y_i - \beta x_i)^2,

dSdβ=−2∑xi(yi−βxi)=−2∑xiyi+2β∑xi2=0 ⇒ b=∑xiyi∑xi2,\frac{dS}{d\beta} = -2\sum x_i(y_i - \beta x_i) = -2\sum x_iy_i + 2\beta\sum x_i^2 = 0 \ \Rightarrow\ b = \frac{\sum x_iy_i}{\sum x_i^2},

二阶导 2∑xi2>02\sum x_i^2 > 0,是最小值。

期望:E(yi)=βxiE(y_i) = \beta x_i,

E(b)=∑xi E(yi)∑xi2=∑xi⋅βxi∑xi2=β.E(b) = \frac{\sum x_i\,E(y_i)}{\sum x_i^2} = \frac{\sum x_i\cdot\beta x_i}{\sum x_i^2} = \beta.

方差:yiy_i 互不相关,Var(yi)=σ2\mathrm{Var}(y_i) = \sigma^2,把 b 看成 ∑ciyi\sum c_iy_i,ci=xi/∑xj2c_i = x_i/\sum x_j^2:

Var(b)=∑ci2 σ2=∑xi2(∑xj2)2 σ2=σ2∑xi2.\mathrm{Var}(b) = \sum c_i^2\,\sigma^2 = \frac{\sum x_i^2}{\big(\sum x_j^2\big)^2}\,\sigma^2 = \frac{\sigma^2}{\sum x_i^2}.
✍️ (b) [2 分] WLS 估计
dSwdβ=−2∑kixi(yi−βxi)=0 ⇒ bw=∑i=1nkixiyi∑i=1nkixi2.\frac{dS_w}{d\beta} = -2\sum k_ix_i(y_i - \beta x_i) = 0\ \Rightarrow\ b_w = \frac{\sum_{i=1}^n k_ix_iy_i}{\sum_{i=1}^n k_ix_i^2}.

二阶导 2∑kixi2>02\sum k_ix_i^2 > 0。

✍️ (c) [3 分] MLE

正态 + 不相关 ⇒ 独立,yi∼N(βxi,σ2/ki)y_i \sim N(\beta x_i, \sigma^2/k_i):

log⁡L(β)=const−12σ2∑i=1nki(yi−βxi)2=const−Sw(β)2σ2,\log L(\beta) = \text{const} - \frac{1}{2\sigma^2}\sum_{i=1}^n k_i(y_i - \beta x_i)^2 = \text{const} - \frac{S_w(\beta)}{2\sigma^2},

const 不含 β。最大化 log L ⇔ 最小化 Sw(β)S_w(\beta),所以 β^MLE=bw\hat\beta_{\text{MLE}} = b_w。Yes, they coincide.(似然的完整写法见第 26 章 Q3 (c)。)

✍️ (d) [2 分] E(bw)E(b_w)、Var(bw)\mathrm{Var}(b_w)
E(bw)=∑kixi⋅βxi∑kixi2=β,Var(bw)=∑ki2xi2⋅σ2/ki(∑kixi2)2=σ2∑kixi2.E(b_w) = \frac{\sum k_ix_i\cdot\beta x_i}{\sum k_ix_i^2} = \beta,\qquad \mathrm{Var}(b_w) = \frac{\sum k_i^2x_i^2\cdot\sigma^2/k_i}{\big(\sum k_ix_i^2\big)^2} = \frac{\sigma^2}{\sum k_ix_i^2}.

方差一步用了 yiy_i 不相关。和 (a) 比:ki≡1k_i \equiv 1 时就回到 OLS 的结果。

✍️ (e) [5 分] 变换成 OLS 模型,并验证估计相同

误差满足 OLS 假设(ki\sqrt{k_i} 是常数):

  • E(εnew,i)=ki E(εi)=0E(\varepsilon_{new,i}) = \sqrt{k_i}\,E(\varepsilon_i) = 0;
  • Var(εnew,i)=ki Var(εi)=ki⋅σ2/ki=σ2\mathrm{Var}(\varepsilon_{new,i}) = k_i\,\mathrm{Var}(\varepsilon_i) = k_i\cdot\sigma^2/k_i = \sigma^2,对所有 i 相同;
  • i≠ji \ne j:Cov(εnew,i,εnew,j)=kikj Cov(εi,εj)=0\mathrm{Cov}(\varepsilon_{new,i}, \varepsilon_{new,j}) = \sqrt{k_ik_j}\,\mathrm{Cov}(\varepsilon_i, \varepsilon_j) = 0。

所以 (2) 是普通无截距模型。用 (a) 的公式(把 x、y 换成新变量):

β^=∑xnew,i ynew,i∑xnew,i2=∑kixikiyi∑kixi2=∑kixiyi∑kixi2=bw.\hat\beta = \frac{\sum x_{new,i}\,y_{new,i}}{\sum x_{new,i}^2} = \frac{\sum\sqrt{k_i}x_i\sqrt{k_i}y_i}{\sum k_ix_i^2} = \frac{\sum k_ix_iy_i}{\sum k_ix_i^2} = b_w.

得分点:三条性质各 1 分;估计 1 分;"等于 bwb_w"1 分。注意 (a) 的结论在这里直接拿来用,这就是 (a) 先让你推 OLS 的原因。

27.6 Q6 [15 分]:影响点和 DFFITS

📄 2021 期末 Q6
PART I. A linear model is fitted to data with response y and predictor x. Answer parts (a), (b) and (c) with the help of R outputs produced after fitting this model. Figure 1 shows two plots. The first one is a diagnostic plot for the fitted model. The second plot shows a scatterplot of the data together with the fitted regression line (black line), as well as the fitted line (red line) to the data without the ith observation. The observation (xi,yi)(x_i, y_i) which was removed from the data has been identified as a potential influential observation on the first plot.
(a) [3 marks] After examining the plots, identify the potential influential observation. Write a few sentences, commenting on both plots, to give your reasons.
(b) [2 marks] Recall that the ith DFFITS value is defined as DFFITSi=y^i−y^i,−iσ^−ihii\text{DFFITS}_i = \dfrac{\hat y_i - \hat y_{i,-i}}{\hat\sigma_{-i}\sqrt{h_{ii}}} (1). Use the definitions given in lectures to explain in words what does the numerator in (1) y^i−y^i,−i\hat y_i - \hat y_{i,-i} represent. Copy the second plot of Figure 1 in your answer book (draw it by hand) and show on the plot the change y^i−y^i,−i\hat y_i - \hat y_{i,-i}, where ith observation was identified as influential in part (a).
(c) [2 marks] Given the following R output: [hatvalues(model) and rstudent(model) for 15 observations, see below] calculate DFFITSi\text{DFFITS}_i for the observation identified as influential in part (a) using the following formula DFFITSi=tihii1−hii\text{DFFITS}_i = t_i\sqrt{\dfrac{h_{ii}}{1 - h_{ii}}}. Based on this value of DFFITSi\text{DFFITS}_i and using rule of thumb from lectures, comment whether or not the identified observation is influential.
PART II. Consider now the full rank general linear model y=Xβ+εy = X\beta + \varepsilon (with usual assumptions discussed in lectures) and answer parts (d), (e) and (f). In your answers, you can make use of the following result (you are not asked to prove this): b−i=b−(X⊤X)−1xiei1−hiib_{-i} = b - \dfrac{(X^\top X)^{-1}x_ie_i}{1 - h_{ii}} (2), where b−ib_{-i} denotes the least squares estimate of β obtained by fitting the model without the i-th observation, xi⊤x_i^\top is the ith row of design matrix X, eie_i is the ith raw residual and hiih_{ii} is the ith leverage.
(d) [1 mark] Explain in words why we can express y^i\hat y_i and y^i,−i\hat y_{i,-i} as y^i=xi⊤b\hat y_i = x_i^\top b and y^i,−i=xi⊤b−i\hat y_{i,-i} = x_i^\top b_{-i}?
(e) [5 marks] Show that y^i−y^i,−i=hiiei1−hii\hat y_i - \hat y_{i,-i} = \dfrac{h_{ii}e_i}{1 - h_{ii}} and hence find E(y^i−y^i,−i)E(\hat y_i - \hat y_{i,-i}) and Var(y^i−y^i,−i)\mathrm{Var}(\hat y_i - \hat y_{i,-i}).
(f) [2 marks] Show that DFFITSi\text{DFFITS}_i, defined in (1), is equal to DFFITSi=tihii1−hii\text{DFFITS}_i = t_i\sqrt{\dfrac{h_{ii}}{1 - h_{ii}}}, where tit_i is the ith externally studentized residual.

Figure 1(原卷截图):

2021 Q6 Figure 1:Residuals vs Leverage 图和带两条拟合线的散点图

题目给的输出(15 个观测):

> hatvalues(model)
         1          2          3          4          5          6          7          8
0.10810719 0.09671217 0.26150336 0.09013108 0.07723297 0.07526270 0.07349556 0.18545526
         9         10         11         12         13         14         15
0.06699572 0.07136280 0.07453147 0.21955909 0.26507827 0.23572744 0.09884492
> rstudent(model)
         1          2          3          4          5          6          7          8
 0.1866793 -0.3443789  1.5798615 -0.2085149 -0.4995792 -0.1905082  0.4625887  0.6590486
         9         10         11         12         13         14         15
-0.4356538  1.3459058 -0.9486411  1.1671205 -0.2639845 -4.5839057  0.5313462
✍️ (a) [3 分] 找出影响点,两张图都要评论

怎么读第一张图(读法见第 25 章 25.4):横轴杠杆、纵轴标准化残差,红色虚线是 Cook's distance = 0.5 和 1 的等高线。14 号在右下角:杠杆约 0.24(偏高),标准化残差约 −2.9(很大),而且在 Cook's 1 的虚线外面。3 号、12 号杠杆也高,但残差不大,没越过虚线。

怎么读第二张图:黑线 = 用全部数据拟合,红线 = 去掉 14 号以后拟合。14 号是左下角那个点(x ≈ 1.5,y ≈ 0.7),远低于其他点的趋势。它把黑线的左端往下拽,所以黑线比红线平很多:一个点就明显改变了斜率。

可以直接写的答案:

Observation 14 is the potential influential observation. In the Residuals vs Leverage plot it has a large negative standardized residual (about −2.9) together with a relatively high leverage (about 0.24), and it lies outside the Cook's distance contour of 1, so its Cook's distance is greater than 1. In the scatterplot, the fitted line without observation 14 (red) is much steeper than the fitted line using all data (black): this single point (at x ≈ 1.5 with a very small y) pulls the left end of the line down and changes the slope considerably. Hence observation 14 is influential.

得分点:指出 14 号(1 分);第一张图的理由:大残差 + 高杠杆 + 越过 Cook's 线(1 分);第二张图的理由:两条线差很多(1 分)。题目要求"commenting on both plots",只说一张图会丢分。

✍️ (b) [2 分] 分子的含义 + 在图上画出来

y^i\hat y_i is the fitted value at xix_i from the model fitted to all the data, and y^i,−i\hat y_{i,-i} is the predicted value at xix_i from the model fitted without the i-th observation. So y^i−y^i,−i\hat y_i - \hat y_{i,-i} is the change in the fitted value at the i-th point caused by deleting the i-th observation.

怎么画:在答题本上照着画出散点图和两条线。在 14 号点的横坐标 x14≈1.5x_{14} \approx 1.5 处画一条竖线段,从黑线上的点(y^14\hat y_{14},约 3.3)连到红线上的点(y^14,−14\hat y_{14,-14},约 4.1),标上 "y^14−y^14,−14\hat y_{14} - \hat y_{14,-14}"。这段长度约 −0.8(黑线在红线下面,所以是负的)。

常见错误:画成从点到线的距离(那是残差),或者画在别的 x 处。必须是同一个 x = x₁₄ 处、两条线之间的竖直距离。

✍️ (c) [2 分] 手算 DFFITS₁₄

从输出里读 14 号:h14,14=0.23572744h_{14,14} = 0.23572744,t14=−4.5839057t_{14} = -4.5839057。

DFFITS14=t14h14,141−h14,14=−4.5839×0.235730.76427=−4.5839×0.5554=−2.546.\text{DFFITS}_{14} = t_{14}\sqrt{\frac{h_{14,14}}{1 - h_{14,14}}} = -4.5839\times\sqrt{\frac{0.23573}{0.76427}} = -4.5839\times 0.5554 = -2.546.

|DFFITS₁₄| = 2.55 > 2, so by the rule of thumb from lectures (|DFFITS| > 2 is large) observation 14 is influential: deleting it changes its fitted value by about 2.5 standard errors.

(有的教材用 2p/n=22/15=0.732\sqrt{p/n} = 2\sqrt{2/15} = 0.73 当界限,结论一样。讲义用的是 2。)

计算器步骤:先算 0.23573 ÷ 0.76427 = 0.30844,开方 0.55537,再乘 −4.58391。

✍️ (d)(e)(f) [1 + 5 + 2 分] 和 2023 Q4 (d)(e)(f) 完全相同

(d) A fitted value is obtained by plugging the predictor values of the i-th observation, xi⊤x_i^\top (the i-th row of X), into the estimated regression equation. With all the data the coefficient estimate is b, so y^i=xi⊤b\hat y_i = x_i^\top b; with the i-th observation deleted the estimate is b−ib_{-i}, evaluated at the same xix_i, so y^i,−i=xi⊤b−i\hat y_{i,-i} = x_i^\top b_{-i}.

(e) 证明:

y^i−y^i,−i=xi⊤(b−b−i)=(2)xi⊤(X⊤X)−1xi ei1−hii=hiiei1−hii.\hat y_i - \hat y_{i,-i} = x_i^\top(b - b_{-i}) \overset{(2)}{=} \frac{x_i^\top(X^\top X)^{-1}x_i\,e_i}{1 - h_{ii}} = \frac{h_{ii}e_i}{1 - h_{ii}}.

由 e=(I−H)ye = (I - H)y:E(e)=(I−H)Xβ=0E(e) = (I - H)X\beta = 0,Var(e)=σ2(I−H)\mathrm{Var}(e) = \sigma^2(I - H),所以 E(ei)=0E(e_i) = 0,Var(ei)=σ2(1−hii)\mathrm{Var}(e_i) = \sigma^2(1 - h_{ii})。于是

E(y^i−y^i,−i)=hii1−hiiE(ei)=0,Var(y^i−y^i,−i)=hii2(1−hii)2 σ2(1−hii)=σ2hii21−hii.E(\hat y_i - \hat y_{i,-i}) = \frac{h_{ii}}{1 - h_{ii}}E(e_i) = 0,\qquad \mathrm{Var}(\hat y_i - \hat y_{i,-i}) = \frac{h_{ii}^2}{(1 - h_{ii})^2}\,\sigma^2(1 - h_{ii}) = \frac{\sigma^2h_{ii}^2}{1 - h_{ii}}.

2021 这一问是 5 分(2023 是 4 分),所以 E(ei)E(e_i)、Var(ei)\mathrm{Var}(e_i) 的来历一定要写出来。

(f)

DFFITSi=hiiei(1−hii) σ^−ihii=eiσ^−i1−hii⋅hii1−hii=tihii1−hii.\text{DFFITS}_i = \frac{h_{ii}e_i}{(1 - h_{ii})\,\hat\sigma_{-i}\sqrt{h_{ii}}} = \frac{e_i}{\hat\sigma_{-i}\sqrt{1 - h_{ii}}}\cdot\sqrt{\frac{h_{ii}}{1 - h_{ii}}} = t_i\sqrt{\frac{h_{ii}}{1 - h_{ii}}}.

每一步的详细解释见第 26 章 Q4 (d)(e)(f)。

✅ 2021 卷检查清单
  • Q1:(b) 填 R² = 0.5024;F = 30.29 ~ F1,30F_{1,30};(e) 是 97%;(f) newdata 填 log(290)
  • Q2:dummy 的 t = 0.984 ~ t29t_{29},p = 0.333;和 rstudent 是同一个检验;命令 2*pt(-abs(rstudent(m21)[25]), 29)
  • Q3:(a) F = 25.21 ~ F4,27F_{4,27};(b) F = 8.019 ~ F3,27F_{3,27};(c) 要单独拟合 wt + disp,F = 0.791 ~ F1,<b>29</b>F_{1,<b>29</b>},不拒绝;(d) 92% 预测区间
  • Q4:b=β+Sεb = \beta + S\varepsilon ⇒ 无偏;Var(b)=σ2SS⊤\mathrm{Var}(b) = \sigma^2SS^\top;I−XSI - XS 对称幂等;tr(I−XS)=n−p\mathrm{tr}(I - XS) = n - p
  • Q5:OLS ∑xiyi/∑xi2\sum x_iy_i/\sum x_i^2;WLS ∑kixiyi/∑kixi2\sum k_ix_iy_i/\sum k_ix_i^2;MLE = WLS;变换后 OLS = WLS
  • Q6:14 号是影响点(两张图都要说);DFFITS₁₄ = −2.55,|·| > 2;(e) 的期望 0、方差 σ2hii2/(1−hii)\sigma^2h_{ii}^2/(1 - h_{ii})

第 24 章 · 2020 T3 期末完整解答(4 题 × 15 分)

本章目标
把 2020 T3 期末整份卷子逐题、逐小问做一遍。每一问给出:考什么 → 完整的步骤(可以照着写在答题本上)→ 得分点和常见错误。
这份卷子 4 题 × 15 分:Q1、Q3 是 Week 1–5 的推导(中心化 SLR、E(SSreg)E(\text{SSreg})),Q2 是"只给输出、不用 R"的分析题,Q4 是影响点(Cook's D)。老师说今年重点看 2020、2021、2023 三份,这份要能独立做完。
原卷:past_final_exams/MATH2831_2020.pdf 配套脚本:R/ch24_2020_final.R(只用来核对数字,考试时这些题不用 R)。
⚠️ 2020 年的考试形式和今年不同
2020 年是线上居家考试,3 小时,全部手写后拍照上传。今年是机房 Möbius,2 小时,R 题在 Möbius 里填。题目内容和难度仍然有参考价值:Q2 的分析思路和今年 R 题一样,只是今年要你自己跑 R 得到这些输出。
📚 做这份卷子要用到的知识
题知识点Lab Test 学过?详细讲解
Q1最小二乘求导、EE 和 Var\mathrm{Var} 的线性性质、协方差的拆分、χ2\chi^2 的定义✅ 大部分学过;协方差拆分和"联合正态 ⇒ 独立"本章会讲第 1、3、5 章
Q2读诊断图、log 变换后预测、overall F、序贯 F、外学生化残差F 检验学过;诊断图、变换是新内容第 7、10、16、25 章
Q3X⊤XX^\top X、帽子矩阵、迹、E(y⊤Ay)E(y^\top Ay)部分学过第 5、8、11 章,本章逐步写出
Q4杠杆、内学生化残差、Cook's D杠杆、残差学过;Cook's D 是新内容第 15 章;符号表见第 26 章 Q4

24.1 Q1:中心化的简单线性回归 [15 分]

📄 2020 期末 Q1
Consider a modified version of the simple linear regression model given by yi=β0+β1(xi−xˉ)+εi,i=1,…,n,(1)y_i = \beta_0 + \beta_1(x_i - \bar x) + \varepsilon_i, \quad i = 1, \dots, n, \qquad (1) where xˉ=∑i=1nxi/n\bar x = \sum_{i=1}^n x_i/n, so that xix_i enters the model centered. As usual, εi\varepsilon_i are uncorrelated errors with zero mean and common variance σ².
i) [2 marks] The model given in (1) is fitted to the following simple data: (y, x) = (3, 10), (5, 8), (24, 12). Write model (1) in the matrix form y=Xβ+εy = X\beta + \varepsilon, where β=(β0,β1)⊤\beta = (\beta_0, \beta_1)^\top and ε=(ε1,ε2,ε3)⊤\varepsilon = (\varepsilon_1, \varepsilon_2, \varepsilon_3)^\top. Clearly identify design matrix X and vector of responses y using the given data.
ii) [4 marks] Derive the least squares estimators b0b_0 and b1b_1 of the parameters β0\beta_0 and β1\beta_1 in model (1) by minimizing S(β0,β1)=∑i=1n(yi−β0−β1(xi−xˉ))2S(\beta_0, \beta_1) = \sum_{i=1}^n (y_i - \beta_0 - \beta_1(x_i - \bar x))^2 with respect to β0\beta_0 and β1\beta_1. You must show your work.
iii) [3 marks] Show that b0b_0 and b1b_1 derived in part ii) are unbiased estimators of β0\beta_0 and β1\beta_1, respectively. You must show your work.
iv) [4 marks] Prove that b0b_0 and b1b_1 derived in part ii) are uncorrelated. Then show that the covariance matrix of b=(b0,b1)⊤b = (b_0, b_1)^\top is given by Var(b)=(σ2/n00σ2/Sxx)\mathrm{Var}(b) = \begin{pmatrix}\sigma^2/n & 0\\ 0 & \sigma^2/S_{xx}\end{pmatrix}.
v) [2 marks] Assume that errors εi\varepsilon_i in (1) are independent and identically distributed and follow N(0,σ2)N(0, \sigma^2) distribution. Find the distribution of the sum n(b0−β0)2σ2+Sxx(b1−β1)2σ2.\frac{n(b_0 - \beta_0)^2}{\sigma^2} + \frac{S_{xx}(b_1 - \beta_1)^2}{\sigma^2}. You must give reasons for your answer.

整道题的关键事实:中心化之后 ∑i=1n(xi−xˉ)=∑xi−nxˉ=0\sum_{i=1}^n (x_i - \bar x) = \sum x_i - n\bar x = 0。后面每一问几乎都靠这一行化简,答题时第一次用到要写出来。另外记号 Sxx=∑(xi−xˉ)2S_{xx} = \sum(x_i - \bar x)^2,Sxy=∑(xi−xˉ)(yi−yˉ)S_{xy} = \sum(x_i - \bar x)(y_i - \bar y)(formula sheet 第 1 页有)。

✍️ i) [2 分] 写成矩阵形式

xˉ=(10+8+12)/3=10\bar x = (10 + 8 + 12)/3 = 10,所以中心化后的 x 是 xi−xˉ=0, −2, 2x_i - \bar x = 0,\ -2,\ 2。设计矩阵第一列全是 1(对应 β0\beta_0),第二列是 xi−xˉx_i - \bar x(对应 β1\beta_1):

(3524)⏟y=(101−212)⏟X(β0β1)+(ε1ε2ε3).\underbrace{\begin{pmatrix}3\\5\\24\end{pmatrix}}_{y} = \underbrace{\begin{pmatrix}1 & 0\\ 1 & -2\\ 1 & 2\end{pmatrix}}_{X}\begin{pmatrix}\beta_0\\ \beta_1\end{pmatrix} + \begin{pmatrix}\varepsilon_1\\ \varepsilon_2\\ \varepsilon_3\end{pmatrix}.

常见错误:第二列直接写 10, 8, 12(没中心化)。题目问的是模型 (1) 的 X,第二列必须是 xi−xˉx_i - \bar x。

✍️ ii) [4 分] 推导最小二乘估计

对 S(β0,β1)S(\beta_0, \beta_1) 分别求偏导,令其为 0(链式法则:括号里对 β0\beta_0 求导是 −1,对 β1\beta_1 求导是 −(xi−xˉ)-(x_i - \bar x))。

对 β0\beta_0:

∂S∂β0=−2∑i=1n(yi−β0−β1(xi−xˉ))=0 ⇒ ∑yi−nβ0−β1∑(xi−xˉ)⏟=0=0 ⇒ b0=1n∑yi=yˉ.\frac{\partial S}{\partial \beta_0} = -2\sum_{i=1}^n \big(y_i - \beta_0 - \beta_1(x_i - \bar x)\big) = 0 \ \Rightarrow\ \sum y_i - n\beta_0 - \beta_1\underbrace{\sum (x_i - \bar x)}_{=0} = 0 \ \Rightarrow\ b_0 = \frac1n\sum y_i = \bar y.

对 β1\beta_1:

∂S∂β1=−2∑i=1n(xi−xˉ)(yi−β0−β1(xi−xˉ))=0\frac{\partial S}{\partial \beta_1} = -2\sum_{i=1}^n (x_i - \bar x)\big(y_i - \beta_0 - \beta_1(x_i - \bar x)\big) = 0 ⇒ ∑(xi−xˉ)yi−β0∑(xi−xˉ)⏟=0−β1∑(xi−xˉ)2=0 ⇒ b1=∑(xi−xˉ)yi∑(xi−xˉ)2=SxySxx.\Rightarrow\ \sum (x_i - \bar x)y_i - \beta_0\underbrace{\sum(x_i - \bar x)}_{=0} - \beta_1\sum(x_i - \bar x)^2 = 0 \ \Rightarrow\ b_1 = \frac{\sum (x_i - \bar x)y_i}{\sum (x_i - \bar x)^2} = \frac{S_{xy}}{S_{xx}}.

最后一步用到 ∑(xi−xˉ)yi=∑(xi−xˉ)(yi−yˉ)\sum(x_i - \bar x)y_i = \sum(x_i - \bar x)(y_i - \bar y),因为两者相差 yˉ∑(xi−xˉ)=0\bar y\sum(x_i - \bar x) = 0。

(可选)说明这是最小值:二阶导矩阵是 2(n00Sxx)2\begin{pmatrix}n & 0\\ 0 & S_{xx}\end{pmatrix},正定,所以是最小值。

和普通 SLR 比:斜率完全相同;截距变成了 yˉ\bar y,因为中心化后 x = xˉ\bar x 时模型的均值就是 β0\beta_0。用 i) 的数据:b0=32/3=10.67b_0 = 32/3 = 10.67,Sxy=0⋅3+(−2)⋅5+2⋅24=38S_{xy} = 0\cdot3 + (-2)\cdot5 + 2\cdot24 = 38,Sxx=8S_{xx} = 8,b1=4.75b_1 = 4.75(题目没要求算,脚本 24.1 有核对)。

✍️ iii) [3 分] 无偏性

x 是固定的(不是随机变量),所以 E(yi)=β0+β1(xi−xˉ)+E(εi)=β0+β1(xi−xˉ)E(y_i) = \beta_0 + \beta_1(x_i - \bar x) + E(\varepsilon_i) = \beta_0 + \beta_1(x_i - \bar x)。

E(b0)=1n∑E(yi)=1n(nβ0+β1∑(xi−xˉ))=1n(nβ0+0)=β0.E(b_0) = \frac1n\sum E(y_i) = \frac1n\Big(n\beta_0 + \beta_1\sum(x_i - \bar x)\Big) = \frac1n(n\beta_0 + 0) = \beta_0. E(b1)=1Sxx∑(xi−xˉ)E(yi)=1Sxx(β0∑(xi−xˉ)⏟=0+β1∑(xi−xˉ)2⏟=Sxx)=β1.E(b_1) = \frac{1}{S_{xx}}\sum(x_i - \bar x)E(y_i) = \frac{1}{S_{xx}}\Big(\beta_0\underbrace{\sum(x_i - \bar x)}_{=0} + \beta_1\underbrace{\sum(x_i - \bar x)^2}_{=S_{xx}}\Big) = \beta_1.

得分点:写出 b1=∑(xi−xˉ)yi/Sxxb_1 = \sum(x_i - \bar x)y_i / S_{xx} 这种"y 的线性组合"形式再取期望;直接写 E(Sxy/Sxx)E(S_{xy}/S_{xx}) 不展开会丢分。

✍️ iv) [4 分] 不相关 + 协方差矩阵

把两个估计都写成 y 的线性组合:b0=∑aiyib_0 = \sum a_iy_i,ai=1na_i = \frac1n;b1=∑ciyib_1 = \sum c_iy_i,ci=xi−xˉSxxc_i = \frac{x_i - \bar x}{S_{xx}}。

yiy_i 互不相关,且 Var(yi)=Var(εi)=σ2\mathrm{Var}(y_i) = \mathrm{Var}(\varepsilon_i) = \sigma^2,所以 Cov(yi,yj)=0 (i≠j)\mathrm{Cov}(y_i, y_j) = 0\ (i \ne j):

Cov(b0,b1)=Cov(∑iaiyi,∑jcjyj)=∑iaici σ2=σ2nSxx∑(xi−xˉ)=0.\mathrm{Cov}(b_0, b_1) = \mathrm{Cov}\Big(\sum_i a_iy_i, \sum_j c_jy_j\Big) = \sum_i a_ic_i\,\sigma^2 = \frac{\sigma^2}{nS_{xx}}\sum(x_i - \bar x) = 0.

第二个等号是怎么来的(最容易卡住的一步):协方差像乘法分配律一样可以拆开,常数可以提出来:Cov(aU,cW)=ac Cov(U,W)\mathrm{Cov}(aU, cW) = ac\,\mathrm{Cov}(U, W),Cov(U1+U2,W)=Cov(U1,W)+Cov(U2,W)\mathrm{Cov}(U_1 + U_2, W) = \mathrm{Cov}(U_1, W) + \mathrm{Cov}(U_2, W)。以 n = 2 为例,四项全部写出来:

Cov(a1y1+a2y2, c1y1+c2y2)=a1c1Cov(y1,y1)⏟σ2+a1c2Cov(y1,y2)⏟0+a2c1Cov(y2,y1)⏟0+a2c2Cov(y2,y2)⏟σ2.\mathrm{Cov}(a_1y_1 + a_2y_2,\ c_1y_1 + c_2y_2) = a_1c_1\underbrace{\mathrm{Cov}(y_1, y_1)}_{\sigma^2} + a_1c_2\underbrace{\mathrm{Cov}(y_1, y_2)}_{0} + a_2c_1\underbrace{\mathrm{Cov}(y_2, y_1)}_{0} + a_2c_2\underbrace{\mathrm{Cov}(y_2, y_2)}_{\sigma^2}.

下标不同的交叉项是 0(误差不相关,而 yiy_i 只比 εi\varepsilon_i 多一个常数),下标相同的是 Var(yi)=σ2\mathrm{Var}(y_i) = \sigma^2,所以只剩 (a1c1+a2c2)σ2(a_1c_1 + a_2c_2)\sigma^2。一般的 n 同理:∑i∑jaicjCov(yi,yj)=∑iaiciσ2\sum_i\sum_j a_ic_j\mathrm{Cov}(y_i, y_j) = \sum_i a_ic_i\sigma^2。用 i) 的数据核对:a=(13,13,13)a = (\frac13, \frac13, \frac13),c=(0,−14,14)c = (0, -\frac14, \frac14),∑aici=0\sum a_ic_i = 0。

b1b_1 为什么能写成 ∑ciyi\sum c_iy_i:Sxy=∑(xi−xˉ)(yi−yˉ)=∑(xi−xˉ)yi−yˉ∑(xi−xˉ)S_{xy} = \sum(x_i - \bar x)(y_i - \bar y) = \sum(x_i - \bar x)y_i - \bar y\sum(x_i - \bar x),后一项是 0,所以 yˉ\bar y 消失了。如果不先消掉 yˉ\bar y,每一项都含同一个 yˉ\bar y,各项之间不独立,就没法直接相加方差。

所以 b0b_0、b1b_1 不相关。再求两个方差:

Var(b0)=∑ai2σ2=n⋅1n2σ2=σ2n,Var(b1)=∑ci2σ2=∑(xi−xˉ)2Sxx2σ2=σ2Sxx.\mathrm{Var}(b_0) = \sum a_i^2\sigma^2 = n\cdot\frac{1}{n^2}\sigma^2 = \frac{\sigma^2}{n},\qquad \mathrm{Var}(b_1) = \sum c_i^2\sigma^2 = \frac{\sum(x_i - \bar x)^2}{S_{xx}^2}\sigma^2 = \frac{\sigma^2}{S_{xx}}.

放进矩阵(对角线是方差,非对角线是协方差)就是题目给的 Var(b)\mathrm{Var}(b)。

另一种写法(矩阵):X⊤X=(n∑(xi−xˉ)∑(xi−xˉ)∑(xi−xˉ)2)=(n00Sxx)X^\top X = \begin{pmatrix}n & \sum(x_i - \bar x)\\ \sum(x_i - \bar x) & \sum(x_i - \bar x)^2\end{pmatrix} = \begin{pmatrix}n & 0\\ 0 & S_{xx}\end{pmatrix},所以 Var(b)=σ2(X⊤X)−1=(σ2/n00σ2/Sxx)\mathrm{Var}(b) = \sigma^2(X^\top X)^{-1} = \begin{pmatrix}\sigma^2/n & 0\\ 0 & \sigma^2/S_{xx}\end{pmatrix}。用这种写法要先说明 Var(b)=σ2(X⊤X)−1\mathrm{Var}(b) = \sigma^2(X^\top X)^{-1} 的来历(b=(X⊤X)−1X⊤yb = (X^\top X)^{-1}X^\top y,Var(Ay)=A Var(y)A⊤\mathrm{Var}(Ay) = A\,\mathrm{Var}(y)A^\top)。

✍️ v) [2 分] 分布:χ22\chi^2_2
  1. εi\varepsilon_i iid 正态 ⇒ y 是多元正态;b0b_0、b1b_1 都是 y 的线性组合 ⇒ (b0,b1)(b_0, b_1) 联合正态。
  2. 由 iii) iv):b0∼N(β0,σ2/n)b_0 \sim N(\beta_0, \sigma^2/n),b1∼N(β1,σ2/Sxx)b_1 \sim N(\beta_1, \sigma^2/S_{xx}),标准化: Z0=b0−β0σ/n∼N(0,1),Z1=b1−β1σ/Sxx∼N(0,1).Z_0 = \frac{b_0 - \beta_0}{\sigma/\sqrt n} \sim N(0,1),\qquad Z_1 = \frac{b_1 - \beta_1}{\sigma/\sqrt{S_{xx}}} \sim N(0,1).
  3. 联合正态 + 不相关 ⇒ 独立(这一步只对正态成立,必须写出"联合正态")。
    为什么:二元标准正态的密度里,只有相关系数 ρ 把两个变量连在一起;ρ = 0 时密度拆成两个一元密度的乘积 12πe−(z02+z12)/2=ϕ(z0)ϕ(z1)\frac{1}{2\pi}e^{-(z_0^2 + z_1^2)/2} = \phi(z_0)\phi(z_1),这就是独立的定义。
    为什么一定要"联合":反例 X∼N(0,1)X \sim N(0,1),W 以各 1/2 概率取 ±1 且与 X 独立,Y=WXY = WX。Y 也是 N(0, 1),Cov(X,Y)=0\mathrm{Cov}(X, Y) = 0,但 ∣Y∣=∣X∣|Y| = |X|,显然不独立,因为 (X, Y) 不是联合正态。
    为什么 (b0,b1)(b_0, b_1) 是联合正态:它们的任意线性组合 λ0b0+λ1b1\lambda_0b_0 + \lambda_1b_1 仍是独立正态 yiy_i 的线性组合,所以是正态,这正是联合正态的定义。
  4. 题目的和 =Z02+Z12= Z_0^2 + Z_1^2,两个独立标准正态的平方和 ⇒ χ22\boldsymbol{\chi^2_2}。

脚本 24.2 用 10000 次模拟验证:这个和的均值 ≈ 2、方差 ≈ 4,正是 χ22\chi^2_2 的均值和方差。

Rch24 · 24.1

y <- c(3, 5, 24); x <- c(10, 8, 12)
xc <- x - mean(x)
X <- cbind(1, xc); X
t(X) %*% X
b <- solve(t(X) %*% X) %*% t(X) %*% y; b
Console 输出
       xc
[1,] 1  0
[2,] 1 -2
[3,] 1  2
     xc
   3  0
xc 0  8
       [,1]
   10.66667
xc  4.75000

X⊤XX^\top X 是对角矩阵 diag(3, 8) = diag(n, SxxS_{xx}),这就是 iv) 里 b0b_0、b1b_1 不相关的原因。

24.2 Q2:拍卖钟表价格,只看输出作答 [15 分]

📄 2020 期末 Q2
A study was conducted to investigate the price of grandfather clocks at auctions. The selling price (in pounds) at auction of 30 antique grandfather clocks were recorded, as well as the age (in years) of the clock and number of individuals participating in the bidding.
i) [3 marks] A multiple linear regression model was fitted with Price as the response and Age and Bidders as predictors. Examine diagnostic plots on Figure 1 and comment on whether you think this model is adequate and if not state what assumptions you think are being violated; name the residual plots where you see this violation.
ii) [12 marks] After examining the diagnostic plot, it was suggested to transform the response and one of the predictors. A new model involving log-transformed Price and log-transformed Age, while Bidders is kept un-transformed, was fitted to the data. Answer the following questions with the help of the diagnostic plot on Figure 2 and numerical outputs.
a) [3 marks] Examine diagnostic plots for the new model log(Price) ~ log(Age) + Bidders on Figure 2 and comment on why the new model is better suited for analyzing the data set. Using the fitted model predict the selling price (in log units) of a 177 years old grandfather clock when there are 7 participants bidding.
b) [3 marks] State whether you think that this linear regression model is better than the model containing only an intercept term. You should refer to an appropriate hypothesis test to support your answer: state the null and alternative hypothesis, the value of test statistic, and the conclusion of the test at the 5% level of significance.
c) [3 marks] It was felt that log(Age) should be included in the model, but that Bidders might not be related to log(Price) in the model involving log(Age). Perform a hypothesis test to compare the model involving both predictors, log(Age) and Bidders, to the model including only log(Age). State the null and alternative hypothesis, the value of test statistic, and the conclusion of the test at the 5% level of significance.
d) [3 marks] The externally studentized residual for 20th observation was found to be t20=−2.2504t_{20} = -2.2504. Assuming the model fitted is appropriate, state whether you think this observation is an unusual one. You should support your answer with an appropriate hypothesis test (use 5% level of significance). You may also use: qt(0.95,26) = 1.705618, qt(0.95,27) = 1.703288, qt(0.975,26) = 2.055529, qt(0.975,27) = 2.051831.

Figure 1:Price ~ Age + Bidders 的诊断图

2020 Q2 Figure 1: diagnostic plots for Price ~ Age + Bidders
✍️ i) [3 分] 原模型合适吗

四张图逐张看(方法见第 10 章;每种"坏"图长什么样,见第 25 章的可视化例子):

  • Residuals vs Fitted:红线是很明显的 V / U 形:两头的残差大多为正(+100 到 +200),中间(拟合值 1200–1500)大多为负。残差有系统性的规律 ⇒ 线性假设不成立,均值和预测变量的关系不是线性的。
  • Normal Q-Q:左下端一排点(约 −1.4)明显在直线上方,右上端的点在直线下方,整体呈 S 形 ⇒ 两端比正态分布"短",正态性也值得怀疑。
  • Scale-Location:红线在 0.8–1.0 之间轻微起伏,没有明显的喇叭形 ⇒ 方差恒定这一条问题不大。
  • Residuals vs Leverage:所有点都在 Cook's distance 0.5 的等高线以内(图上连等高线都看不到)⇒ 没有强影响点。

可以直接写的答案:

The model is not adequate. The Residuals vs Fitted plot shows a clear U-shaped pattern (positive residuals at both ends, negative in the middle), so the linearity assumption is violated. The Normal Q-Q plot shows the points deviating from the line at both tails, so the normality assumption is also questionable. The Scale-Location plot does not show a strong trend and no observation lies outside the Cook's distance contours in the Residuals vs Leverage plot.

得分点:3 分 = 判断"不合适" + 说出违反哪个假设 + 点名是哪张图。只说"有问题"不点名图会扣分。

Figure 2:log(Price) ~ log(Age) + Bidders 的诊断图

2020 Q2 Figure 2: diagnostic plots for log(Price) ~ log(Age) + Bidders

题目给的数值输出(节选):

Coefficients:
            Estimate Std. Error t value Pr(>|t|)
(Intercept) -0.669082   0.447817  -1.494    0.147
log(Age)     1.449734   0.087463  16.575 1.12e-15 ***
Bidders      0.066160   0.006235  10.611 3.92e-11 ***
Residual standard error: 0.08659 on 27 degrees of freedom
Multiple R-squared:  0.9253,	Adjusted R-squared:  0.9197
F-statistic: 167.2 on 2 and 27 DF,  p-value: 6.189e-16

> anova(model)
          Df  Sum Sq Mean Sq F value    Pr(>F)
log(Age)   1 1.66267 1.66267  221.74 1.535e-14 ***
Bidders    1 0.84424 0.84424  112.59 3.919e-11 ***
Residuals 27 0.20245 0.00750
✍️ ii a) [3 分] 新模型为什么更好 + 预测

看图(约 2 分):Residuals vs Fitted 的红线基本贴着 0,U 形消失 ⇒ 线性假设现在成立;Normal Q-Q 的点基本落在直线上(只有 20、15 两个端点略偏)⇒ 正态性可以接受;Scale-Location 红线大致水平 ⇒ 方差恒定;Residuals vs Leverage 没有点超出 Cook's 0.5 ⇒ 没有强影响点。所以变换后的模型满足假设,更适合分析这组数据。

预测(约 1 分):代入 Age = 177、Bidders = 7。log 用的是自然对数(R 的 log()),log(177) = 5.1761:

log⁡(Price)^=−0.669082+1.449734×log⁡(177)+0.066160×7=−0.669082+7.50402+0.46312=7.298.\widehat{\log(\text{Price})} = -0.669082 + 1.449734 \times \log(177) + 0.066160 \times 7 = -0.669082 + 7.50402 + 0.46312 = 7.298.

换回英镑是 e7.298≈1477e^{7.298} \approx 1477 英镑(题目只要 log 单位,写 7.298 即可)。

常见错误:把 177 直接代进去(模型里是 log(Age)),或者对 Bidders 也取 log(Bidders 没有变换)。

✍️ ii b) [3 分] 整体 F 检验
  • 假设:H0:β1=β2=0H_0: \beta_1 = \beta_2 = 0(log(Age) 和 Bidders 的系数都为 0,即只有截距的模型就够了) vs H1H_1:β1\beta_1、β2\beta_2 至少一个不为 0。
  • 统计量:F = 167.2,在 H0H_0 下 ~ F2,27F_{2,27}(分子 df = 预测变量个数 2,分母 df = 残差 df = 30 − 3 = 27)。
  • 结论:p = 6.189e-16 < 0.05 ⇒ 拒绝 H0H_0。这个模型显著好于只有截距的模型。(或者比临界值:F0.05;2,27=3.35F_{0.05;2,27} = 3.35,167.2 远大于它。)

数字从 summary 最后一行 "F-statistic: 167.2 on 2 and 27 DF" 直接读。

✍️ ii c) [3 分] 加了 log(Age) 之后,Bidders 还有用吗
  • 假设:在含有 log(Age) 的模型里,H0:βBidders=0H_0: \beta_{\text{Bidders}} = 0 vs H1:βBidders≠0H_1: \beta_{\text{Bidders}} \ne 0。等价于比较"只有 log(Age)"的简化模型和"log(Age) + Bidders"的完整模型。
  • 统计量:看 anova 表的 Bidders 那一行。anova 是按顺序加变量的:log(Age) 先进,Bidders 后进,所以这一行正是"已有 log(Age) 时再加 Bidders"的 F 检验(第 7 章的 sequential F): F=R(β2∣β0,β1)/1SSres/27=0.844240.00750=112.59 ∼ F1,27.F = \frac{R(\beta_2 \mid \beta_0, \beta_1)/1}{\text{SSres}/27} = \frac{0.84424}{0.00750} = 112.59 \ \sim\ F_{1,27}.
  • 结论:p = 3.919e-11 < 0.05 ⇒ 拒绝 H0H_0。即使模型里已经有 log(Age),Bidders 仍然和 log(Price) 显著相关,应该保留。

检查:只加一个变量时 F = t2t^2。summary 里 Bidders 的 t = 10.611,10.6112=112.5910.611^2 = 112.59,和 anova 一致。所以用 partial t 检验作答(t = 10.611 ~ t27t_{27})也对。

常见错误:用 log(Age) 那一行(221.74)。那一行检验的是"在只有截距的模型里加 log(Age)",不是本题问的。

✍️ ii d) [3 分] 第 20 个观测是离群点吗
  • 假设:H0H_0:第 20 个观测不是离群点(均值漂移模型里 Δ=0\Delta = 0,见第 14 章) vs H1H_1:它是离群点(Δ≠0\Delta \ne 0)。
  • 统计量:外学生化残差 t20=−2.2504t_{20} = -2.2504,在 H0H_0 下 ~ tn−p−1t_{n-p-1}。这里 n = 30,p = 3(截距 + 2 个预测变量),所以自由度 = 30 − 3 − 1 = 26。
  • 临界值:双侧 5% 用 qt(0.975, 26) = 2.0555。
  • 结论:∣t20∣=2.2504>2.0555|t_{20}| = 2.2504 > 2.0555 ⇒ 在 5% 水平拒绝 H0H_0(p ≈ 0.033),第 20 个观测是 unusual 的(离群点)。

这题的陷阱:题目同时给了 df = 26 和 27、0.95 和 0.975 四个分位数。

  • df 用 26 不用 27:算 tit_i 时要用去掉第 i 个观测后的 σ^−i\hat\sigma_{-i},少了一个观测,所以比模型残差 df 少 1。
  • 用 0.975 不用 0.95:问的是"是否 unusual",偏大偏小都算,是双侧检验。
Rch24 · 24.3

b <- c(-0.669082, 1.449734, 0.066160)
pred <- sum(b * c(1, log(177), 7)); pred
exp(pred)
qf(0.95, 2, 27)
qf(0.95, 1, 27); 10.611^2
2 * pt(-2.2504, df = 26)
Console 输出
[1] 7.298078
[1] 1477.458
[1] 3.354131
[1] 4.210008
[1] 112.5933
[1] 0.03310697

24.3 Q3:E(SSreg)=σ2+β12SxxE(\text{SSreg}) = \sigma^2 + \beta_1^2 S_{xx} [15 分]

📄 2020 期末 Q3(原卷用 𝕀 表示全是 1 的 n × n 矩阵,下面写作 J,避免和单位矩阵 I 混淆)
Consider the general linear model y=Xβ+εy = X\beta + \varepsilon (where as usual y is an n × 1 vector of responses, X is an n × p design matrix and ε is a vector of zero mean errors uncorrelated with variance σ²). The regression sum of squares is defined as SSreg=∑i=1n(y^i−yˉ)2\text{SSreg} = \sum_{i=1}^n(\hat y_i - \bar y)^2. It can be proved (you are not asked to prove this) that SSreg can also be expressed as the following quadratic form in y: SSreg=y⊤(H−1nJ)y\text{SSreg} = y^\top\big(H - \frac1n J\big)y, where H=X(X⊤X)−1X⊤H = X(X^\top X)^{-1}X^\top is the n × n hat matrix and J is an n × n matrix of ones.
i) [2 marks] The ordinary simple linear regression model yi=β0+β1xi+εiy_i = \beta_0 + \beta_1x_i + \varepsilon_i can be written in the form of the general linear model y=Xβ+εy = X\beta + \varepsilon for suitable design matrix X. What is X? What is X⊤XX^\top X?
In all of the remaining parts, ii) to v), consider the above ordinary simple linear regression model in the matrix form.
ii) [3 marks] Show that 1nX⊤JX=(n∑xi∑xi1n(∑xi)2)\frac1n X^\top JX = \begin{pmatrix}n & \sum x_i\\ \sum x_i & \frac1n(\sum x_i)^2\end{pmatrix}.
iii) [3 marks] Hence show that X⊤(H−1nJ)X=X⊤HX−1nX⊤JX=(000Sxx)X^\top\big(H - \frac1n J\big)X = X^\top HX - \frac1n X^\top JX = \begin{pmatrix}0 & 0\\ 0 & S_{xx}\end{pmatrix}.
iv) [2 marks] Find tr(H−1nJ)\mathrm{tr}\big(H - \frac1n J\big) where tr(A) denotes the trace of the square matrix A, defined as the sum of its diagonal entries.
v) [5 marks] Using all the above, prove that E(SSreg)=σ2+β12SxxE(\text{SSreg}) = \sigma^2 + \beta_1^2 S_{xx}. You must show your work. (Hint: use the formula for E(y⊤Ay)E(y^\top Ay).)
✍️ i) [2 分] X 和 X⊤XX^\top X
X=(1x11x2⋮⋮1xn),X⊤X=(1⋯1x1⋯xn)(1x1⋮⋮1xn)=(n∑xi∑xi∑xi2).X = \begin{pmatrix}1 & x_1\\ 1 & x_2\\ \vdots & \vdots\\ 1 & x_n\end{pmatrix},\qquad X^\top X = \begin{pmatrix}1 & \cdots & 1\\ x_1 & \cdots & x_n\end{pmatrix}\begin{pmatrix}1 & x_1\\ \vdots & \vdots\\ 1 & x_n\end{pmatrix} = \begin{pmatrix}n & \sum x_i\\ \sum x_i & \sum x_i^2\end{pmatrix}.

X⊤XX^\top X 的 (j, k) 元素 = X 第 j 列和第 k 列的内积:1·1 求和 = n,1·xix_i 求和 = ∑xi\sum x_i,xi⋅xix_i \cdot x_i 求和 = ∑xi2\sum x_i^2。

✍️ ii) [3 分] 1nX⊤JX\frac1n X^\top JX

关键技巧:全 1 矩阵可以写成 J=11⊤J = \mathbf 1\mathbf 1^\top,其中 1=(1,…,1)⊤\mathbf 1 = (1, \dots, 1)^\top 是 n × 1 的全 1 向量。于是

X⊤JX=X⊤1 1⊤X=(X⊤1)(X⊤1)⊤.X^\top JX = X^\top\mathbf 1\,\mathbf 1^\top X = (X^\top\mathbf 1)(X^\top\mathbf 1)^\top.

而 X⊤1X^\top\mathbf 1 = X 每一列的和 = (n∑xi)\begin{pmatrix}n\\ \sum x_i\end{pmatrix},所以

X⊤JX=(n∑xi)(n∑xi)=(n2n∑xin∑xi(∑xi)2) ⇒ 1nX⊤JX=(n∑xi∑xi1n(∑xi)2).X^\top JX = \begin{pmatrix}n\\ \sum x_i\end{pmatrix}\begin{pmatrix}n & \sum x_i\end{pmatrix} = \begin{pmatrix}n^2 & n\sum x_i\\ n\sum x_i & (\sum x_i)^2\end{pmatrix} \ \Rightarrow\ \frac1n X^\top JX = \begin{pmatrix}n & \sum x_i\\ \sum x_i & \frac1n(\sum x_i)^2\end{pmatrix}.

不想用 11⊤\mathbf 1\mathbf 1^\top 也可以直接乘:JXJX 的每一行都是 (n,∑xi)(n, \sum x_i),再左乘 X⊤X^\top 即可。

✍️ iii) [3 分] X⊤(H−1nJ)X=diag(0,Sxx)X^\top(H - \frac1n J)X = \mathrm{diag}(0, S_{xx})

先算 X⊤HXX^\top HX:

X⊤HX=X⊤X(X⊤X)−1X⊤X=X⊤X(中间的 X⊤X(X⊤X)−1=I).X^\top HX = X^\top X(X^\top X)^{-1}X^\top X = X^\top X\quad(\text{中间的 }X^\top X(X^\top X)^{-1} = I).

(也可以用 HX=XHX = X:H 把 X 的列投影到 X 的列空间,投影后不变。)再用 i)、ii):

X⊤(H−1nJ)X=X⊤X−1nX⊤JX=(n−n∑xi−∑xi∑xi−∑xi∑xi2−1n(∑xi)2)=(000Sxx).X^\top\Big(H - \frac1n J\Big)X = X^\top X - \frac1n X^\top JX = \begin{pmatrix}n - n & \sum x_i - \sum x_i\\ \sum x_i - \sum x_i & \sum x_i^2 - \frac1n(\sum x_i)^2\end{pmatrix} = \begin{pmatrix}0 & 0\\ 0 & S_{xx}\end{pmatrix}.

最后一步:Sxx=∑(xi−xˉ)2=∑xi2−nxˉ2=∑xi2−1n(∑xi)2S_{xx} = \sum(x_i - \bar x)^2 = \sum x_i^2 - n\bar x^2 = \sum x_i^2 - \frac1n(\sum x_i)^2。这个恒等式要写出来,是得分点。

✍️ iv) [2 分] 迹 = 1

迹是线性的:tr(H−1nJ)=tr(H)−1ntr(J)\mathrm{tr}(H - \frac1n J) = \mathrm{tr}(H) - \frac1n\mathrm{tr}(J)。

  • tr(H)=tr(X(X⊤X)−1X⊤)=tr((X⊤X)−1X⊤X)=tr(Ip)=p=2\mathrm{tr}(H) = \mathrm{tr}\big(X(X^\top X)^{-1}X^\top\big) = \mathrm{tr}\big((X^\top X)^{-1}X^\top X\big) = \mathrm{tr}(I_p) = p = 2(用 tr(AB)=tr(BA)\mathrm{tr}(AB) = \mathrm{tr}(BA))。
  • tr(J)=n\mathrm{tr}(J) = n(对角线上 n 个 1)。
tr(H−1nJ)=2−1n⋅n=1.\mathrm{tr}\Big(H - \frac1n J\Big) = 2 - \frac1n\cdot n = 1.
✍️ v) [5 分] 证明 E(SSreg)=σ2+β12SxxE(\text{SSreg}) = \sigma^2 + \beta_1^2S_{xx}

用到的公式(formula sheet 最后一页):若 E(y)=μE(y) = \mu,Var(y)=V\mathrm{Var}(y) = V,则 E(y⊤Ay)=tr(AV)+μ⊤AμE(y^\top Ay) = \mathrm{tr}(AV) + \mu^\top A\mu。

这里 A=H−1nJA = H - \frac1n J,μ=E(y)=Xβ\mu = E(y) = X\beta,V=Var(y)=Var(ε)=σ2IV = \mathrm{Var}(y) = \mathrm{Var}(\varepsilon) = \sigma^2 I(误差不相关、方差 σ²)。

第一项(用 iv):

tr(AV)=tr(σ2A)=σ2 tr(H−1nJ)=σ2⋅1=σ2.\mathrm{tr}(AV) = \mathrm{tr}(\sigma^2 A) = \sigma^2\,\mathrm{tr}\Big(H - \frac1n J\Big) = \sigma^2 \cdot 1 = \sigma^2.

第二项(用 iii):

μ⊤Aμ=β⊤X⊤(H−1nJ)Xβ=(β0β1)(000Sxx)(β0β1)=β12Sxx.\mu^\top A\mu = \beta^\top X^\top\Big(H - \frac1n J\Big)X\beta = \begin{pmatrix}\beta_0 & \beta_1\end{pmatrix}\begin{pmatrix}0 & 0\\ 0 & S_{xx}\end{pmatrix}\begin{pmatrix}\beta_0\\ \beta_1\end{pmatrix} = \beta_1^2 S_{xx}.

合起来:E(SSreg)=σ2+β12SxxE(\text{SSreg}) = \sigma^2 + \beta_1^2S_{xx}。∎

这个结果说明什么(可以加一句,显得理解了):H0:β1=0H_0: \beta_1 = 0 成立时 E(SSreg)=σ2=E(σ^2)E(\text{SSreg}) = \sigma^2 = E(\hat\sigma^2),所以 F = SSreg / σ^2\hat\sigma^2 应该在 1 附近;β1≠0\beta_1 \ne 0 时分子期望更大,F 偏大。这正是 SLR 的 F 检验"F 大就拒绝"的理由。

五分怎么给:写出公式和 A、μ、V(2 分);第一项(1 分);第二项(2 分)。一定要写 Var(y) = σ²I,很多人漏掉。

Rch24 · 24.4:数值验证 iii) iv) v)(可跳过)

set.seed(2)
n <- 12; xq <- runif(n, 0, 5); Xq <- cbind(1, xq)
H <- Xq %*% solve(t(Xq) %*% Xq) %*% t(Xq); J <- matrix(1, n, n)
A <- H - J / n
round(t(Xq) %*% A %*% Xq, 10)
sum((xq - mean(xq))^2)
sum(diag(A))
beta0 <- 1; beta1 <- 2; sigma <- 3
SSreg <- replicate(20000, {
  yq <- beta0 + beta1 * xq + rnorm(n, sd = sigma)
  sum((fitted(lm(yq ~ xq)) - mean(yq))^2)
})
c(simulated = mean(SSreg), theory = sigma^2 + beta1^2 * sum((xq - mean(xq))^2))
Console 输出
           xq
   0  0.00000
xq 0 24.14372
[1] 24.14372
[1] 1
simulated    theory
 105.2031  105.5749

24.4 Q4:影响点和 Cook's D [15 分]

📄 2020 期末 Q4
A multiple linear model is fitted to data with response y and predictors x1 and x2. Answer parts i) and ii) with the help of R-outputs produced after fitting this model.
i) [3 marks] Figure 3 shows a diagnostic plot for the fitted model. After examining the plots, based on the Cook's distance measure, which observations would you classify as being influential? Give reasons why.
ii) [3 marks] For the observation(s) identified as influential in the previous part, calculate Cook's DiD_i using the formula given in lectures Di=ri2hiip(1−hii)D_i = \frac{r_i^2 h_{ii}}{p(1 - h_{ii})} and the following R-output (hatvalues(model) and rstandard(model) for 13 observations).
Consider now the full rank general linear model y=Xβ+εy = X\beta + \varepsilon (with usual assumptions) and answer parts iii) and iv).
iii) [3 marks] Cook's distance for the ith observation is the influence measure given by Di=(b−b−i)⊤(X⊤X)(b−b−i)pσ^2D_i = \frac{(b - b_{-i})^\top(X^\top X)(b - b_{-i})}{p\hat\sigma^2} (2). Use the definition of b−ib_{-i} to explain in words what does b−b−ib - b_{-i} represent. What does Cook's distance (DiD_i) measure?
iv) [6 marks] In this part you are asked to derive an easy computational formula for Cook's distance given in lectures. You can make use of the following result (you are not asked to prove this): b−i=b−(X⊤X)−1xiei1−hiib_{-i} = b - \frac{(X^\top X)^{-1}x_ie_i}{1 - h_{ii}} (3), where xi⊤x_i^\top the ith row of design matrix X, eie_i is the ith raw residual and hiih_{ii} is the ith leverage, which can be written as hii=xi⊤(X⊤X)−1xih_{ii} = x_i^\top(X^\top X)^{-1}x_i. Show that Di is equal to Di=ri2phii1−hiiD_i = \frac{r_i^2}{p}\frac{h_{ii}}{1 - h_{ii}}, where rir_i is the ith internally studentized residual. (Hint: obtain the expression for b−b−ib - b_{-i} from (3) and then substitute into (2).)

Figure 3:y ~ x1 + x2 的 Cook's distance 图和 Residuals vs Leverage 图

2020 Q4 Figure 3: Cook's distance and Residuals vs Leverage plots
> hatvalues(model)
         1          2          3          4          5          6
0.14423641 0.28862704 0.14164879 0.09863649 0.18048629 0.15995646
         7          8          9         10         11         12
0.29003420 0.09505224 0.13806694 0.26717202 0.37847203 0.38099986
        13
0.43661124
> rstandard(model)
          1           2           3           4           5           6
-0.12543602  0.31684273  0.17350829  0.21594335  0.05115624 -0.06995024
          7           8           9          10          11          12
-0.51572178  0.63864291 -0.46679194  0.61214275 -2.75414799 -0.69093819
         13
 2.60073093 
✍️ i) [3 分] 哪些是影响点

Observations 11 and 13 are influential. In the Cook's distance plot their bars (about 1.5 and 1.75) are far taller than all others and exceed 1, the rule of thumb from lectures. In the Residuals vs Leverage plot both points lie outside the Cook's distance contour of 1: each combines a large standardized residual (about −2.75 for obs 11 and 2.6 for obs 13) with a high leverage (about 0.38 and 0.44, well above the average leverage p/n = 3/13 = 0.23). Observation 12 also has a high leverage (0.38) but a small residual (−0.69), so its Cook's distance is small (about 0.1) and it is not influential.

得分点:点名 11、13 + 用 Cook's D > 1(或 > 0.5)的标准 + 解释"大残差 且高杠杆"。顺带说 12 为什么不是,显示你懂"高杠杆 ≠ 影响点"。

✍️ ii) [3 分] 手算 D11D_{11}、D13D_{13}

p = 参数个数 = 截距 + x1 + x2 = 3(不是 2!)。题目给的 rstandard 就是内学生化残差 rir_i,直接代:

D11=(−2.75414799)2×0.378472033×(1−0.37847203)=7.5853×0.378473×0.62153=2.87081.8646=1.54,D_{11} = \frac{(-2.75414799)^2 \times 0.37847203}{3 \times (1 - 0.37847203)} = \frac{7.5853 \times 0.37847}{3 \times 0.62153} = \frac{2.8708}{1.8646} = 1.54, D13=(2.60073093)2×0.436611243×(1−0.43661124)=6.7638×0.436613×0.56339=2.95311.6902=1.75.D_{13} = \frac{(2.60073093)^2 \times 0.43661124}{3 \times (1 - 0.43661124)} = \frac{6.7638 \times 0.43661}{3 \times 0.56339} = \frac{2.9531}{1.6902} = 1.75.

两个都 > 1,和图一致,确认是影响点。(讲义另一条标准:和 F0.5; p, n−p=F0.5;3,10=0.845F_{0.5;\,p,\,n-p} = F_{0.5;3,10} = 0.845 比,两个也都更大。)

常见错误:p 用 2;把 rir_i 当成 tit_i(rstudent);忘了平方后负号消失。

Rch24 · 24.5

h <- c(0.14423641, 0.28862704, 0.14164879, 0.09863649, 0.18048629, 0.15995646,
       0.29003420, 0.09505224, 0.13806694, 0.26717202, 0.37847203, 0.38099986,
       0.43661124)
r <- c(-0.12543602, 0.31684273, 0.17350829, 0.21594335, 0.05115624, -0.06995024,
       -0.51572178, 0.63864291, -0.46679194, 0.61214275, -2.75414799, -0.69093819,
       2.60073093)
p <- 3; n <- 13
D <- r^2 / p * h / (1 - h)
round(D, 4)
qf(0.5, p, n - p)
Console 输出
 [1] 0.0009 0.0136 0.0017 0.0017 0.0002 0.0003 0.0362 0.0143 0.0116 0.0455
[11] 1.5397 0.0979 1.7473
[1] 0.8450806
✍️ iii) [3 分] b−b−ib - b_{-i} 和 Cook's D 的含义

b−ib_{-i} is the least squares estimate of β obtained by fitting the model with the ith observation deleted. So b−b−ib - b_{-i} is the change in the estimated regression coefficients caused by deleting the ith observation: it shows how much the ith observation alone moves the fitted coefficients.

Cook's distance DiD_i measures the overall influence of the ith observation on the estimated coefficients: it is the squared distance between b and b−ib_{-i}, measured in the metric X⊤XX^\top X and scaled by pσ^2p\hat\sigma^2. Since (b−b−i)⊤X⊤X(b−b−i)=(y^−y^−i)⊤(y^−y^−i)(b - b_{-i})^\top X^\top X(b - b_{-i}) = (\hat y - \hat y_{-i})^\top(\hat y - \hat y_{-i}), it equivalently measures how much all n fitted values change when observation i is deleted. A large DiD_i (e.g. greater than 1) indicates an influential observation.

中文要点:b−b−ib - b_{-i} = 删掉第 i 个点后系数估计变了多少;DiD_i = 这个变化的"标准化长度的平方",也等于所有拟合值一起变了多少。DiD_i 大 ⇒ 第 i 个点单独就能明显改变拟合结果 ⇒ 影响点。

✍️ iv) [6 分] 证明 Di=ri2phii1−hiiD_i = \dfrac{r_i^2}{p}\dfrac{h_{ii}}{1 - h_{ii}}(和第 15 章 P15-2 是同一个证明)

第 1 步:从 (3) 得到 b−b−ib - b_{-i}(移项):

b−b−i=(X⊤X)−1xiei1−hii.b - b_{-i} = \frac{(X^\top X)^{-1}x_ie_i}{1 - h_{ii}}.

第 2 步:代入 (2) 的分子。eie_i 和 1−hii1 - h_{ii} 都是数,可以提到外面;转置时 (X⊤X)−1(X^\top X)^{-1} 对称,所以 ((X⊤X)−1xi)⊤=xi⊤(X⊤X)−1\big((X^\top X)^{-1}x_i\big)^\top = x_i^\top(X^\top X)^{-1}:

(b−b−i)⊤(X⊤X)(b−b−i)=ei2(1−hii)2 xi⊤(X⊤X)−1(X⊤X)(X⊤X)−1⏟=Ixi=ei2(1−hii)2 xi⊤(X⊤X)−1xi⏟=hii=ei2 hii(1−hii)2.\begin{aligned}(b - b_{-i})^\top(X^\top X)(b - b_{-i}) &= \frac{e_i^2}{(1 - h_{ii})^2}\,x_i^\top(X^\top X)^{-1}\underbrace{(X^\top X)(X^\top X)^{-1}}_{=I}x_i\\ &= \frac{e_i^2}{(1 - h_{ii})^2}\,\underbrace{x_i^\top(X^\top X)^{-1}x_i}_{=h_{ii}} = \frac{e_i^2\,h_{ii}}{(1 - h_{ii})^2}.\end{aligned}

第 3 步:除以 pσ^2p\hat\sigma^2,凑出 ri2r_i^2。内学生化残差 ri=eiσ^1−hiir_i = \dfrac{e_i}{\hat\sigma\sqrt{1 - h_{ii}}},所以 ri2=ei2σ^2(1−hii)r_i^2 = \dfrac{e_i^2}{\hat\sigma^2(1 - h_{ii})}。把分母里的两个 (1−hii)(1 - h_{ii}) 拆开,一个给 ri2r_i^2,一个留下:

Di=ei2 hiipσ^2(1−hii)2=1p⋅ei2σ^2(1−hii)⏟=ri2⋅hii1−hii=ri2p hii1−hii. ∎D_i = \frac{e_i^2\,h_{ii}}{p\hat\sigma^2(1 - h_{ii})^2} = \frac1p\cdot\underbrace{\frac{e_i^2}{\hat\sigma^2(1 - h_{ii})}}_{=r_i^2}\cdot\frac{h_{ii}}{1 - h_{ii}} = \frac{r_i^2}{p}\,\frac{h_{ii}}{1 - h_{ii}}.\ ∎

结论的含义(加一句加分):DiD_i 由两部分相乘:ri2r_i^2(残差大不大)和 hii/(1−hii)h_{ii}/(1 - h_{ii})(杠杆高不高)。两者都大才会是影响点,这正是 i) 里 11、13 是影响点而 12 不是的原因。

6 分怎么给:写出 b−b−ib - b_{-i}(1 分);代入并正确转置(2 分);用 hiih_{ii} 的定义化简(1 分);用 rir_i 的定义凑出结果(2 分)。

✅ 本章检查清单
  • Q1:中心化后 ∑(xi−xˉ)=0\sum(x_i - \bar x) = 0 是所有化简的关键;b0=yˉb_0 = \bar y、b1=Sxy/Sxxb_1 = S_{xy}/S_{xx};不相关 + 联合正态 ⇒ 独立 ⇒ χ22\chi^2_2
  • Q2:Residuals vs Fitted 看线性,Q-Q 看正态,Scale-Location 看方差,Residuals vs Leverage 看影响点;预测时代 log(177);Bidders 的检验看 anova 的第二行;外学生化残差 df = n − p − 1
  • Q3:J=11⊤J = \mathbf 1\mathbf 1^\top;X⊤HX=X⊤XX^\top HX = X^\top X;tr(H)=p\mathrm{tr}(H) = p;E(y⊤Ay)=tr(AV)+μ⊤AμE(y^\top Ay) = \mathrm{tr}(AV) + \mu^\top A\mu,写出 V=σ2IV = \sigma^2I
  • Q4:p 是参数个数(含截距);Cook's D > 1 是影响点;能默写 iv) 的三步证明
  • 限时练习:不看答案,Q1 + Q3 各 20 分钟,Q2 + Q4 各 15 分钟

第 28 章 · 2019 T3 期末完整解答(4 题 × 15 分,纸笔考试)

本章目标
把 2019 T3 期末整张卷子逐题、逐小问做一遍。2019 是线下纸笔考试:2 小时,4 题 × 15 分,没有电脑,所有 R 输出都印在卷子上,只能读输出、手算。
今年是机房 Möbius 考试,形式和 2019 不同,但证明题(Q1、Q3)和读输出的分析题(Q2)思路完全通用。Q4 的 logistic 回归在今年的优先级最低(见第 20 章),Q4(b) 的 Cp 推导值得会。
原卷:past_final_exams/MATH2831_2019.pdf 配套脚本:R/ch28_2019_final.R(用 R 当计算器核对每一个数,并用模拟验证证明题的结论)。
📚 做这份卷子要用到的知识
题知识点Lab Test 学过?详细讲解
Q1 (a)SLR 的 SSres、SSreg、E(b12)E(b_1^2)✅ 学过第 3、4 章
Q1 (b)(c)随机向量的协方差矩阵、帽子矩阵、E(y⊤Ay)E(y^\top Ay)部分学过第 5、8、11 章,本章会先补
Q2 (a)模型假设、读诊断图、变换和 WLS假设学过;变换、WLS 是新内容第 16、17、25 章
Q2 (b)读 summary 和 anova、t 检验、CI、F 检验✅ 学过第 6、7 章
Q3多元正态 MLE、BLUE、Gauss–Markov 定理❌ 新内容本章会先补
Q4 (a)logistic 回归❌ 新内容(优先级最低)第 20 章,本章会先补
Q4 (b)Mallows' Cp、R²、adjusted R²✅ 学过第 9 章

28.1 Q1 [15 分]:SLR 的方差估计 + 协方差矩阵(证明)

📄 2019 期末 Q1
a) [6 marks] In the simple linear regression model, the estimator of the variance σ² is given by σ^2=1n−2∑i=1n(yi−b0−b1xi)2\hat\sigma^2 = \dfrac{1}{n-2}\sum_{i=1}^n(y_i - b_0 - b_1x_i)^2.
i) [3 marks] Show that σ^2=Syy−b12Sxxn−2\hat\sigma^2 = \dfrac{S_{yy} - b_1^2S_{xx}}{n-2}.
ii) [3 marks] Hence or otherwise show that SSreg=b12SxxSS_{reg} = b_1^2S_{xx} and E(SSreg)=σ2+β12SxxE(SS_{reg}) = \sigma^2 + \beta_1^2S_{xx}. Hint: Use the fact that b1∼N(β1,σ2Sxx−1)b_1 \sim N(\beta_1, \sigma^2S_{xx}^{-1}).
b) [4 marks] Let Y be n × 1 and Z be p × 1 random vectors, and let V be their n × p covariance matrix, so V=Cov(Y,Z)=E[(Y−E[Y])(Z−E[Z])T]V = \mathrm{Cov}(Y, Z) = E[(Y - E[Y])(Z - E[Z])^T]. Suppose A and B are n × n and p × p matrices respectively, show that Cov(AY,BZ)=AVBT\mathrm{Cov}(AY, BZ) = AVB^T.
c) [5 marks] Consider the multiple linear regression model y=Xβ+εy = X\beta + \varepsilon, where X is an n × p full rank design matrix, β is a p × 1 vector of parameters and ε∼N(0,σ2I)\varepsilon \sim N(0, \sigma^2I), where I is an n × n identity matrix. The n × n hat matrix is denoted by H=X(X⊤X)−1X⊤H = X(X^\top X)^{-1}X^\top.
i) [3 marks] Show that the covariance between y−y^=(I−H)yy - \hat y = (I - H)y and the least squares estimator of β, b=(X⊤X)−1X⊤yb = (X^\top X)^{-1}X^\top y (1), is a matrix of zeros. Hint: Use the result in part b).
ii) [2 marks] Prove that the estimator of the error variance σ^2=y⊤(I−X(X⊤X)−1X⊤)yn−p\hat\sigma^2 = \dfrac{y^\top(I - X(X^\top X)^{-1}X^\top)y}{n - p} is an unbiased estimator of σ².
📚 先回忆 SLR 的记号(formula sheet 第 1 页)

Sxx=∑(xi−xˉ)2S_{xx} = \sum(x_i - \bar x)^2,Sxy=∑(xi−xˉ)(yi−yˉ)S_{xy} = \sum(x_i - \bar x)(y_i - \bar y),Syy=∑(yi−yˉ)2=SStotalS_{yy} = \sum(y_i - \bar y)^2 = SS_{total};b1=Sxy/Sxxb_1 = S_{xy}/S_{xx},b0=yˉ−b1xˉb_0 = \bar y - b_1\bar x。

两个马上要用的等式:Sxy=b1SxxS_{xy} = b_1S_{xx}(由 b1b_1 的定义);SStotal=SSreg+SSresSS_{total} = SS_{reg} + SS_{res}(ANOVA 分解)。

✍️ a) i) [3 分] σ^2=Syy−b12Sxxn−2\hat\sigma^2 = \dfrac{S_{yy} - b_1^2S_{xx}}{n-2}

第 1 步:把 b0b_0 代掉。b0=yˉ−b1xˉb_0 = \bar y - b_1\bar x,所以每个残差

yi−b0−b1xi=yi−yˉ+b1xˉ−b1xi=(yi−yˉ)−b1(xi−xˉ).y_i - b_0 - b_1x_i = y_i - \bar y + b_1\bar x - b_1x_i = (y_i - \bar y) - b_1(x_i - \bar x).

第 2 步:平方再求和,用 (a−c)2=a2−2ac+c2(a - c)^2 = a^2 - 2ac + c^2:

∑(yi−b0−b1xi)2=∑(yi−yˉ)2⏟Syy−2b1∑(xi−xˉ)(yi−yˉ)⏟Sxy+b12∑(xi−xˉ)2⏟Sxx.\sum(y_i - b_0 - b_1x_i)^2 = \underbrace{\sum(y_i - \bar y)^2}_{S_{yy}} - 2b_1\underbrace{\sum(x_i - \bar x)(y_i - \bar y)}_{S_{xy}} + b_1^2\underbrace{\sum(x_i - \bar x)^2}_{S_{xx}}.

第 3 步:用 Sxy=b1SxxS_{xy} = b_1S_{xx}:

=Syy−2b1⋅b1Sxx+b12Sxx=Syy−b12Sxx.= S_{yy} - 2b_1\cdot b_1S_{xx} + b_1^2S_{xx} = S_{yy} - b_1^2S_{xx}.

两边除以 n − 2,得证。∎

✍️ a) ii) [3 分] SSreg=b12SxxSS_{reg} = b_1^2S_{xx},E(SSreg)=σ2+β12SxxE(SS_{reg}) = \sigma^2 + \beta_1^2S_{xx}

第一部分:SSres=(n−2)σ^2=Syy−b12SxxSS_{res} = (n-2)\hat\sigma^2 = S_{yy} - b_1^2S_{xx}(由 i)),而 SStotal=SyySS_{total} = S_{yy},所以

SSreg=SStotal−SSres=Syy−(Syy−b12Sxx)=b12Sxx.SS_{reg} = SS_{total} - SS_{res} = S_{yy} - (S_{yy} - b_1^2S_{xx}) = b_1^2S_{xx}.

(也可以直接算:y^i−yˉ=b0+b1xi−yˉ=b1(xi−xˉ)\hat y_i - \bar y = b_0 + b_1x_i - \bar y = b_1(x_i - \bar x),平方求和就是 b12Sxxb_1^2S_{xx}。)

第二部分:关键是 E(b12)E(b_1^2)。由 Var(Z)=E(Z2)−[E(Z)]2\mathrm{Var}(Z) = E(Z^2) - [E(Z)]^2 得 E(Z2)=Var(Z)+[E(Z)]2E(Z^2) = \mathrm{Var}(Z) + [E(Z)]^2。用提示 E(b1)=β1E(b_1) = \beta_1、Var(b1)=σ2/Sxx\mathrm{Var}(b_1) = \sigma^2/S_{xx}:

E(SSreg)=Sxx E(b12)=Sxx(σ2Sxx+β12)=σ2+β12Sxx.  ∎E(SS_{reg}) = S_{xx}\,E(b_1^2) = S_{xx}\Big(\frac{\sigma^2}{S_{xx}} + \beta_1^2\Big) = \sigma^2 + \beta_1^2S_{xx}.\ \ ∎

得分点:E(b12)=Var(b1)+[E(b1)]2E(b_1^2) = \mathrm{Var}(b_1) + [E(b_1)]^2 这一步是核心(2 分)。SxxS_{xx} 只和 x 有关,是常数,可以提到期望外面。2020 Q3 用矩阵方法证明了同一个结论(第 24 章)。

✍️ b) [4 分] Cov(AY,BZ)=AVB⊤\mathrm{Cov}(AY, BZ) = AVB^\top

A、B 是常数矩阵,所以 E(AY)=A E(Y)E(AY) = A\,E(Y),E(BZ)=B E(Z)E(BZ) = B\,E(Z)。按定义:

Cov(AY,BZ)=E[(AY−A E[Y])(BZ−B E[Z])⊤]=E[A(Y−E[Y]) (B(Z−E[Z]))⊤]=E[A(Y−E[Y])(Z−E[Z])⊤B⊤]=A E[(Y−E[Y])(Z−E[Z])⊤] B⊤=AVB⊤.\begin{aligned} \mathrm{Cov}(AY, BZ) &= E\big[(AY - A\,E[Y])(BZ - B\,E[Z])^\top\big] = E\big[A(Y - E[Y])\,\big(B(Z - E[Z])\big)^\top\big]\\ &= E\big[A(Y - E[Y])(Z - E[Z])^\top B^\top\big] = A\,E\big[(Y - E[Y])(Z - E[Z])^\top\big]\,B^\top = AVB^\top. \end{aligned}

每一步的理由:提出 A、B(分配律);(BW)⊤=W⊤B⊤(BW)^\top = W^\top B^\top;常数矩阵可以提到期望外面(左边的 A 和右边的 B⊤B^\top)。∎

注意:证明里没用到 A、B 是方阵,只要乘法尺寸对得上就成立。c) i) 里的 B 就是 p × n 的,结论照样能用。

✍️ c) i) [3 分] Cov((I−H)y, b)=0\mathrm{Cov}\big((I - H)y,\ b\big) = 0

两个都是同一个 y 的线性变换:A=I−HA = I - H(n × n),B=(X⊤X)−1X⊤B = (X^\top X)^{-1}X^\top(p × n),Y = Z = y,所以 V=Cov(y,y)=Var(y)=σ2IV = \mathrm{Cov}(y, y) = \mathrm{Var}(y) = \sigma^2I。由 b):

Cov((I−H)y, b)=(I−H) σ2I ((X⊤X)−1X⊤)⊤=σ2(I−H)X(X⊤X)−1.\mathrm{Cov}\big((I - H)y,\ b\big) = (I - H)\,\sigma^2I\,\big((X^\top X)^{-1}X^\top\big)^\top = \sigma^2(I - H)X(X^\top X)^{-1}.

(转置:((X⊤X)−1X⊤)⊤=X(X⊤X)−1\big((X^\top X)^{-1}X^\top\big)^\top = X(X^\top X)^{-1},因为 (X⊤X)−1(X^\top X)^{-1} 对称。)关键一步:

HX=X(X⊤X)−1X⊤X=X⇒(I−H)X=X−X=0.HX = X(X^\top X)^{-1}X^\top X = X \quad\Rightarrow\quad (I - H)X = X - X = 0.

所以协方差 =σ2⋅0⋅(X⊤X)−1=0= \sigma^2\cdot 0\cdot(X^\top X)^{-1} = 0(n × p 的零矩阵)。∎

意义:残差和系数估计不相关;正态时就是独立,这正是 t 检验里分子 b 和分母 σ^\hat\sigma 独立的原因。

✍️ c) ii) [2 分] σ^2\hat\sigma^2 无偏

用 E(y⊤Ay)=tr(AV)+μ⊤AμE(y^\top Ay) = \mathrm{tr}(AV) + \mu^\top A\mu(formula sheet),A=I−HA = I - H,μ=E(y)=Xβ\mu = E(y) = X\beta,V=σ2IV = \sigma^2I:

E[y⊤(I−H)y]=σ2 tr(I−H)+β⊤X⊤(I−H)X⏟= 0β=σ2(n−p).E\big[y^\top(I - H)y\big] = \sigma^2\,\mathrm{tr}(I - H) + \beta^\top X^\top\underbrace{(I - H)X}_{=\,0}\beta = \sigma^2(n - p).

迹:tr(In−H)=n−tr(X(X⊤X)−1X⊤)=n−tr((X⊤X)−1X⊤X)=n−tr(Ip)=n−p\mathrm{tr}(I_n - H) = n - \mathrm{tr}\big(X(X^\top X)^{-1}X^\top\big) = n - \mathrm{tr}\big((X^\top X)^{-1}X^\top X\big) = n - \mathrm{tr}(I_p) = n - p(tr(AB)=tr(BA)\mathrm{tr}(AB) = \mathrm{tr}(BA))。所以 E(σ^2)=σ2(n−p)/(n−p)=σ2E(\hat\sigma^2) = \sigma^2(n-p)/(n-p) = \sigma^2。∎

和 2021 Q4 (d) 是同一个结论,那里用 ε 写,这里用 y 写:用 y 时多了 μ⊤Aμ\mu^\top A\mu 那一项,要说明它是 0。

Rch28 · 28.1:数值验证(考试不用)
set.seed(1)
n <- 15; x <- runif(n, 0, 10); beta0 <- 1; beta1 <- 0.8; sigma <- 2
Sxx <- sum((x - mean(x))^2)
y <- beta0 + beta1 * x + rnorm(n, sd = sigma)
m <- lm(y ~ x); b1 <- coef(m)[2]; Syy <- sum((y - mean(y))^2)
c(def = sum(residuals(m)^2) / (n - 2), short = unname((Syy - b1^2 * Sxx) / (n - 2)))   # a i)
SSreg <- replicate(20000, {
  yy <- beta0 + beta1 * x + rnorm(n, sd = sigma)
  coef(lm(yy ~ x))[2]^2 * Sxx
})
c(simulated = mean(SSreg), theory = sigma^2 + beta1^2 * Sxx)                         # a ii)
Console 输出
     def    short
3.503262 3.503262
simulated    theory
 83.14182  82.83362

28.2 Q2 [15 分]:汽车油耗,只看输出作答

📄 2019 期末 Q2
A study was conducted to investigate the fuel efficiency of cars measured in Mpg or miles per gallon (number of observations n = 398). A multiple linear regression model was fitted with the response Mpg and predictors Cylinder (number of cylinders), Weight (the weight of the car) and Displacement (swept volume of pistons). We investigate different transforms of the response. Answer part a) of this question with the help of the following outputs. [Diagnostic plots for ∛Mpg ~ Cylinder + Weight + Displacement and log(Mpg) ~ Cylinder + Weight + Displacement, see below]
a) [7 marks] i) [2 marks] What are the standard model assumptions of the multiple linear regression model? Give details. ii) [3 marks] By examining the diagnostic plots, discuss which of the above models is better suited for analysing the data set. iii) [2 marks] Suppose the data set violates the non-constant variance assumption. State and discuss two potential methods to overcome this issue.
b) [8 marks] The response Mpg was log-transformed and the model was refitted using the transformed response. The summary() and anova() outputs of the refitted model are given below. [see below] You may also use the following output: qf(0.95,2,394) = 3.018626, qf(0.95,1,396) = 3.865048, qt(0.975,394) = 1.966003, qt(0.95,396) = 1.648711.
i) [1 mark] What percentage of variation in the response is explained by the model?
ii) [2 marks] State the value of the partial t statistic and p-value for testing for an effect of weight in the presence of the other predictors. What is the conclusion of this test using a 5% level of significance?
iii) [2 marks] Compute a 95% confidence interval for β₂.
iv) [2 marks] Compute the value of the F statistic used for testing the hypothesis H0:β2=β3=0H_0: \beta_2 = \beta_3 = 0 vs H1:β2≠0H_1: \beta_2 \ne 0 or β3≠0\beta_3 \ne 0, and give your conclusion of the test when using a 5% level of significance.
v) [1 mark] Test under a 5% significance level, whether the model containing predictors weight, cylinders and displacement is preferred over the model containing only weight and cylinders. Give your conclusion.

第一组图:∛Mpg(立方根)

2019 Q2 立方根 Mpg 模型的四张诊断图

第二组图:log(Mpg)

2019 Q2 log(Mpg) 模型的四张诊断图
✍️ a) i) [2 分] 多元线性回归的标准假设

The model is y=Xβ+εy = X\beta + \varepsilon, with X a fixed n × p full rank design matrix, and:

  1. Linearity: the mean response is a linear function of the parameters, E(y)=XβE(y) = X\beta, i.e. E(εi)=0E(\varepsilon_i) = 0.
  2. Constant variance: Var(εi)=σ2\mathrm{Var}(\varepsilon_i) = \sigma^2 for all i.
  3. Uncorrelated (independent) errors: Cov(εi,εj)=0\mathrm{Cov}(\varepsilon_i, \varepsilon_j) = 0 for i ≠ j; together with 2, Var(ε)=σ2I\mathrm{Var}(\varepsilon) = \sigma^2I.
  4. Normality: εi\varepsilon_i are normally distributed (needed for t and F tests and intervals), so ε∼N(0,σ2I)\varepsilon \sim N(0, \sigma^2I).

"Give details" 就是每条都写成公式。写全四条 2 分。

✍️ a) ii) [3 分] 哪个模型更好

两组图逐张对比(读法见第 25 章):

图∛Mpg 模型log(Mpg) 模型
Residuals vs Fitted红线明显弯曲(中间低、两头高);右边点散得很开红线几乎是平的,点在 0 上下随机
Normal Q-Q右上端明显翘到线上方(右偏 / 重右尾)基本贴着直线,只有 388、365、112 几个端点偏离
Scale-Location红线随拟合值上升 ⇒ 方差变大红线大致水平
Residuals vs Leverage两个模型都没有点越过 Cook's 0.5;14 号杠杆最高(约 0.125)但残差不大

可以直接写的答案:

For the cube-root model, the Residuals vs Fitted plot shows curvature (a U-shaped red line) and the spread of the residuals increases with the fitted values, which is confirmed by the increasing trend in the Scale-Location plot; the Normal Q-Q plot shows the upper tail departing above the line (right skewness). So the linearity, constant variance and normality assumptions are questionable. For the log model, the residuals are randomly scattered around zero with no clear pattern, the Scale-Location plot is roughly flat and the Q-Q plot is close to a straight line except for a few extreme points (388, 365, 112). Neither model has points outside the Cook's distance contour of 0.5. Hence the log(Mpg) model is better suited for analysing the data.

✍️ a) iii) [2 分] 方差不恒定时的两种补救
  1. Variance-stabilising transformation of the response, e.g. log(y), √y or a Box–Cox type power transformation. If the error standard deviation grows with the mean, a log transform makes the variance roughly constant (as in part ii).
  2. Weighted least squares: if Var(εi)=σ2/wi\mathrm{Var}(\varepsilon_i) = \sigma^2/w_i with known (or estimated) weights, minimise ∑wi(yi−xi⊤β)2\sum w_i(y_i - x_i^\top\beta)^2, giving bw=(X⊤WX)−1X⊤Wyb_w = (X^\top WX)^{-1}X^\top Wy with W=diag(wi)W = \mathrm{diag}(w_i); observations with larger variance get smaller weight.

每个方法 1 分:写出名字 + 一句怎么做。详见第 16、17 章。

b) 用到的输出(印在卷子上):

lm(formula = log(mpg) ~ cylinders + weight + displacement, data = mpg)
                Estimate Std. Error t value Pr(>|t|)
(Intercept)    4.048e+00  5.526e-02  73.255   <2e-16 ***
cylinders     -1.801e-02  1.534e-02  -1.173   0.2413
weight        -2.424e-04  2.652e-05  -9.140   <2e-16 ***
displacement  -6.650e-04  3.084e-04  -2.156   0.0317 *
Residual standard error: 0.1607 on 394 degrees of freedom
Multiple R-squared: 0.7779, Adjusted R-squared: 0.7762

> anova(model)
              Df  Sum Sq Mean Sq   F value Pr(>F)
cylinders      1 31.2302 31.2302 1209.4318 < 2e-16 ***
weight         1  4.2762  4.2762  165.6022 < 2e-16 ***
displacement   1  0.1200  0.1200    4.6487 0.03168 *
Residuals    394 10.1740  0.0258

先定好记号:模型 log⁡(Mpg)=β0+β1 cylinders+β2 weight+β3 displacement+ε\log(Mpg) = \beta_0 + \beta_1\,\text{cylinders} + \beta_2\,\text{weight} + \beta_3\,\text{displacement} + \varepsilon。所以 β₂ 是 weight,β₃ 是 displacement(按 summary 的行顺序)。

✍️ b) i) [1 分] 解释了多少变异

R2=0.7779R^2 = 0.7779,即 77.79% of the variation in log(Mpg) is explained by the model.(用 Multiple R-squared,不是 adjusted。)

✍️ b) ii) [2 分] weight 的 partial t 检验

H0:β2=0H_0: \beta_2 = 0 vs H1:β2≠0H_1: \beta_2 \ne 0(其他预测变量都在模型里)。weight 那一行:t = −9.140,p < 2e-16。

Since p < 0.05, reject H0: weight has a significant effect on log(Mpg) in the presence of cylinders and displacement.

✍️ b) iii) [2 分] β₂ 的 95% 置信区间

公式 b2±t0.025, n−p⋅se(b2)b_2 \pm t_{0.025,\,n-p}\cdot\text{se}(b_2),n − p = 398 − 4 = 394,题目给了 qt(0.975, 394) = 1.966003:

−2.424×10−4±1.966003×2.652×10−5=−2.424×10−4±0.5214×10−4=(−2.945×10−4, −1.903×10−4).-2.424\times10^{-4} \pm 1.966003\times 2.652\times10^{-5} = -2.424\times10^{-4} \pm 0.5214\times10^{-4} = (-2.945\times10^{-4},\ -1.903\times10^{-4}).

区间不包含 0,和 ii) 的结论一致。坑:题目还给了 qt(0.95, 396),那是单侧、df 也不对,是干扰项。

✍️ b) iv) [2 分] 检验 H0:β2=β3=0H_0: \beta_2 = \beta_3 = 0

想清楚在比较哪两个模型:H0 成立时模型只剩 cylinders;所以是比较"只有 cylinders"和"全模型"。多出来的平方和就是 anova 表里 cylinders 之后加进来的 weight、displacement 两行(anova 是按顺序加变量的):

F=(4.2762+0.1200)/210.1740/394=2.19810.02582=85.12∼F2,394 under H0.F = \frac{(4.2762 + 0.1200)/2}{10.1740/394} = \frac{2.1981}{0.02582} = 85.12 \sim F_{2,394}\ \text{under } H_0.

Since F = 85.12 > F_{0.95;2,394} = 3.0186, reject H0 at the 5% level: at least one of weight and displacement is useful in the model that contains cylinders.

为什么能这样拆:R(β2,β3∣β0,β1)=R(β2∣β0,β1)+R(β3∣β0,β1,β2)=4.2762+0.1200R(\beta_2, \beta_3 \mid \beta_0, \beta_1) = R(\beta_2 \mid \beta_0, \beta_1) + R(\beta_3 \mid \beta_0, \beta_1, \beta_2) = 4.2762 + 0.1200(序贯平方和可以相加)。分子 df = 2(检验 2 个系数),分母用全模型的 MSE。

✍️ b) v) [1 分] 全模型 vs 只有 weight 和 cylinders

就是检验 H0:β3=0H_0: \beta_3 = 0(displacement 最后加入)。anova 表最后一行(displacement 是最后进入的):F = 4.6487,p = 0.03168;也等于 summary 里 t2=(−2.156)2=4.648t^2 = (-2.156)^2 = 4.648,p 值相同。

p = 0.0317 < 0.05 (equivalently F = 4.65 > 3.87), so reject H0: the model with weight, cylinders and displacement is preferred over the model with only weight and cylinders.

坑:这里能直接用 anova 最后一行,是因为 displacement 恰好是最后一个加进去的。如果要检验的变量不在最后,就不能直接读 anova 那一行(要用 summary 的 t 检验)。

Rch28 · 28.2:核对 b) 的数(R 当计算器)
b2 <- -2.424e-04; se2 <- 2.652e-05
b2 + c(-1, 1) * 1.966003 * se2                      # iii)
MSres <- 10.1740 / 394
((4.2762 + 0.1200) / 2) / MSres                     # iv)
0.1200 / MSres; (-2.156)^2                          # v)
Console 输出
[1] -0.0002945384 -0.0001902616
[1] 85.12398
[1] 4.64714
[1] 4.648336

28.3 Q3 [15 分]:广义线性模型的 MLE、BLUE 和 Gauss–Markov 定理

📄 2019 期末 Q3
Suppose you are given the linear model y=Xβ+εy = X\beta + \varepsilon, where X is an n × p full rank design matrix, β is a p × 1 vector of parameters and ε is a zero mean Gaussian random vector with covariance matrix V, that is, ε∼N(0,V)\varepsilon \sim N(0, V).
a) [5 marks] Derive the maximum likelihood estimator of β. Hint: the density of an n × 1 multivariate Gaussian vector y with mean μ and covariance matrix Σ is given by fy(y)=1(2π)n/2∣det⁡(Σ)∣1/2exp⁡{−12(y−μ)⊤Σ−1(y−μ)}f_y(y) = \dfrac{1}{(2\pi)^{n/2}|\det(\Sigma)|^{1/2}}\exp\Big\{-\dfrac12(y - \mu)^\top\Sigma^{-1}(y - \mu)\Big\}.
b) [2 marks] Verify that when V = σ²I, where I is the n × n identity matrix, the maximum likelihood estimator is equivalent to the least squares estimator: b=(X⊤X)−1X⊤yb = (X^\top X)^{-1}X^\top y (2).
c) [3 marks] The least squares estimator (2) enjoys the optimality property known as BLUE when the covariance matrix of ε is V = σ²I. Explain what a BLUE estimator is.
d) [5 marks] Prove the Gauss Markov theorem, that is, show that the estimator (2) is BLUE under the assumption that V = σ²I. Hint: Let b~=((X⊤X)−1X⊤+B)y\tilde b = ((X^\top X)^{-1}X^\top + B)y be any other unbiased linear estimator. Note that when B = 0 we get b~=b\tilde b = b. Then, show that Var(b~)=σ2(BB⊤+(X⊤X)−1)\mathrm{Var}(\tilde b) = \sigma^2(BB^\top + (X^\top X)^{-1}).
📚 需要先补:矩阵求导 和 "一个矩阵比另一个大"是什么意思

矩阵求导(formula sheet 上有):对向量 β 求导,∂∂β(a⊤β)=a\dfrac{\partial}{\partial\beta}(a^\top\beta) = a,∂∂β(β⊤Aβ)=Aβ+A⊤β\dfrac{\partial}{\partial\beta}(\beta^\top A\beta) = A\beta + A^\top\beta(A 对称时 = 2Aβ)。和一元的 (ax)′=a(ax)' = a、(ax2)′=2ax(ax^2)' = 2ax 一个道理。

半正定:矩阵 M 叫半正定(记 M ≥ 0),如果对任意向量 c 都有 c⊤Mc≥0c^\top Mc \ge 0。"估计 1 的协方差矩阵 − 估计 2 的协方差矩阵 ≥ 0"的意思是:估计任何线性组合 c⊤βc^\top\beta 时,估计 2 的方差都不比估计 1 大。

一个常用事实:任何 BB⊤BB^\top 都是半正定的,因为 c⊤BB⊤c=(B⊤c)⊤(B⊤c)=∥B⊤c∥2≥0c^\top BB^\top c = (B^\top c)^\top(B^\top c) = \|B^\top c\|^2 \ge 0。

✍️ a) [5 分] 推导 β 的最大似然估计

第 1 步:写似然。y=Xβ+εy = X\beta + \varepsilon,ε ~ N(0, V),所以 y∼N(Xβ,V)y \sim N(X\beta, V)。代入提示的密度,μ = Xβ,Σ = V:

L(β)=1(2π)n/2∣det⁡V∣1/2exp⁡{−12(y−Xβ)⊤V−1(y−Xβ)}.L(\beta) = \frac{1}{(2\pi)^{n/2}|\det V|^{1/2}}\exp\Big\{-\frac12(y - X\beta)^\top V^{-1}(y - X\beta)\Big\}.

第 2 步:取 log:

log⁡L(β)=−n2log⁡(2π)−12log⁡∣det⁡V∣⏟与 β 无关−12(y−Xβ)⊤V−1(y−Xβ).\log L(\beta) = \underbrace{-\frac n2\log(2\pi) - \frac12\log|\det V|}_{\text{与 } \beta \text{ 无关}} - \frac12(y - X\beta)^\top V^{-1}(y - X\beta).

第 3 步:把二次型展开。V−1V^{-1} 对称,而 y⊤V−1Xβy^\top V^{-1}X\beta 是一个数,等于它的转置 β⊤X⊤V−1y\beta^\top X^\top V^{-1}y,两个交叉项合并:

(y−Xβ)⊤V−1(y−Xβ)=y⊤V−1y−2β⊤X⊤V−1y+β⊤X⊤V−1Xβ.(y - X\beta)^\top V^{-1}(y - X\beta) = y^\top V^{-1}y - 2\beta^\top X^\top V^{-1}y + \beta^\top X^\top V^{-1}X\beta.

第 4 步:对 β 求导令为 0(a=X⊤V−1ya = X^\top V^{-1}y,A=X⊤V−1XA = X^\top V^{-1}X 对称):

∂log⁡L∂β=−12(−2X⊤V−1y+2X⊤V−1Xβ)=X⊤V−1y−X⊤V−1Xβ=0.\frac{\partial\log L}{\partial\beta} = -\frac12\big(-2X^\top V^{-1}y + 2X^\top V^{-1}X\beta\big) = X^\top V^{-1}y - X^\top V^{-1}X\beta = 0.

第 5 步:解出 β(X 满秩、V 正定 ⇒ X⊤V−1XX^\top V^{-1}X 可逆):

β^MLE=(X⊤V−1X)−1X⊤V−1y.\hat\beta_{\text{MLE}} = (X^\top V^{-1}X)^{-1}X^\top V^{-1}y.

这就是广义最小二乘(GLS)估计。二阶导 −X⊤V−1X-X^\top V^{-1}X 负定,所以是最大值。

得分点:似然 1 分;log 1 分;展开 1 分;求导 1 分;结果 1 分。

✍️ b) [2 分] V = σ²I 时等于最小二乘

V−1=1σ2IV^{-1} = \dfrac{1}{\sigma^2}I,代入 a):

β^=(1σ2X⊤X)−11σ2X⊤y=σ2(X⊤X)−1⋅1σ2X⊤y=(X⊤X)−1X⊤y=b.\hat\beta = \Big(\frac{1}{\sigma^2}X^\top X\Big)^{-1}\frac{1}{\sigma^2}X^\top y = \sigma^2(X^\top X)^{-1}\cdot\frac{1}{\sigma^2}X^\top y = (X^\top X)^{-1}X^\top y = b.

((cA)−1=c−1A−1(cA)^{-1} = c^{-1}A^{-1},两个 σ² 抵消。)

✍️ c) [3 分] 什么是 BLUE

BLUE stands for Best Linear Unbiased Estimator. An estimator b~\tilde b of β is:

  • Linear if it is a linear function of the observations, b~=Cy\tilde b = Cy for some fixed p × n matrix C;
  • Unbiased if E(b~)=βE(\tilde b) = \beta for all β;
  • Best if, among all linear unbiased estimators, it has the smallest variance, in the sense that Var(b~)−Var(b)\mathrm{Var}(\tilde b) - \mathrm{Var}(b) is positive semi-definite for any other linear unbiased b~\tilde b; equivalently Var(c⊤b)≤Var(c⊤b~)\mathrm{Var}(c^\top b) \le \mathrm{Var}(c^\top\tilde b) for every vector c (in particular each bjb_j has the smallest variance).

三个词各 1 分。BLUE 只需要 E(ε)=0E(\varepsilon) = 0、Var(ε)=σ2I\mathrm{Var}(\varepsilon) = \sigma^2I,不需要正态(2014 Q6(c) 专门问过这一点)。

✍️ d) [5 分] 证明 Gauss–Markov 定理

设 b~=((X⊤X)−1X⊤+B)y\tilde b = \big((X^\top X)^{-1}X^\top + B\big)y 是任意一个线性无偏估计(B 是 p × n 常数矩阵)。

第 1 步:无偏 ⇒ BX = 0。

E(b~)=((X⊤X)−1X⊤+B)Xβ=β+BXβ.E(\tilde b) = \big((X^\top X)^{-1}X^\top + B\big)X\beta = \beta + BX\beta.

要对所有 β 都等于 β,必须 BXβ=0BX\beta = 0 对所有 β 成立,所以 BX=0BX = 0(因此也有 X⊤B⊤=(BX)⊤=0X^\top B^\top = (BX)^\top = 0)。

第 2 步:算方差。记 C=(X⊤X)−1X⊤+BC = (X^\top X)^{-1}X^\top + B,Var(b~)=C Var(y) C⊤=σ2CC⊤\mathrm{Var}(\tilde b) = C\,\mathrm{Var}(y)\,C^\top = \sigma^2CC^\top。展开 CC⊤CC^\top 的四项:

CC⊤=(X⊤X)−1X⊤X(X⊤X)−1+(X⊤X)−1X⊤B⊤⏟= 0+BX⏟= 0(X⊤X)−1+BB⊤=(X⊤X)−1+BB⊤.\begin{aligned} CC^\top &= (X^\top X)^{-1}X^\top X(X^\top X)^{-1} + (X^\top X)^{-1}\underbrace{X^\top B^\top}_{=\,0} + \underbrace{BX}_{=\,0}(X^\top X)^{-1} + BB^\top\\ &= (X^\top X)^{-1} + BB^\top. \end{aligned}

所以 Var(b~)=σ2(BB⊤+(X⊤X)−1)\mathrm{Var}(\tilde b) = \sigma^2\big(BB^\top + (X^\top X)^{-1}\big),这就是提示要你证的式子。

第 3 步:比较。Var(b)=σ2(X⊤X)−1\mathrm{Var}(b) = \sigma^2(X^\top X)^{-1}(B = 0 的情形),所以

Var(b~)−Var(b)=σ2BB⊤,\mathrm{Var}(\tilde b) - \mathrm{Var}(b) = \sigma^2BB^\top,

而 BB⊤BB^\top 半正定:对任意 c,c⊤BB⊤c=∥B⊤c∥2≥0c^\top BB^\top c = \|B^\top c\|^2 \ge 0。因此 Var(c⊤b~)≥Var(c⊤b)\mathrm{Var}(c^\top\tilde b) \ge \mathrm{Var}(c^\top b) 对所有 c 成立,特别地 Var(b~j)≥Var(bj)\mathrm{Var}(\tilde b_j) \ge \mathrm{Var}(b_j)。所以最小二乘估计 b 在所有线性无偏估计中方差最小,即 b 是 BLUE。∎(等号只在 B = 0 即 b~=b\tilde b = b 时成立。)

得分点:BX = 0(1 分);展开 CC⊤CC^\top 并消掉交叉项(2 分);BB⊤BB^\top 半正定的论证 + 结论(2 分)。

Rch28 · 28.4:数值验证 a) 和 d)(考试不用)
set.seed(2)
n <- 25; X <- cbind(1, runif(n, 0, 5)); beta <- c(1, 2)
V <- diag(runif(n, 0.5, 4))
y <- X %*% beta + rnorm(n, sd = sqrt(diag(V)))
gls <- solve(t(X) %*% solve(V) %*% X) %*% t(X) %*% solve(V) %*% y      # a) 的公式
negloglik <- function(bb) 0.5 * t(y - X %*% bb) %*% solve(V) %*% (y - X %*% bb)
cbind(formula = gls, optim = optim(c(0, 0), negloglik)$par)          # 直接数值最大化似然
Console 输出
                   optim
[1,] 0.4375022 0.4375898
[2,] 2.1354933 2.1353150

公式和数值最大化的结果一致(差别只是 optim 的数值误差)。

28.4 Q4 [15 分]:logistic 回归 + Mallows' Cp

⚠️ 今年的优先级
Q4 (a) 的 logistic 回归在今年的课里是最后讲的内容,Lab 10 有练习,但近三年(2020、2021、2023)期末都没考,优先级最低(第 20 章)。Q4 (b) 的 Cp 推导很短,用的是帽子矩阵的迹,值得会。
📄 2019 期末 Q4
By using the titanic dataset from CRAN, we study the probability of survival of passengers on the Titanic by fitting a logistic regression model. The response Survived is a binary variable, which takes value 1 if the passenger survived the disaster and 0 otherwise. The predictor variables include two categorical variables PClass ∈ {1st class, 2nd class, 3rd class}, Sex ∈ {Male, Female} and a continuous variable Age. A logistic regression model was fitted to these data and the summary outputs are given below. [see below] You may also use: qchisq(0.95,3) = 7.814728, qchisq(0.95,4) = 9.487729, qchisq(0.95,5) = 11.0705.
a) [8 marks] i) [2 marks] Derive an expression for the estimated probability of survival in terms of the design matrix X and the vector of estimators b. Hint: Recall that the link function in the logistic model is given by g(x)=ln⁡(x1−x)g(x) = \ln\big(\frac{x}{1-x}\big) and it links the mean response and the linear model through the equality g(E(y))=Xβg(E(y)) = X\beta. ii) [2 marks] Estimate the probability of survival for a first class, female passenger aged 45. iii) [2 marks] Given that all other factors are the same, compare the odds of survival for male and female passengers. iv) [2 marks] Conduct the appropriate hypothesis test under a 5% level to test whether the model containing all the predictors is preferred over the model with only the intercept.
b) [7 marks] i) [4 marks] In this question we consider the derivation of the Mallow's Cp statistic for model selection. We suppose that there exists a 'true' regression model given by y=Xβ+εy = X\beta + \varepsilon, where the response y is a n × 1 vector, the design matrix X is a n × m matrix, β is a m × 1 vector of parameters and the error ε∼N(0,σ2I)\varepsilon \sim N(0, \sigma^2I). Let the proposed model contain only p predictors. Write y^\hat y for the vector of fitted values using the proposed model with p predictors. Show that ∑i=1nVar(y^i)σ2=p\dfrac{\sum_{i=1}^n\mathrm{Var}(\hat y_i)}{\sigma^2} = p. ii) [3 marks] Explain the role of the R² value, adjusted R² value and Mallow's Cp in model selection.
glm(formula = Survived ~ PClass + Sex + Age, family = "binomial", data = titanic)
             Estimate Std. Error z value Pr(>|z|)
(Intercept)  3.759662   0.397567   9.457  < 2e-16 ***
PClass2nd   -1.291962   0.260076  -4.968 6.78e-07 ***
PClass3rd   -2.521419   0.276657  -9.114  < 2e-16 ***
Age         -0.039177   0.007616  -5.144 2.69e-07 ***
Sexmale     -2.631357   0.201505 -13.058  < 2e-16 ***
    Null deviance: 1025.57  on 755  degrees of freedom
Residual deviance:  695.14  on 751  degrees of freedom
AIC: 705.14
📚 需要先补:logistic 回归在做什么(第 20 章)

y 只能是 0 或 1,E(yi)=P(yi=1)=πiE(y_i) = P(y_i = 1) = \pi_i 是概率,必须在 0 和 1 之间,所以不能直接写 πi=xi⊤β\pi_i = x_i^\top\beta。做法是对概率做一个变换:

log⁡πi1−πi=xi⊤β.\log\frac{\pi_i}{1 - \pi_i} = x_i^\top\beta.

左边叫 log-odds(odds = 成功概率 / 失败概率)。读系数的方法:bjb_j = 预测变量 j 增加 1(或从基准类变成这一类)时 log-odds 的变化;ebje^{b_j} = odds 变成原来的几倍(odds ratio)。

哑变量的基准类:输出里有 PClass2nd、PClass3rd、Sexmale,说明基准是 1st class 和 female(R 按字母顺序取第一个当基准)。

偏差检验(deviance):作用相当于线性模型里的 F 检验。Null deviance − Residual deviance 在 H0 下近似服从 χ2\chi^2,自由度 = 两个 df 之差。

✍️ a) i) [2 分] 估计的生存概率

令 π=E(y)\pi = E(y),由 g(π)=log⁡π1−π=ηg(\pi) = \log\frac{\pi}{1-\pi} = \eta(η = Xβ)反解:

π1−π=eη⇒π=eη(1−π)⇒π(1+eη)=eη⇒π=eη1+eη.\frac{\pi}{1-\pi} = e^\eta \Rightarrow \pi = e^\eta(1 - \pi) \Rightarrow \pi(1 + e^\eta) = e^\eta \Rightarrow \pi = \frac{e^\eta}{1 + e^\eta}.

把 β 换成估计 b,逐个元素:

π^=exp⁡(Xb)1+exp⁡(Xb),i.e. π^i=exp⁡(xi⊤b)1+exp⁡(xi⊤b)=11+exp⁡(−xi⊤b),\hat\pi = \frac{\exp(Xb)}{1 + \exp(Xb)},\qquad\text{i.e. } \hat\pi_i = \frac{\exp(x_i^\top b)}{1 + \exp(x_i^\top b)} = \frac{1}{1 + \exp(-x_i^\top b)},

其中 exp 对向量 Xb 的每个元素分别作用。

✍️ a) ii) [2 分] 1 等舱、女性、45 岁的生存概率

1st class 和 female 都是基准类,所以 PClass2nd = PClass3rd = Sexmale = 0,只剩截距和 Age:

η^=3.759662−0.039177×45=3.759662−1.762965=1.996697,\hat\eta = 3.759662 - 0.039177\times 45 = 3.759662 - 1.762965 = 1.996697, π^=e1.9966971+e1.996697=7.36508.3650=0.880.\hat\pi = \frac{e^{1.996697}}{1 + e^{1.996697}} = \frac{7.3650}{8.3650} = 0.880.

估计生存概率约 0.88。

✍️ a) iii) [2 分] 男性和女性的 odds 比较

其他条件相同时,男性的 log-odds 比女性多 bSexmale=−2.631357b_{\text{Sexmale}} = -2.631357,所以

odds(male)odds(female)=e−2.631357=0.0720.\frac{\text{odds(male)}}{\text{odds(female)}} = e^{-2.631357} = 0.0720.

Holding class and age fixed, the odds of survival for a male passenger are about 0.072 times (7.2% of) the odds for a female passenger; equivalently, the odds of survival for females are about 1/0.072 ≈ 13.9 times those of males.

✍️ a) iv) [2 分] 全模型 vs 只有截距

H0H_0:PClass2nd、PClass3rd、Age、Sexmale 四个系数全为 0;H1H_1:至少一个不为 0。

G=Null deviance−Residual deviance=1025.57−695.14=330.43∼χ755−7512=χ42 under H0.G = \text{Null deviance} - \text{Residual deviance} = 1025.57 - 695.14 = 330.43 \sim \chi^2_{755 - 751} = \chi^2_4\ \text{under } H_0.

Since 330.43 > χ²_{0.95,4} = 9.4877, reject H0 at the 5% level: the model with all predictors is preferred over the intercept-only model.

坑:df = 4(四个系数:PClass 占 2 个),不是 3(变量个数)。题目同时给了 3、4、5 三个临界值,就是考你这一点。

✍️ b) i) [4 分] ∑Var(y^i)/σ2=p\sum\mathrm{Var}(\hat y_i)/\sigma^2 = p

提议的模型用 n × p 设计矩阵 XpX_p,帽子矩阵 Hp=Xp(Xp⊤Xp)−1Xp⊤H_p = X_p(X_p^\top X_p)^{-1}X_p^\top,拟合值 y^=Hpy\hat y = H_py。不管真模型是什么,Var(y)=Var(ε)=σ2I\mathrm{Var}(y) = \mathrm{Var}(\varepsilon) = \sigma^2I。

第 1 步:Var(y^)=Hp σ2I Hp⊤=σ2HpHp=σ2Hp\mathrm{Var}(\hat y) = H_p\,\sigma^2I\,H_p^\top = \sigma^2H_pH_p = \sigma^2H_p(HpH_p 对称、幂等)。

第 2 步:Var(y^i)\mathrm{Var}(\hat y_i) 是这个矩阵的第 i 个对角元,所以 ∑iVar(y^i)=tr(σ2Hp)=σ2 tr(Hp)\sum_i\mathrm{Var}(\hat y_i) = \mathrm{tr}(\sigma^2H_p) = \sigma^2\,\mathrm{tr}(H_p)。

第 3 步:tr(Hp)=tr((Xp⊤Xp)−1Xp⊤Xp)=tr(Ip)=p\mathrm{tr}(H_p) = \mathrm{tr}\big((X_p^\top X_p)^{-1}X_p^\top X_p\big) = \mathrm{tr}(I_p) = p(tr(AB)=tr(BA)\mathrm{tr}(AB) = \mathrm{tr}(BA))。

∑i=1nVar(y^i)σ2=σ2pσ2=p.  ∎\frac{\sum_{i=1}^n\mathrm{Var}(\hat y_i)}{\sigma^2} = \frac{\sigma^2p}{\sigma^2} = p.\ \ ∎

意义:用的参数越多,拟合值的总方差越大。Cp 把"偏差"和这个"方差"加在一起,所以能在"模型太小(偏差大)"和"模型太大(方差大)"之间取平衡。

✍️ b) ii) [3 分] R²、adjusted R²、Cp 的作用
  • R² = SSreg/SStotal is the proportion of variation explained. It always increases when a predictor is added, so it can only compare models with the same number of predictors (e.g. choose the best model of each size); it cannot be used on its own to choose the model size.
  • Adjusted R² = 1 − [SSres/(n − p)]/[SStotal/(n − 1)] penalises extra parameters; it can decrease when a useless predictor is added. Choose the model with the largest adjusted R².
  • Mallows' Cp = SSres_p/σ̂² − n + 2p (σ̂² from the full model) estimates the total mean squared error of the fitted values scaled by σ². A model with little bias has Cp ≈ p; we prefer models with small Cp close to p.
✅ 2019 卷检查清单
  • Q1:SSres=Syy−b12SxxSS_{res} = S_{yy} - b_1^2S_{xx};E(b12)=Var(b1)+β12E(b_1^2) = \mathrm{Var}(b_1) + \beta_1^2;Cov(AY,BZ)=AVB⊤\mathrm{Cov}(AY, BZ) = AVB^\top;(I−H)X=0(I - H)X = 0
  • Q2:log 模型更好(点名图);β₂ 是 weight;CI (−2.945e-4, −1.903e-4);F = 85.12 ~ F2,394F_{2,394};v) 用 anova 最后一行 F = 4.65
  • Q3:β^=(X⊤V−1X)−1X⊤V−1y\hat\beta = (X^\top V^{-1}X)^{-1}X^\top V^{-1}y;BLUE 三个词;Gauss–Markov:BX = 0 ⇒ Var(b~)=σ2((X⊤X)−1+BB⊤)\mathrm{Var}(\tilde b) = \sigma^2((X^\top X)^{-1} + BB^\top)
  • Q4:概率 0.88;odds ratio 0.072;偏差检验 330.43 ~ χ42\chi^2_4;tr(Hp)=p\mathrm{tr}(H_p) = p

第 29 章 · 2014 S2 期末完整解答(7 题共 70 分,纸笔考试)

本章目标
把 2014 S2 期末整张卷子逐题、逐小问做一遍。这是最老的一份:2 小时、7 题、分值不等(12 + 10 + 6 + 5 + 10 + 7 + 20 = 70 分),纸笔考试,只给 R 输出。
它的价值:题目短、基础,几乎全是 Lab Test 范围内的内容(SLR 推断、F 检验、模型选择、SLR 的方差公式、杠杆公式),很适合用来检查基础是不是扎实。Q6 的 Gauss–Markov 和 2019 Q3 一样。Q5 (c) 的矩母函数今年没讲,了解即可。
原卷:past_final_exams/MATH2831_2014.pdf 配套脚本:R/ch29_2014_final.R。
📚 做这份卷子要用到的知识
题知识点Lab Test 学过?详细讲解
Q1读 SLR 输出、F 和 t 检验、单侧 p 值、CI 和 PI✅ 学过第 3、4 章
Q2step() 向前选择、序贯 F 检验、嵌套 F✅ 学过第 7、9 章
Q3PRESS、Cp、adjusted R²、R²✅ 学过第 9 章
Q4E(y⊤Ay)E(y^\top Ay) 的证明、χ2\chi^2 的均值公式学过,证明是新的第 1、11 章,本章会先补
Q5σ^2\hat\sigma^2 无偏、χ2\chi^2 的均值方差、Var(Syy)部分学过本章会先补
Q6MLE、BLUE、Gauss–Markov❌ 新内容第 28 章 Q3(同一题)
Q7SLR 的矩阵形式、Var(b₀)、Var(b₁)、Cov、杠杆公式✅ 学过第 5、8 章

29.1 Q1 [12 分]:读 SLR 输出(原油和汽油价格)

📄 2014 期末 Q1
The table below shows the R output produced from fitting a simple linear regression model with the price of crude oil (in US dollars per barrel) as the predictor and gasoline price (in US cents per gallon) for the period 1978–1986 as the response.
            Estimate Std. Error t value Pr(>|t|)
(Intercept)   47.989      6.823   7.033 0.000205 ***
crude          2.686      0.301   8.924 4.51e-05 ***
Residual standard error: 6.833 on 7 degrees of freedom
Multiple R-squared: 0.9192, Adjusted R-squared: 0.9077
F-statistic: 79.64 on 1 and 7 DF, p-value: 4.507e-05
a) [3 marks] Write down i) the least squares estimates of the intercept and slope, ii) the estimated error variance for the fitted model?
b) [1 mark] What percentage of variation in the response is explained by the model?
c) [3 marks] Using the R output, i) state the value of an F statistic for testing H0:β1=0H_0: \beta_1 = 0 versus H1:β1≠0H_1: \beta_1 \ne 0, where β₁ is the slope term in the model. ii) State the p-value for the test, and the conclusion of the test using a 5% level of significance.
d) [2 marks] State the value of the t statistic for the partial t-test which is equivalent to the F-test considered in part c). How would the computation of the p-value for the t statistic be modified for testing H0:β1=0H_0: \beta_1 = 0 versus the one sided alternative H1:β1>0H_1: \beta_1 > 0?
e) [3 marks] In the following, you may use the fact that for T∼t7T \sim t_7, P(T>2.364)≈0.025P(T > 2.364) \approx 0.025 and Sxx≈463.24S_{xx} \approx 463.24, xˉ≈21.37\bar x \approx 21.37. Construct, when the price of crude oil is 20 dollars per barrel, i) a 95% prediction interval for the gasoline price, ii) a 95% percent confidence interval for the mean gasoline price.
✍️ a) [3 分] 估计值和误差方差

i) 截距 b0=47.989b_0 = 47.989,斜率 b1=2.686b_1 = 2.686(Estimate 列)。

ii) 误差方差是 σ^2\hat\sigma^2,输出给的 "Residual standard error" 是 σ^\hat\sigma(标准差),要平方:σ^2=6.8332=46.69\hat\sigma^2 = 6.833^2 = 46.69。

坑:直接填 6.833 会丢分,那是标准差不是方差。

✍️ b) [1 分] 解释了多少变异

R2=0.9192R^2 = 0.9192,即 91.92%。

✍️ c) [3 分] F 检验

i) F = 79.64("F-statistic: 79.64 on 1 and 7 DF"),在 H0 下服从 F1,7F_{1,7}(n − 2 = 7,所以 n = 9)。

ii) p = 4.507e-05。Since p < 0.05, reject H0: there is a significant linear relationship between crude oil price and gasoline price.

✍️ d) [2 分] 等价的 t 检验,以及单侧 p 值

t = 8.924(crude 那一行)。等价是因为 SLR 里 t2=Ft^2 = F:8.9242=79.648.924^2 = 79.64。

单侧 H1:β1>0H_1: \beta_1 > 0:p 值只算右尾 P(T7>8.924)P(T_7 > 8.924)。输出给的 4.51e-05 是双侧的 P(∣T7∣>8.924)P(|T_7| > 8.924),t 分布对称,所以

pone-sided=4.51×10−52=2.255×10−5.p_{\text{one-sided}} = \frac{4.51\times10^{-5}}{2} = 2.255\times10^{-5}.

The one-sided p-value is half of the two-sided p-value (because the observed t = 8.924 is positive, i.e. in the direction of H1). 如果 t 是负的,单侧(> 0)的 p 值就是 1 − 双侧/2,会很大。

✍️ e) [3 分] x₀ = 20 时的 95% PI 和 CI

第 1 步:点预测:y^(20)=47.989+2.686×20=101.709\hat y(20) = 47.989 + 2.686\times 20 = 101.709。

第 2 步:两个根号里的东西(formula sheet 上的公式),n = 9:

1n+(x0−xˉ)2Sxx=19+(20−21.37)2463.24=0.11111+0.00405=0.11516.\frac1n + \frac{(x_0 - \bar x)^2}{S_{xx}} = \frac19 + \frac{(20 - 21.37)^2}{463.24} = 0.11111 + 0.00405 = 0.11516.

第 3 步:区间,t0.025,7=2.364t_{0.025,7} = 2.364,σ^=6.833\hat\sigma = 6.833,2.364×6.833=16.1532.364\times 6.833 = 16.153:

  • i) 预测区间(一个新的汽油价格,根号里多一个 1):101.709±16.1531+0.11516=101.709±17.058=(84.65, 118.77)101.709 \pm 16.153\sqrt{1 + 0.11516} = 101.709 \pm 17.058 = (84.65,\ 118.77)。
  • ii) 置信区间(平均汽油价格):101.709±16.1530.11516=101.709±5.482=(96.23, 107.19)101.709 \pm 16.153\sqrt{0.11516} = 101.709 \pm 5.482 = (96.23,\ 107.19)。

预测区间比置信区间宽很多:它还要包括单个观测本身的随机误差 σ²。

Rch29 · 29.1
b0 <- 47.989; b1 <- 2.686; s <- 6.833; n <- 9
x0 <- 20; Sxx <- 463.24; xbar <- 21.37; tq <- 2.364
yhat <- b0 + b1 * x0; yhat
yhat + c(-1, 1) * tq * s * sqrt(1 + 1 / n + (x0 - xbar)^2 / Sxx)   # PI
yhat + c(-1, 1) * tq * s * sqrt(1 / n + (x0 - xbar)^2 / Sxx)       # CI
Console 输出
[1] 101.709
[1]  84.651 118.767
[1]  96.2273 107.1907

29.2 Q2 [10 分]:step() 向前选择的输出

📄 2014 期末 Q2
The following outputs were produced using the abalone dataset from UCI Machine Learning Archives. The goal is to predict abalone age (through the number of rings on the shell) given various descriptive attributes of the abalone. We take 14 samples of the weight, length and diameter from the abalones dataset and use them to predict abalone age (number of rings on their shells). The following are the output from the step() function in R, where the default forward model selection criterion used is the so called AIC.
>null <- lm(data$ring ~ 1)
>full <- lm(data$ring ~ data$length + data$weight + data$diameter)
>step(null, scope = list(lower = null, upper = full),
  direction = 'forward', test = 'F', k = 0.2)
Start:  AIC=23.74
data$rings ~ 1
                Df Sum of Sq    RSS    AIC   F value  Pr(>F)
+ data$length    1   24.372  50.842  18.455    (α)    0.03361 *
+ data$weight    1    (δ)    51.538  18.646  5.5127   0.03685 *
+ data$diameter  1    4.753  70.461  23.024  0.8095   0.38598
<none>                       75.214  23.738
Step:  AIC=18.46
data$rings ~ data$length
                 Df Sum of Sq    RSS    AIC  F value Pr(>F)
+ data$diameter   1   4.4410   46.401 17.376  1.0528  0.3269
<none>                         50.842 18.455
+ data$weight     1   0.0279   50.814 18.648  0.0060  0.9395
Step:  AIC=17.38
data$rings ~ data$length + data$diameter
                Df Sum of Sq    RSS     AIC  F value Pr(>F)
<none>                         (γ)    17.376
+ data$weight    1   0.17801  46.223  17.522   (β)   0.8483
Call: lm(formula = data$rings ~ data$length + data$diameter)
Coefficients: (Intercept) 3.0739  data$length 15.6393  data$diameter 0.7625
a) [2 marks] Suppose we performed the forward model selection procedure using the sequential F-test and the stopping rule: stop when none of the sequential F-statistics for the coefficients considered to be added are significant at 5% level. i) What is the final model. ii) State the reason for your choice.
b) [8 marks] Four values are missing from the above output and are replaced by (α), (β), (γ) and (δ). i) [4 marks] What are the values (γ) and (δ). State in words what these values refers to. ii) [2 marks] Compute the two missing F-values, (α) and (β). iii) [2 marks] For this question you may use the fact that F0.95,2,10=4.102821F_{0.95,2,10} = 4.102821 and F0.95,2,12=3.885294F_{0.95,2,12} = 3.885294. A) What is the value of the test statistic used to test whether we should include both the predictors diameter and weight to the model with the intercept and the predictor length. B) What is the conclusion of this test.
📚 怎么读 step() 的表(第 9 章)
  • 每个 "Step" 是当前模型;表里每一行是"再加一个变量"会怎样。<none> 那一行是"什么都不加",也就是当前模型本身。
  • RSS:加了这个变量以后模型的残差平方和。Sum of Sq = 当前模型的 RSS − 加变量后的 RSS = 加这个变量让 RSS 减少了多少(额外平方和)。
  • F value:序贯 F 检验 F=Sum of Sq/1RSSnew/(n−pnew)F = \dfrac{\text{Sum of Sq}/1}{\text{RSS}_{\text{new}}/(n - p_{\text{new}})},pnewp_{\text{new}} 是加变量后模型的参数个数(含截距)。
  • AIC 越小越好;R 每一步加 AIC 最小的那个,直到 <none> 最小为止。这里 k = 0.2 表示 AIC 的惩罚项是 0.2 × 参数个数(默认是 2),惩罚很弱,所以 AIC 倾向于多加变量。核对:14log⁡(75.214/14)+0.2×1=23.73814\log(75.214/14) + 0.2\times 1 = 23.738。
✍️ a) [2 分] 用序贯 F 检验做向前选择

第 1 步(从只有截距开始):length(p = 0.0336)和 weight(p = 0.0369)在 5% 都显著,加最显著的(F 最大、p 最小):length。

第 2 步(当前模型 rings ~ length):diameter 的 p = 0.3269,weight 的 p = 0.9395,都不显著 ⇒ 停止。

i) The final model is rings ~ length. ii) At the first step length has the most significant sequential F statistic (p = 0.0336 < 0.05) so it is added; at the second step neither diameter (p = 0.327) nor weight (p = 0.940) is significant at the 5% level, so we stop.

注意:这和 step() 用 AIC 选出来的模型(length + diameter)不一样。因为这里 k = 0.2,AIC 的惩罚很弱,只要 RSS 稍微变小就会加变量。

✍️ b) i) [4 分] (γ) 和 (δ)

(δ) = 从只有截距的模型加入 weight 后 RSS 的减少量:

δ=75.214−51.538=23.676.\delta = 75.214 - 51.538 = 23.676.

It is the extra (regression) sum of squares due to weight when weight is added to the intercept-only model, R(βweight∣β0)R(\beta_{weight} \mid \beta_0).

(γ) = 第三步 <none> 那一行的 RSS,也就是当前模型 rings ~ length + diameter 自己的 RSS。它在第二步已经出现过("+ data$diameter" 那一行的 RSS):

γ=46.401.\gamma = 46.401.

It is the residual sum of squares of the current model with length and diameter (no further predictor added).

核对:γ − 0.17801 = 46.223,正是加 weight 那一行的 RSS。

✍️ b) ii) [2 分] (α) 和 (β)

n = 14。加 length 后模型有 2 个参数,分母 df = 14 − 2 = 12:

α=24.372/150.842/12=24.3724.2368=5.752.\alpha = \frac{24.372/1}{50.842/12} = \frac{24.372}{4.2368} = 5.752.

在 length + diameter 上再加 weight,模型有 4 个参数,分母 df = 14 − 4 = 10:

β=0.17801/146.223/10=0.178014.6223=0.0385.\beta = \frac{0.17801/1}{46.223/10} = \frac{0.17801}{4.6223} = 0.0385.

核对:用 R 算 pf(5.752, 1, 12, lower.tail = FALSE) = 0.0336,pf(0.0385, 1, 10, lower.tail = FALSE) = 0.848,和输出的 p 值一致。

坑:分母要用加变量后模型的 RSS 和 df,不是加之前的。

✍️ b) iii) [2 分] 同时加入 diameter 和 weight 的 F 检验

比较"只有 length"(RSS = 50.842)和"length + diameter + weight"(RSS = 46.223,4 个参数):H0:βdiameter=βweight=0H_0: \beta_{diameter} = \beta_{weight} = 0。

F=(50.842−46.223)/246.223/(14−4)=2.30954.6223=0.4996∼F2,10 under H0.F = \frac{(50.842 - 46.223)/2}{46.223/(14 - 4)} = \frac{2.3095}{4.6223} = 0.4996 \sim F_{2,10}\ \text{under } H_0.

A) F = 0.4996. B) Since 0.4996 < F_{0.95,2,10} = 4.1028, we do not reject H0: there is no evidence that adding diameter and weight improves the model that already contains length.

坑:题目给了 F0.95,2,10F_{0.95,2,10} 和 F0.95,2,12F_{0.95,2,12} 两个,正确的分母 df 是全模型的 n − 4 = 10。

29.3 Q3 [6 分]:PRESS、Cp、adjusted R²、R²

📄 2014 期末 Q3
The following outputs were generated from R-codes written by a MATH2931 student using the abalone dataset. The output lists models fitted to subsets of the three predictors {weight, diameter, length}. The calculated PRESS statistics, Mallow's Cp, Adjusted R² and R² of each sub-model are given below.
  weight diameter length      PRESS  Mallow Cp       Adjr2        r2
1  FALSE    FALSE   TRUE   69.95831   0.999289  0.26770996 0.3240400
1   TRUE    FALSE  FALSE   72.29385   1.149947  0.25767971 0.3147813
1  FALSE     TRUE  FALSE   94.17609   5.243819 -0.01487436 0.0631929
2  FALSE     TRUE   TRUE   79.22630   2.038512  0.27091795 0.3830844
2   TRUE     TRUE  FALSE   84.98796   2.415549  0.24353431 0.3599136
2   TRUE    FALSE   TRUE   79.01542   2.993256  0.20157628 0.3244107
3   TRUE     TRUE   TRUE   86.51333   4.000000  0.20108650 0.3854512
a) [4 marks] Explain the roles of PRESS, Mallow's Cp, Adjusted R² and R² statistic in model selection.
b) [2 marks] In the third model (the model with only the diameter as the predictor), the adjusted R² appears to be negative. Is this possible? Give an explanation.
✍️ a) [4 分] 四个统计量的作用(各 1 分)
  • R² = SSreg/SStotal, the proportion of variation explained. It never decreases when a predictor is added (here the 3-predictor model has the largest R², 0.385), so it is only useful for comparing models with the same number of predictors.
  • Adjusted R² = 1 − (1 − R²)(n − 1)/(n − p) penalises the number of parameters; choose the model with the largest value (here diameter + length, 0.271).
  • Mallows' Cp = SSres_p/σ̂²_full − n + 2p estimates the scaled mean squared error of the fitted values; a model with little bias has Cp ≈ p. Choose a model with small Cp close to p (here length only: Cp = 0.999 ≈ p = 2 is small; note the full model always has Cp = p = 4).
  • PRESS = Σ(y_i − ŷ_{i,−i})² = Σ(e_i/(1 − h_ii))² is the leave-one-out prediction error sum of squares; it measures predictive ability. Choose the model with the smallest PRESS (here length only, 69.96).

(Cp = 4.000 正好等于全模型的参数个数,这是 Cp 的定义决定的:全模型的 SSres/σ̂² 就是 n − p。)

✍️ b) [2 分] adjusted R² 可以是负的吗

可以。

Radj2=1−(1−R2)n−1n−p=1−(1−0.0631929)×1312=1−0.9368×1.0833=−0.0149.R^2_{adj} = 1 - (1 - R^2)\frac{n - 1}{n - p} = 1 - (1 - 0.0631929)\times\frac{13}{12} = 1 - 0.9368\times 1.0833 = -0.0149.

Yes, it is possible. Adjusted R² is not a squared quantity; it equals R² minus a penalty for the number of parameters. When R² is very small (here 0.063, diameter explains almost nothing), the factor (n − 1)/(n − p) > 1 makes (1−R2)(n−1)/(n−p)>1(1 - R^2)(n-1)/(n-p) > 1, so the adjusted R² becomes negative. It indicates that the predictor is useless: the model is worse than the intercept-only model once the extra parameter is accounted for.

29.4 Q4 [5 分]:证明 E(y⊤Ay)=tr(AV)+μ⊤AμE(y^\top Ay) = \mathrm{tr}(AV) + \mu^\top A\mu

📄 2014 期末 Q4
Prove the following results.
a) [3 marks] Let y be a k × 1 random vector with mean vector μ and covariance matrix V. Let A be a k × k matrix of real numbers. Then E[y⊤Ay]=tr(AV)+μ⊤AμE[y^\top Ay] = \mathrm{tr}(AV) + \mu^\top A\mu.
b) [2 marks] Let Z1,…,ZkZ_1, \dots, Z_k be i.i.d. normal random variables with mean μ and variance σ². By using part a), show that E[∑i=1kZi2]=k(σ2+μ2)E\big[\sum_{i=1}^k Z_i^2\big] = k(\sigma^2 + \mu^2), and deduce the value of the expectation of a χk2\chi^2_k random variable.
📚 证明用到的三个迹的技巧
  • 一个数(1 × 1 矩阵)的迹就是它自己:y⊤Ay=tr(y⊤Ay)y^\top Ay = \mathrm{tr}(y^\top Ay)。
  • tr(AB)=tr(BA)\mathrm{tr}(AB) = \mathrm{tr}(BA),所以 tr(y⊤Ay)=tr(Ayy⊤)\mathrm{tr}(y^\top Ay) = \mathrm{tr}(Ayy^\top)(把 y⊤y^\top 从前面"转"到后面)。
  • 迹和期望都是线性的,可以交换:E[tr(M)]=tr(E[M])E[\mathrm{tr}(M)] = \mathrm{tr}(E[M])。
  • 再加一个协方差的老公式:Var(y)=E(yy⊤)−μμ⊤\mathrm{Var}(y) = E(yy^\top) - \mu\mu^\top,所以 E(yy⊤)=V+μμ⊤E(yy^\top) = V + \mu\mu^\top(就是一元的 E(Y2)=Var(Y)+[E(Y)]2E(Y^2) = \mathrm{Var}(Y) + [E(Y)]^2)。
✍️ a) [3 分] 证明
E[y⊤Ay]=E[tr(y⊤Ay)]=E[tr(Ayy⊤)]=tr(A E[yy⊤])=tr(A(V+μμ⊤))=tr(AV)+tr(Aμμ⊤)=tr(AV)+tr(μ⊤Aμ)=tr(AV)+μ⊤Aμ.\begin{aligned} E[y^\top Ay] &= E\big[\mathrm{tr}(y^\top Ay)\big] = E\big[\mathrm{tr}(Ayy^\top)\big] = \mathrm{tr}\big(A\,E[yy^\top]\big)\\ &= \mathrm{tr}\big(A(V + \mu\mu^\top)\big) = \mathrm{tr}(AV) + \mathrm{tr}(A\mu\mu^\top) = \mathrm{tr}(AV) + \mathrm{tr}(\mu^\top A\mu) = \mathrm{tr}(AV) + \mu^\top A\mu. \end{aligned}

每一步:一个数等于它的迹;tr(AB)=tr(BA)\mathrm{tr}(AB) = \mathrm{tr}(BA);期望和迹交换、A 是常数提出来;E(yy⊤)=V+μμ⊤E(yy^\top) = V + \mu\mu^\top;迹的线性;再用一次 tr(AB)=tr(BA)\mathrm{tr}(AB) = \mathrm{tr}(BA),μ⊤Aμ\mu^\top A\mu 是一个数。∎

✍️ b) [2 分] E∑Zi2=k(σ2+μ2)E\sum Z_i^2 = k(\sigma^2 + \mu^2),以及 E(χk2)=kE(\chi^2_k) = k

令 Z=(Z1,…,Zk)⊤Z = (Z_1, \dots, Z_k)^\top,i.i.d. ⇒ E(Z)=μ1E(Z) = \mu\mathbf 1(全是 μ 的向量),Var(Z)=σ2I\mathrm{Var}(Z) = \sigma^2I。取 A = I,∑Zi2=Z⊤IZ\sum Z_i^2 = Z^\top IZ:

E[∑i=1kZi2]=tr(I⋅σ2I)+(μ1)⊤I(μ1)=kσ2+μ21⊤1⏟= k=k(σ2+μ2).E\Big[\sum_{i=1}^kZ_i^2\Big] = \mathrm{tr}(I\cdot\sigma^2I) + (\mu\mathbf 1)^\top I(\mu\mathbf 1) = k\sigma^2 + \mu^2\underbrace{\mathbf 1^\top\mathbf 1}_{=\,k} = k(\sigma^2 + \mu^2).

推论:χk2\chi^2_k 的定义是 k 个独立 N(0, 1) 的平方和,即 μ = 0、σ² = 1,所以 E(χk2)=k(1+0)=kE(\chi^2_k) = k(1 + 0) = k。

29.5 Q5 [10 分]:σ^2\hat\sigma^2 无偏、χ2\chi^2 的矩、Var(Syy)

📄 2014 期末 Q5
In the simple linear model, the estimator of the variance σ² is given by σ^2=1n−2∑i=1n(yi−b0−b1xi)2\hat\sigma^2 = \dfrac{1}{n-2}\sum_{i=1}^n(y_i - b_0 - b_1x_i)^2.
a) [2 marks] Show that σ^2=Syy−b12Sxxn−2\hat\sigma^2 = \dfrac{S_{yy} - b_1^2S_{xx}}{n-2}.
b) [3 marks] By using part a), show that σ^2\hat\sigma^2 is an unbiased estimator of σ².
c) [3 marks] Let X∼χk2X \sim \chi^2_k random variable, compute either the characteristic function or the moment generating function of X (no need for both), hence compute E(X) and Var(X).
d) [2 marks] Compute the variance of SyyS_{yy}.
✍️ a) [2 分] 和 2019 Q1 a) i) 完全相同

b0=yˉ−b1xˉb_0 = \bar y - b_1\bar x ⇒ yi−b0−b1xi=(yi−yˉ)−b1(xi−xˉ)y_i - b_0 - b_1x_i = (y_i - \bar y) - b_1(x_i - \bar x)。平方求和:

∑(yi−b0−b1xi)2=Syy−2b1Sxy+b12Sxx=Syy−2b12Sxx+b12Sxx=Syy−b12Sxx,\sum(y_i - b_0 - b_1x_i)^2 = S_{yy} - 2b_1S_{xy} + b_1^2S_{xx} = S_{yy} - 2b_1^2S_{xx} + b_1^2S_{xx} = S_{yy} - b_1^2S_{xx},

用了 Sxy=b1SxxS_{xy} = b_1S_{xx}。除以 n − 2 得证。

✍️ b) [3 分] 无偏:分别算 E(Syy)E(S_{yy}) 和 E(b12Sxx)E(b_1^2S_{xx})

第 1 步:E(Syy)E(S_{yy})。yi=β0+β1xi+εiy_i = \beta_0 + \beta_1x_i + \varepsilon_i,yˉ=β0+β1xˉ+εˉ\bar y = \beta_0 + \beta_1\bar x + \bar\varepsilon,所以

yi−yˉ=β1(xi−xˉ)+(εi−εˉ).y_i - \bar y = \beta_1(x_i - \bar x) + (\varepsilon_i - \bar\varepsilon).

平方后取期望:交叉项期望为 0(E(εi−εˉ)=0E(\varepsilon_i - \bar\varepsilon) = 0),而

Var(εi−εˉ)=Var(εi)−2Cov(εi,εˉ)+Var(εˉ)=σ2−2σ2n+σ2n=σ2(1−1n)\mathrm{Var}(\varepsilon_i - \bar\varepsilon) = \mathrm{Var}(\varepsilon_i) - 2\mathrm{Cov}(\varepsilon_i, \bar\varepsilon) + \mathrm{Var}(\bar\varepsilon) = \sigma^2 - \frac{2\sigma^2}{n} + \frac{\sigma^2}{n} = \sigma^2\Big(1 - \frac1n\Big)

(Cov(εi,εˉ)=1nVar(εi)=σ2/n\mathrm{Cov}(\varepsilon_i, \bar\varepsilon) = \frac1n\mathrm{Var}(\varepsilon_i) = \sigma^2/n,因为 εi\varepsilon_i 只和自己相关)。求和:

E(Syy)=β12Sxx+nσ2(1−1n)=β12Sxx+(n−1)σ2.E(S_{yy}) = \beta_1^2S_{xx} + n\sigma^2\Big(1 - \frac1n\Big) = \beta_1^2S_{xx} + (n - 1)\sigma^2.

第 2 步:E(b12Sxx)E(b_1^2S_{xx}) =Sxx(Var(b1)+β12)=Sxx(σ2/Sxx+β12)=σ2+β12Sxx= S_{xx}\big(\mathrm{Var}(b_1) + \beta_1^2\big) = S_{xx}\big(\sigma^2/S_{xx} + \beta_1^2\big) = \sigma^2 + \beta_1^2S_{xx}。

第 3 步:相减:

E(σ^2)=(n−1)σ2+β12Sxx−σ2−β12Sxxn−2=(n−2)σ2n−2=σ2.  ∎E(\hat\sigma^2) = \frac{(n-1)\sigma^2 + \beta_1^2S_{xx} - \sigma^2 - \beta_1^2S_{xx}}{n - 2} = \frac{(n - 2)\sigma^2}{n - 2} = \sigma^2.\ \ ∎
✍️ c) [3 分] χk2\chi^2_k 的矩母函数、均值、方差 今年没讲矩母函数

矩母函数 M(t)=E(etX)M(t) = E(e^{tX})。用 χk2\chi^2_k 的密度(formula sheet 上有):

M(t)=∫0∞etxxk/2−1e−x/22k/2Γ(k/2) dx=12k/2Γ(k/2)∫0∞xk/2−1e−x(1−2t)/2 dx,t<12.M(t) = \int_0^\infty e^{tx}\frac{x^{k/2 - 1}e^{-x/2}}{2^{k/2}\Gamma(k/2)}\,dx = \frac{1}{2^{k/2}\Gamma(k/2)}\int_0^\infty x^{k/2 - 1}e^{-x(1 - 2t)/2}\,dx,\quad t < \tfrac12.

换元 u=x(1−2t)u = x(1 - 2t),积分变成 (1−2t)−k/2∫0∞uk/2−1e−u/2du=(1−2t)−k/2 2k/2Γ(k/2)(1 - 2t)^{-k/2}\int_0^\infty u^{k/2-1}e^{-u/2}du = (1 - 2t)^{-k/2}\,2^{k/2}\Gamma(k/2)(最后一步是 χk2\chi^2_k 的密度积分为 1)。所以

M(t)=(1−2t)−k/2.M(t) = (1 - 2t)^{-k/2}.

求导:M′(t)=k(1−2t)−k/2−1M'(t) = k(1 - 2t)^{-k/2 - 1},M′′(t)=k(k+2)(1−2t)−k/2−2M''(t) = k(k + 2)(1 - 2t)^{-k/2 - 2}。代入 t = 0:

E(X)=M′(0)=k,E(X2)=M′′(0)=k(k+2),Var(X)=k(k+2)−k2=2k.E(X) = M'(0) = k,\qquad E(X^2) = M''(0) = k(k + 2),\qquad \mathrm{Var}(X) = k(k + 2) - k^2 = 2k.

不用矩母函数的快捷方法(今年更可能用到):X=∑Zi2X = \sum Z_i^2,Z ~ N(0, 1),E(Z4)=3E(Z^4) = 3 ⇒ Var(Z2)=3−1=2\mathrm{Var}(Z^2) = 3 - 1 = 2;独立的方差相加 ⇒ Var(X)=2k\mathrm{Var}(X) = 2k。

✍️ d) [2 分] Var(Syy)\mathrm{Var}(S_{yy})

题目想要的答案(用 c 的结果,在 β1=0\beta_1 = 0 也就是 y 和 x 无关时):这时 yiy_i 是 i.i.d. N(β0,σ2)N(\beta_0, \sigma^2),Syy/σ2=∑(yi−yˉ)2/σ2∼χn−12S_{yy}/\sigma^2 = \sum(y_i - \bar y)^2/\sigma^2 \sim \chi^2_{n-1},所以

Var(Syy)=σ4 Var(χn−12)=2(n−1)σ4.\mathrm{Var}(S_{yy}) = \sigma^4\,\mathrm{Var}(\chi^2_{n-1}) = 2(n - 1)\sigma^4.

一般情形(β1\beta_1 任意,完整答案):Syy=SSreg+SSresS_{yy} = SS_{reg} + SS_{res},正态误差下 b1b_1 和残差独立(2019 Q1 c i),所以两部分独立,方差相加。

  • SSres/σ2∼χn−22SS_{res}/\sigma^2 \sim \chi^2_{n-2} ⇒ Var(SSres)=2(n−2)σ4\mathrm{Var}(SS_{res}) = 2(n - 2)\sigma^4。
  • SSreg=Sxxb12=σ2W2SS_{reg} = S_{xx}b_1^2 = \sigma^2W^2,其中 W=b1Sxx/σ∼N(m,1)W = b_1\sqrt{S_{xx}}/\sigma \sim N(m, 1),m=β1Sxx/σm = \beta_1\sqrt{S_{xx}}/\sigma。E(W4)=m4+6m2+3E(W^4) = m^4 + 6m^2 + 3,E(W2)=m2+1E(W^2) = m^2 + 1,所以 Var(W2)=2+4m2\mathrm{Var}(W^2) = 2 + 4m^2,Var(SSreg)=σ4(2+4m2)=2σ4+4σ2β12Sxx\mathrm{Var}(SS_{reg}) = \sigma^4(2 + 4m^2) = 2\sigma^4 + 4\sigma^2\beta_1^2S_{xx}。
Var(Syy)=2(n−1)σ4+4σ2β12Sxx,\mathrm{Var}(S_{yy}) = 2(n - 1)\sigma^4 + 4\sigma^2\beta_1^2S_{xx},

β1=0\beta_1 = 0 时回到 2(n−1)σ42(n-1)\sigma^4。脚本 29.4 用模拟核对了这个公式(模拟 313.2,理论 312.6)。

29.6 Q6 [7 分]:MLE、BLUE、Gauss–Markov

📄 2014 期末 Q6
Suppose you are given the linear model y=Xβ+εy = X\beta + \varepsilon, where X is an n × p full rank design matrix, β is a p × 1 vector of parameters and ε is a zero mean Gaussian n × 1 vector with covariance matrix V, that is, ε∼N(0,V)\varepsilon \sim N(0, V).
a) [2 marks] Derive the maximum likelihood estimator of β.
b) [1 mark] Suppose now that V = σ²I, where I is the n × n identity matrix, verify that the maximum likelihood estimator of β is equal to the least squares estimator of β: b=(X⊤X)−1X⊤yb = (X^\top X)^{-1}X^\top y (1).
c) [2 marks] The least squares estimator β̂ enjoys the optimality property known as BLUE. (i) Explain what a BLUE estimator is. (ii) Does the BLUE property depend on the distribution of ε? For example, does ε have to be normally distributed?
d) [2 marks] Prove the Gauss Markov theorem, that is, show that the estimator (1) is BLUE.

和 2019 Q3 是同一道题(分值更少)。每一步的详细解释见第 28 章 Q3,这里写出完整但紧凑的答案。

✍️ a) [2 分] MLE

y∼N(Xβ,V)y \sim N(X\beta, V):

log⁡L(β)=const−12(y−Xβ)⊤V−1(y−Xβ)=const−12(y⊤V−1y−2β⊤X⊤V−1y+β⊤X⊤V−1Xβ).\log L(\beta) = \text{const} - \frac12(y - X\beta)^\top V^{-1}(y - X\beta) = \text{const} - \frac12\big(y^\top V^{-1}y - 2\beta^\top X^\top V^{-1}y + \beta^\top X^\top V^{-1}X\beta\big). ∂log⁡L∂β=X⊤V−1y−X⊤V−1Xβ=0 ⇒ β^=(X⊤V−1X)−1X⊤V−1y.\frac{\partial\log L}{\partial\beta} = X^\top V^{-1}y - X^\top V^{-1}X\beta = 0\ \Rightarrow\ \hat\beta = (X^\top V^{-1}X)^{-1}X^\top V^{-1}y.
✍️ b) [1 分] V = σ²I
β^=(1σ2X⊤X)−11σ2X⊤y=(X⊤X)−1X⊤y=b.\hat\beta = \Big(\tfrac{1}{\sigma^2}X^\top X\Big)^{-1}\tfrac{1}{\sigma^2}X^\top y = (X^\top X)^{-1}X^\top y = b.
✍️ c) [2 分] BLUE 是什么、要不要正态

(i) Best Linear Unbiased Estimator: among all estimators that are linear in y (b~=Cy\tilde b = Cy) and unbiased (Eb~=βE\tilde b = \beta for all β), it has the smallest variance (Var(b~)−Var(b)\mathrm{Var}(\tilde b) - \mathrm{Var}(b) is positive semi-definite).

(ii) No. The Gauss–Markov theorem only uses E(ε)=0E(\varepsilon) = 0 and Var(ε)=σ2I\mathrm{Var}(\varepsilon) = \sigma^2I (zero mean, uncorrelated errors with constant variance); normality is not required.

✍️ d) [2 分] Gauss–Markov 证明

任意线性无偏估计写成 b~=((X⊤X)−1X⊤+B)y\tilde b = \big((X^\top X)^{-1}X^\top + B\big)y。无偏:Eb~=β+BXβ=βE\tilde b = \beta + BX\beta = \beta 对所有 β ⇒ BX=0BX = 0。于是

Var(b~)=σ2((X⊤X)−1X⊤+B)(X(X⊤X)−1+B⊤)=σ2((X⊤X)−1+BB⊤)\mathrm{Var}(\tilde b) = \sigma^2\big((X^\top X)^{-1}X^\top + B\big)\big(X(X^\top X)^{-1} + B^\top\big) = \sigma^2\big((X^\top X)^{-1} + BB^\top\big)

(交叉项含 BX=0BX = 0 或 X⊤B⊤=0X^\top B^\top = 0)。所以 Var(b~)−Var(b)=σ2BB⊤\mathrm{Var}(\tilde b) - \mathrm{Var}(b) = \sigma^2BB^\top,对任意 c 有 c⊤BB⊤c=∥B⊤c∥2≥0c^\top BB^\top c = \|B^\top c\|^2 \ge 0,半正定 ⇒ b 方差最小,是 BLUE。∎

29.7 Q7 [20 分]:SLR 的矩阵形式、方差公式、杠杆公式

📄 2014 期末 Q7
Recall that the least squares estimators of β₀ and β₁ are denoted by b₀ and b₁.
a) [4 marks] The simple linear regression model yi=β0+β1xi+εiy_i = \beta_0 + \beta_1x_i + \varepsilon_i can be written in the form of the general linear model y=Xβ+εy = X\beta + \varepsilon for a suitable design matrix X. Write explicitly the matrix formulation of the simple linear model, making clear what each element is and its dimensions.
b) [4 marks] Use the formulae for the least squares estimates for the parameters of the simple linear model to derive expressions for the variances: Var(b₀) and Var(b₁) and the covariance Cov(b₀, b₁).
c) [4 marks] Consider the prediction y^(x0)=b0+b1x0\hat y(x_0) = b_0 + b_1x_0 at a predictor value x₀. Use the expressions obtained from part b) to derive an expression for the variance, at predictor value x₀, given by Var(y^(x0))\mathrm{Var}(\hat y(x_0)).
d) [8 marks] In the general linear model, the leverages are defined as the diagonal elements of the matrix H=X(X⊤X)−1X⊤H = X(X^\top X)^{-1}X^\top. From this definition and for the design matrix of part a), show that in the simple linear regression model the ith leverage (ith diagonal element of H) is hii=1n+(xi−xˉ)2Sxxh_{ii} = \dfrac1n + \dfrac{(x_i - \bar x)^2}{S_{xx}}, where x̄ is the mean of the predictors, n is the sample size and Sxx=∑i(xi−xˉ)2S_{xx} = \sum_i(x_i - \bar x)^2.
✍️ a) [4 分] 矩阵形式
(y1y2⋮yn)⏟y: n×1=(1x11x2⋮⋮1xn)⏟X: n×2(β0β1)⏟β: 2×1+(ε1ε2⋮εn)⏟ε: n×1\underbrace{\begin{pmatrix}y_1\\ y_2\\ \vdots\\ y_n\end{pmatrix}}_{y:\ n\times1} = \underbrace{\begin{pmatrix}1 & x_1\\ 1 & x_2\\ \vdots & \vdots\\ 1 & x_n\end{pmatrix}}_{X:\ n\times2}\underbrace{\begin{pmatrix}\beta_0\\ \beta_1\end{pmatrix}}_{\beta:\ 2\times1} + \underbrace{\begin{pmatrix}\varepsilon_1\\ \varepsilon_2\\ \vdots\\ \varepsilon_n\end{pmatrix}}_{\varepsilon:\ n\times1}

y is the n × 1 vector of responses; X is the n × 2 design matrix whose first column is all ones (for the intercept) and second column contains the predictor values; β = (β₀, β₁)ᵀ is the 2 × 1 parameter vector; ε is the n × 1 vector of errors with E(ε) = 0 and Var(ε) = σ²I. 四样东西(含维度)各 1 分。

✍️ b) [4 分] Var(b₁)、Var(b₀)、Cov(b₀, b₁)

第 1 步:写成 y 的线性组合。b1=SxySxx=∑ciyib_1 = \dfrac{S_{xy}}{S_{xx}} = \sum c_iy_i,ci=xi−xˉSxxc_i = \dfrac{x_i - \bar x}{S_{xx}}(因为 Sxy=∑(xi−xˉ)yiS_{xy} = \sum(x_i - \bar x)y_i);yˉ=∑1nyi\bar y = \sum\frac1ny_i。

第 2 步:三个基本量(yiy_i 不相关、方差 σ²,交叉项为 0):

Var(b1)=σ2∑ci2=σ2SxxSxx2=σ2Sxx,Var(yˉ)=σ2n,Cov(yˉ,b1)=σ2∑1nci=σ2nSxx∑(xi−xˉ)=0.\mathrm{Var}(b_1) = \sigma^2\sum c_i^2 = \frac{\sigma^2S_{xx}}{S_{xx}^2} = \frac{\sigma^2}{S_{xx}},\qquad \mathrm{Var}(\bar y) = \frac{\sigma^2}{n},\qquad \mathrm{Cov}(\bar y, b_1) = \sigma^2\sum\frac1n c_i = \frac{\sigma^2}{nS_{xx}}\sum(x_i - \bar x) = 0.

第 3 步:b0=yˉ−b1xˉb_0 = \bar y - b_1\bar x(xˉ\bar x 是常数):

Var(b0)=Var(yˉ)+xˉ2Var(b1)−2xˉ Cov(yˉ,b1)=σ2(1n+xˉ2Sxx),\mathrm{Var}(b_0) = \mathrm{Var}(\bar y) + \bar x^2\mathrm{Var}(b_1) - 2\bar x\,\mathrm{Cov}(\bar y, b_1) = \sigma^2\Big(\frac1n + \frac{\bar x^2}{S_{xx}}\Big), Cov(b0,b1)=Cov(yˉ−xˉb1, b1)=Cov(yˉ,b1)−xˉ Var(b1)=−xˉσ2Sxx.\mathrm{Cov}(b_0, b_1) = \mathrm{Cov}(\bar y - \bar x b_1,\ b_1) = \mathrm{Cov}(\bar y, b_1) - \bar x\,\mathrm{Var}(b_1) = -\frac{\bar x\sigma^2}{S_{xx}}.

和 2020 Q1 对照:那道题把 x 中心化了(xˉ\bar x 变成 0),所以协方差是 0;这里没中心化,协方差是 −xˉσ2/Sxx-\bar x\sigma^2/S_{xx}。

✍️ c) [4 分] Var(y^(x0))\mathrm{Var}(\hat y(x_0))

Var(aU+bW)=a2Var(U)+b2Var(W)+2ab Cov(U,W)\mathrm{Var}(aU + bW) = a^2\mathrm{Var}(U) + b^2\mathrm{Var}(W) + 2ab\,\mathrm{Cov}(U, W),a = 1、b = x₀:

Var(b0+b1x0)=σ2(1n+xˉ2Sxx)+x02σ2Sxx−2x0xˉσ2Sxx=σ2(1n+xˉ2−2x0xˉ+x02Sxx)=σ2(1n+(x0−xˉ)2Sxx).\begin{aligned} \mathrm{Var}(b_0 + b_1x_0) &= \sigma^2\Big(\frac1n + \frac{\bar x^2}{S_{xx}}\Big) + x_0^2\frac{\sigma^2}{S_{xx}} - 2x_0\frac{\bar x\sigma^2}{S_{xx}}\\ &= \sigma^2\Big(\frac1n + \frac{\bar x^2 - 2x_0\bar x + x_0^2}{S_{xx}}\Big) = \sigma^2\Big(\frac1n + \frac{(x_0 - \bar x)^2}{S_{xx}}\Big). \end{aligned}

这正是 formula sheet 上置信区间根号里的东西。x₀ 离 xˉ\bar x 越远,方差越大。

✍️ d) [8 分] hii=1n+(xi−xˉ)2Sxxh_{ii} = \dfrac1n + \dfrac{(x_i - \bar x)^2}{S_{xx}}

第 1 步:X⊤XX^\top X(两列的内积,见第 24 章的表格算法):

X⊤X=(n∑xj∑xj∑xj2).X^\top X = \begin{pmatrix}n & \sum x_j\\ \sum x_j & \sum x_j^2\end{pmatrix}.

第 2 步:求逆。2 × 2 矩阵 (abcd)−1=1ad−bc(d−b−ca)\begin{pmatrix}a & b\\ c & d\end{pmatrix}^{-1} = \dfrac{1}{ad - bc}\begin{pmatrix}d & -b\\ -c & a\end{pmatrix}。行列式:

n∑xj2−(∑xj)2=n(∑xj2−nxˉ2)=nSxx,(X⊤X)−1=1nSxx(∑xj2−∑xj−∑xjn).n\sum x_j^2 - \Big(\sum x_j\Big)^2 = n\Big(\sum x_j^2 - n\bar x^2\Big) = nS_{xx},\qquad (X^\top X)^{-1} = \frac{1}{nS_{xx}}\begin{pmatrix}\sum x_j^2 & -\sum x_j\\ -\sum x_j & n\end{pmatrix}.

(用了 ∑xj=nxˉ\sum x_j = n\bar x 和 Sxx=∑xj2−nxˉ2S_{xx} = \sum x_j^2 - n\bar x^2。)

第 3 步:hii=xi⊤(X⊤X)−1xih_{ii} = x_i^\top(X^\top X)^{-1}x_i,xi⊤=(1, xi)x_i^\top = (1,\ x_i) 是 X 的第 i 行:

hii=1nSxx(∑xj2−2xi∑xj+nxi2)=1nSxx(Sxx+nxˉ2−2nxixˉ+nxi2).h_{ii} = \frac{1}{nS_{xx}}\Big(\sum x_j^2 - 2x_i\sum x_j + nx_i^2\Big) = \frac{1}{nS_{xx}}\Big(S_{xx} + n\bar x^2 - 2nx_i\bar x + nx_i^2\Big).

第 4 步:配方:nxˉ2−2nxixˉ+nxi2=n(xi−xˉ)2n\bar x^2 - 2nx_i\bar x + nx_i^2 = n(x_i - \bar x)^2,所以

hii=Sxx+n(xi−xˉ)2nSxx=1n+(xi−xˉ)2Sxx.  ∎h_{ii} = \frac{S_{xx} + n(x_i - \bar x)^2}{nS_{xx}} = \frac1n + \frac{(x_i - \bar x)^2}{S_{xx}}.\ \ ∎

另一种思路(更快):y^i=∑jhijyj\hat y_i = \sum_jh_{ij}y_j,所以 Var(y^i)=σ2hii\mathrm{Var}(\hat y_i) = \sigma^2h_{ii}(因为 Var(y^)=σ2H\mathrm{Var}(\hat y) = \sigma^2H);而 c) 给出 Var(y^(xi))=σ2(1n+(xi−xˉ)2Sxx)\mathrm{Var}(\hat y(x_i)) = \sigma^2\big(\frac1n + \frac{(x_i - \bar x)^2}{S_{xx}}\big),比较就得 hiih_{ii}。但题目说 "from this definition",所以主要按上面的矩阵算法写。

得分点:X⊤XX^\top X(2 分)、逆矩阵和行列式 nSxxnS_{xx}(3 分)、乘出来并配方(3 分)。

Rch29 · 29.5:数值核对杠杆公式和方差公式(考试不用)
set.seed(1); n <- 12; x <- runif(n, 0, 10); sigma <- 1.5
Sxx <- sum((x - mean(x))^2)
X <- cbind(1, x); H <- X %*% solve(t(X) %*% X) %*% t(X)
cbind(diag_H = diag(H), formula = 1 / n + (x - mean(x))^2 / Sxx)[1:4, ]
c(Var_b0 = sigma^2 * (1 / n + mean(x)^2 / Sxx), Var_b1 = sigma^2 / Sxx,
  Cov = -mean(x) * sigma^2 / Sxx)
sigma^2 * solve(t(X) %*% X)            # 矩阵公式 sigma^2 (X'X)^{-1},三个数对得上

两种算法给出完全相同的数(运行 R/ch29_2014_final.R 可以看到)。

✅ 2014 卷检查清单
  • Q1:σ^2=6.8332\hat\sigma^2 = 6.833^2(要平方);单侧 p 值 = 双侧 / 2;PI (84.65, 118.77),CI (96.23, 107.19)
  • Q2:序贯 F 停止规则选 rings ~ length;δ = 23.676,γ = 46.401,α = 5.752,β = 0.0385;同时加两个:F = 0.4996 ~ F2,10F_{2,10}
  • Q3:四个统计量的作用;adjusted R² 可以为负
  • Q4:y⊤Ay=tr(Ayy⊤)y^\top Ay = \mathrm{tr}(Ayy^\top) 是证明的钥匙
  • Q5:E(Syy)=(n−1)σ2+β12SxxE(S_{yy}) = (n-1)\sigma^2 + \beta_1^2S_{xx};χk2\chi^2_k 均值 k、方差 2k;Var(Syy)
  • Q6:同 2019 Q3;BLUE 不需要正态
  • Q7:Cov(b0,b1)=−xˉσ2/Sxx\mathrm{Cov}(b_0, b_1) = -\bar x\sigma^2/S_{xx};det⁡(X⊤X)=nSxx\det(X^\top X) = nS_{xx};配方得 hiih_{ii}

第 23 章 · 两套模拟期末(2 小时 × 2)

怎么用
  • 每套 2 小时,结构仿 2023:Q1、Q2 是 R 题(在 RStudio 里做,答案填进下面的框,点"检查"自动判分);Q3、Q4 是证明题(写在纸上,做完展开参考答案)。
  • R 题的题目和数据在 R/ch23_mock_final_questions.R,全是 R 自带数据。开始前 rm(list = ls())。
  • 模拟真实考场:只看课程 PDF(formula sheet、Lecture Notes、slides、tut_labs.pdf、rscripts.R.txt),不看这个网页和其他 .R 文件。
  • 做完对照 R/ch23_mock_final_solutions.R。数值答案允许小的误差。

Mock A

Question 1 [15 marks]:MASS::Animals(2023 Q1 / 2021 Q1–Q2 同构)

题目见脚本 MOCK A Q1:28 种动物的体重(body,kg)和脑重(brain,g)。

(b) R² of log.brain ~ log.body =
(c) F statistic =
(c) Null distribution(例如 F1,26)
(c) p-value =
(d) slope =
(e) 95% CI lower =
(e) upper =
(f) 99% CI for mean log.brain at body = 100:lower =
(f) upper =
(h) t statistic of dummy =
(h) p-value =
文字部分参考答案

(a) brain ~ body:几个巨大的动物(大象、恐龙)杠杆极高,残差图几乎所有点挤在左边,Q-Q 图严重偏离直线,线性、等方差、正态都不成立。log-log 模型的点分布均匀得多,更合适;但恐龙(Brachiosaurus 等,脑小身体大)残差很大,需要调查。

(c) H0:β1=0H_0: \beta_1 = 0 vs H1:β1≠0H_1: \beta_1 \ne 0,p < 0.01 → reject。(f) newdata 填 log.body = log(100)。

(h) H0:Δ26=0H_0: \Delta_{26} = 0;t = −2.506 ~ t25t_{25};p = 0.019 < 0.05 → reject:有证据表明第 26 个观测(Brachiosaurus)是离群点。是同一个检验:rstudent(mA)[26] = −2.5055,df = n − p − 1 = 25。

Question 2 [15 marks]:attitude(2023 Q2 / 2021 Q3 同构)

(a) 3 个预测变量的最优模型包含 complaints、learning 和哪个变量?
(b) PRESS of the best 1-predictor model =
(b) PRESS of the best 3-predictor model =
(d) overall F =
(d) p-value =
(e) F =
(e) p-value =
(e) Null distribution(例如 F5,23)
(f) 95% PI lower =
(f) upper =
文字部分参考答案

(a) i) complaints;ii) complaints + learning;iii) complaints + learning + advance。(b) adjusted R²:0.670、0.686、0.694;PRESS:1556.1、1546.0、1538.5。两个标准都选 3 个变量的模型(差别不大)。

(e) H0H_0:privileges、learning、raises、critical、advance 的系数都是 0。p = 0.51 → 不拒绝:有 complaints 时,其他 5 个变量整体上没有额外作用。

Question 3 [15 marks]:σ̂² 无偏 + mean shift(写在纸上)

📄 题目
Consider the full rank general linear model y=Xβ+εy = X\beta + \varepsilon, E(ε)=0E(\varepsilon) = 0, Var(ε)=σ2I\mathrm{Var}(\varepsilon) = \sigma^2 I, b=(X⊤X)−1X⊤yb = (X^\top X)^{-1}X^\top y, H=X(X⊤X)−1X⊤H = X(X^\top X)^{-1}X^\top, e=y−Xbe = y - Xb.
(a) [3] Show that e=(I−H)εe = (I - H)\varepsilon.
(b) [3] Find E(e)E(e) and Var(e)\mathrm{Var}(e). Are the residuals uncorrelated?
(c) [4] Show that σ^2=e⊤e/(n−p)\hat\sigma^2 = e^\top e/(n-p) is an unbiased estimator of σ².
(d) [5] Now suppose the mean shift model holds for observation j: E(εj)=ΔE(\varepsilon_j) = \Delta and E(εk)=0E(\varepsilon_k) = 0 for k≠jk \ne j. Find E(ej)E(e_j) and the expected value of the PRESS residual E(ej,−j)E(e_{j,-j}). Which of the two is more useful for detecting the shift, and why?
参考答案

(a)(b) 第 14 章 14.1:e=(I−H)y=(I−H)(Xβ+ε)=(I−H)εe = (I-H)y = (I-H)(X\beta + \varepsilon) = (I-H)\varepsilon;E(e)=0E(e) = 0,Var(e)=σ2(I−H)\mathrm{Var}(e) = \sigma^2(I-H);Cov(ei,ej)=−σ2hij\mathrm{Cov}(e_i, e_j) = -\sigma^2h_{ij},一般不为 0,所以残差相关。

(c) 第 21 章 21.2 (d):e⊤e=ε⊤(I−H)εe^\top e = \varepsilon^\top(I-H)\varepsilon,E=σ2tr(I−H)=σ2(n−p)E = \sigma^2\mathrm{tr}(I-H) = \sigma^2(n-p)。

(d) 第 14 章 14.6:E(ej)=Δ(1−hjj)E(e_j) = \Delta(1 - h_{jj}),E(ej,−j)=ΔE(e_{j,-j}) = \Delta。PRESS 残差更有用:普通残差把偏移缩小了 (1−hjj)(1 - h_{jj}) 倍,高杠杆点被缩得最厉害,可能看不出来;PRESS 残差对 Δ 无偏。

Question 4 [15 marks]:影响度量(写在纸上)

📄 题目
Consider the full rank general linear model, and you may use b−i=b−(X⊤X)−1xiei1−hiib_{-i} = b - \frac{(X^\top X)^{-1}x_ie_i}{1 - h_{ii}} without proof.
(a) [2] Show that Cook's distance can be written as Di=(y^−y^−i)⊤(y^−y^−i)pσ^2D_i = \frac{(\hat y - \hat y_{-i})^\top(\hat y - \hat y_{-i})}{p\hat\sigma^2}, where y^−i=Xb−i\hat y_{-i} = Xb_{-i}. Interpret.
(b) [4] Show that Di=ri2phii1−hiiD_i = \frac{r_i^2}{p}\frac{h_{ii}}{1-h_{ii}}.
(c) [4] Show that y^i−y^i,−i=hiiei1−hii\hat y_i - \hat y_{i,-i} = \frac{h_{ii}e_i}{1-h_{ii}} and find its variance.
(d) [2] Show that DFFITSi=tihii/(1−hii)\mathrm{DFFITS}_i = t_i\sqrt{h_{ii}/(1-h_{ii})}.
(e) [3] In a model with n = 20 and p = 3, an observation has hii=0.4h_{ii} = 0.4 and ri=2.1r_i = 2.1. Compute DiD_i, the externally studentized residual tit_i (use ti=rin−p−1n−p−ri2t_i = r_i\sqrt{\frac{n-p-1}{n-p-r_i^2}}) and DFFITSi\mathrm{DFFITS}_i, and comment using the rules of thumb.
参考答案

(a) (b−b−i)⊤X⊤X(b−b−i)=(Xb−Xb−i)⊤(Xb−Xb−i)=(y^−y^−i)⊤(y^−y^−i)(b - b_{-i})^\top X^\top X(b - b_{-i}) = (Xb - Xb_{-i})^\top(Xb - Xb_{-i}) = (\hat y - \hat y_{-i})^\top(\hat y - \hat y_{-i})。含义:Cook's D 是用全部数据和删去第 i 个点得到的两组拟合值向量之间的欧氏距离的平方,再除以 pσ^2p\hat\sigma^2。

(b)(c)(d) 第 15 章 P15-2、P15-4、P15-5。

(e) Di=2.123⋅0.40.6=1.47×0.667=0.98D_i = \frac{2.1^2}{3}\cdot\frac{0.4}{0.6} = 1.47\times0.667 = 0.98;ti=2.11617−4.41=2.1×1.127=2.37t_i = 2.1\sqrt{\frac{16}{17 - 4.41}} = 2.1\times1.127 = 2.37;DFFITSi=2.370.4/0.6=2.37×0.816=1.93\mathrm{DFFITS}_i = 2.37\sqrt{0.4/0.6} = 2.37\times0.816 = 1.93。D 接近 1(> 0.5,值得调查),|DFFITS| 接近 2 → 这个观测可能有影响,应进一步检查。注意 r 和 t 不能随便给:知道 rir_i、n、p 就能算出 tit_i。

Mock B

Question 1 [15 marks]:stackloss 的影响点(Lab 8 风格)

(a) 哪个观测的杠杆 > 2p/n?
(b) largest |rstudent| =
(b) outlier test p-value =
(c) Cook's D of obs 21 =
(c) DFFITS =
(c) COVRATIO =
(e) σ̂ without obs 21 =
(f) 95% PI without obs 21:lower =
(f) upper =
文字部分参考答案

(b) 最大的是第 21 天,t21=−3.33t_{21} = -3.33 ~ t16t_{16},p = 0.004 → 有证据表明是离群点。

(c) D21=0.69D_{21} = 0.69 < 1,也 < F0.5;4,17=0.874F_{0.5;4,17} = 0.874,按 Cook's D 不算强影响;但 |DFFITS| = 2.10 > 2,COVRATIO = 0.217 < 1−3p/n=0.431 - 3p/n = 0.43(删掉它精度会明显提高)。结论:第 21 天值得调查。

(e)(f) 删掉后 Acid.Conc. 系数从 −0.152 变成 −0.107,σ̂ 从 3.24 降到 2.57;预测区间从 (9.98, 23.99) 变窄为 (11.88, 23.06)。

Question 2 [15 marks]:PlantGrowth + ToothGrowth(分类变量、交互、一般线性假设)

(a) 参照组是?
(a) trt2 组的均值 =
(b) F =
(b) p-value =
(d) F for H0: μ_trt1 = μ_trt2 =
(d) p-value =
(e) VC 组拟合线的斜率 =
(f) 交互项 p-value =
(f) H0: β_supp = β_dose:supp = 0 的 F =
文字部分参考答案

(a) ctrl 是参照组(字母顺序第一):ctrl = 5.032,trt1 = 5.032 − 0.371 = 4.661,trt2 = 5.032 + 0.494 = 5.526。(b) overall F 检验三组均值相等:p = 0.016 < 0.05 → 不全相等。(c) trt1 vs ctrl:p = 0.19;trt2 vs ctrl:p = 0.088;5% 水平下都不显著。

(d) β = (μ_ctrl, trt1 − ctrl, trt2 − ctrl),μtrt1−μtrt2=(0,1,−1)β\mu_{trt1} - \mu_{trt2} = (0, 1, -1)\beta,C = (0, 1, −1),d = 0。F = 9.63 ~ F1,27F_{1,27},p = 0.0045 → 拒绝。用 relevel(pg$group, ref = "trt1") 重新拟合,group2trt2 的 t = 3.103,t2=9.63=Ft^2 = 9.63 = F,p 相同。summary 里两个和 ctrl 比的 partial t 都不显著(p = 0.19、0.088),但 trt1 vs trt2 显著(p = 0.0045):trt1 和 trt2 分在 ctrl 两边,各自离 ctrl 不远,彼此却差很多。summary 不直接给的两两比较,要用一般线性假设或 relevel 来做。

(e) OJ(参照组):len^=11.55+7.811 dose\widehat{len} = 11.55 + 7.811\,dose;VC:(11.55−8.255)+(7.811+3.904) dose=3.295+11.715 dose(11.55 - 8.255) + (7.811 + 3.904)\,dose = 3.295 + 11.715\,dose。(f) 交互项 p = 0.025 → dose 的效应在两种补充方式之间不同(VC 斜率更大);H0:βsupp=βdose:supp=0H_0: \beta_{supp} = \beta_{dose:supp} = 0:F = 8.83 ~ F2,56F_{2,56},p = 0.0005 → supp 有效应。

Question 3 [15 marks]:GLS 与方差稳定(写在纸上)

📄 题目
Suppose y=Xβ+εy = X\beta + \varepsilon with X full rank and ε∼N(0,V)\varepsilon \sim N(0, V), V known and positive definite.
(a) [4] Derive the maximum likelihood estimator of β and show it minimizes (y−Xβ)⊤V−1(y−Xβ)(y - X\beta)^\top V^{-1}(y - X\beta).
(b) [4] Find the distribution of the MLE.
(c) [2] Write down the weighted least squares estimator when V=σ2W−1V = \sigma^2 W^{-1}, W=diag(w1,…,wn)W = \mathrm{diag}(w_1, \dots, w_n), and its covariance matrix.
(d) [5] Using a first order Taylor expansion, show that if Y∼Poisson(λ)Y \sim \text{Poisson}(\lambda) then Var(Y)\mathrm{Var}(\sqrt Y) is approximately constant, and if Y is exponential then Var(ln⁡Y)\mathrm{Var}(\ln Y) is approximately constant.
参考答案

(a)(b)(c) 第 17 章 17.2;(d) 第 16 章 16.1 原题答案。

Question 4 [15 marks]:单因素模型与一般线性假设(写在纸上)

📄 题目
Consider k groups with nin_i observations each and the one way classification model yij=μ+ai+εijy_{ij} = \mu + a_i + \varepsilon_{ij}.
(a) [3] For k = 2, n1=n2=2n_1 = n_2 = 2, write the model in matrix form with β=(μ,a1,a2)⊤\beta = (\mu, a_1, a_2)^\top. Show that X is not of full rank.
(b) [4] Re-parametrize as yij=∑vμvxvj+εijy_{ij} = \sum_v \mu_v x_{vj} + \varepsilon_{ij} (no intercept). Write X for general k and show that X⊤X=diag(n1,…,nk)X^\top X = \mathrm{diag}(n_1, \dots, n_k). Hence show that the least squares estimate of μi\mu_i is the group sample mean yˉi⋅\bar y_{i\cdot}.
(c) [3] In this parametrization, find Var(b)\mathrm{Var}(b). Are the estimated group means uncorrelated?
(d) [5] For k = 3, write the hypothesis H0:μ1=μ2=μ3H_0: \mu_1 = \mu_2 = \mu_3 in the form Cβ=dC\beta = d, state the F statistic and its null distribution. For a single contrast c⊤β=0c^\top\beta = 0, show that the F statistic equals the square of t=c⊤b/(σ^c⊤(X⊤X)−1c)t = c^\top b/(\hat\sigma\sqrt{c^\top(X^\top X)^{-1}c}).
参考答案

(a) X 的行:(1,1,0)、(1,1,0)、(1,0,1)、(1,0,1);第 1 列 = 第 2 列 + 第 3 列 ⇒ 列线性相关,秩 2 < 3。

(b) X 的第 v 列是第 v 组的指示变量。(X⊤X)uv=∑jxujxvj(X^\top X)_{uv} = \sum_j x_{uj}x_{vj}:u = v 时是第 v 组的人数 nvn_v;u ≠ v 时没有人同时属于两组,是 0。X⊤yX^\top y 的第 v 个元素 = 第 v 组的 y 之和。所以 b=(X⊤X)−1X⊤yb = (X^\top X)^{-1}X^\top y 的第 v 个元素 = 组和 / nvn_v = yˉv⋅\bar y_{v\cdot}。

(c) Var(b)=σ2(X⊤X)−1=σ2diag(1/n1,…,1/nk)\mathrm{Var}(b) = \sigma^2(X^\top X)^{-1} = \sigma^2\mathrm{diag}(1/n_1, \dots, 1/n_k),对角 ⇒ 不相关。

(d) C=(1−1001−1)C = \begin{pmatrix}1&-1&0\\0&1&-1\end{pmatrix},d = 0,m = 2;F=(Cb)⊤[C(X⊤X)−1C⊤]−1Cb2σ^2∼F2,n−3F = \frac{(Cb)^\top[C(X^\top X)^{-1}C^\top]^{-1}Cb}{2\hat\sigma^2} \sim F_{2,n-3}。m = 1 时 [c⊤(X⊤X)−1c]−1[c^\top(X^\top X)^{-1}c]^{-1} 是一个数,F=(c⊤b)2σ^2c⊤(X⊤X)−1c=t2F = \frac{(c^\top b)^2}{\hat\sigma^2c^\top(X^\top X)^{-1}c} = t^2。

做完之后

第 12 章 · Lab Test 三套模拟考试(Week 1–7 练手)

💡 期末用法
这是 Lab Test 时做的三套 60 分钟模拟,只覆盖 Week 1–7。期末的模拟题在第 23 章;这里适合拿来练 Week 1–7 的 R 操作和判断题。
怎么用
  • 每套 60 分钟:Q1 理论题写在纸上,Q2 在 RStudio 里做。
  • Q2 的题目和数据在 R/ch12_mock_questions.R。做之前先 rm(list = ls()) 清空环境,然后把对应 MOCK 的数据部分选中运行(相当于考场上的"粘贴数据")。
  • 模拟真实考场:只看课程 PDF(formula sheet、Lecture Notes、slides、tut_labs.pdf、rscripts.R.txt),不看这个网页和其他 .R 文件。
  • Q2 做完把答案填进下面的框里,点"检查"自动判分(数值有小的容差)。然后对照 R/ch12_mock_solutions.R。

Mock 1(2025 年真题同构)

2025 年 Part I 的 Movies 数据在 PDF 截图里被截断了,没法原样重做;这里用 Savings 数据出同样结构的题代替。Part II 换成了 women 数据(2025 的 trees 答案你在第 8–10 章已经见过)。

Question 1 [25 marks]:直接用 2025 年真题

Part I [10 marks]. TRUE or FALSE with careful justification (2 marks each):

  1. It is possible to construct an example dataset for a simple linear model where all leverages hii = 1, i = 1, …, n. (hint: you can consider n = 2)
  2. The trace of the hat matrix is equal to p, the number of regression parameters β in the general linear model, i.e. tr(H) = p.
  3. Standardised PRESS residuals (i.e. ei,−i divided by their standard deviation) are identical to standardised ordinary residuals (i.e. ei divided by their standard deviation).
  4. The sum of the sequential sums of squares in an ANOVA table for the general linear model is equal to the regression sum of squares.
  5. The forward-selection and backward-selection algorithms are not guaranteed to find the best predictive model.

Part II [15 marks].

(a) [5 marks] Let Y be n×1 and Z be p×1 random vectors, and let Σ = Cov(Y, Z) be their n×p covariance matrix. Suppose A and B are n×n and p×p matrices respectively, show that Cov(AY, BZ) = AΣBᵀ.

(b) [6 marks] Consider the multiple linear regression model y = Xβ + ε, where X is an n×p full rank design matrix, β is a p×1 vector of parameters and ε ~ N(0, σ²I). The hat matrix is H = X(XᵀX)⁻¹Xᵀ. Show that the covariance between (I − H)y and b = (XᵀX)⁻¹Xᵀy is a matrix of zeros.

(c) [4 marks] For the model in (b) show that (y − Xb)ᵀ(y − Xb) = yᵀ(I − H)y.

参考答案

Part I:全部 True,理由见第 11 章判断题 1–5。Part II:见第 11 章 P1、P2、P3。

Question 2 [25 marks]:Savings 数据 + women(题目在 ch12_mock_questions.R 的 MOCK 1)

Part I (a) Observed F =
(a) Null distribution(例如写 F4,45 → 输入 F4,45)
(a) p-value =
(b) Observed F =
(b) p-value =
(c) Observed t =
(c) p-value =
(d) PI lower =
(d) PI upper =
Part II (a) sum of leverages =
(b) number of obs with leverage > 2 × average =
(c) which observation has the largest |rstudent|?
(c) its value =
(c) outlier test p-value =
(d) PRESS =
解题思路
  • (a) summary(m_full) 最后一行:F-statistic: 5.756 on 4 and 45 DF, p-value: 0.0007904。n = 50, p = 5 → F4,45F_{4,45}。结论:p < 0.05,reject H0,at least one predictor is linearly related to the savings rate.
  • (b) 两个模型是 "Pop15" 和 "Pop15 + Pop75":anova(lm(SavingsRate ~ Pop15, data = Savings), lm(SavingsRate ~ Pop15 + Pop75, data = Savings))。不要读全模型 anova 表里 Pop75 那一行(那一行是 F = 3.6889, p = 0.0611,用的是全模型的 MSres,和 2025 官方做法不一致)。p = 0.069 > 0.05:no significant evidence that adding Pop75 improves the model.
  • (c) partial t:summary 中 Income 行,t = −0.362,p = 0.719,Income 在其他变量存在时不显著。
  • (d) predict(m_full, data.frame(Pop15 = 35, Pop75 = 2.5, Income = 1500, Growth = 3.5), interval = "prediction", level = 0.97)
  • Part II:wm <- lm(weight ~ height, data = women);sum(hatvalues(wm)) = p = 2;门槛 2p/n = 4/15 = 0.267,没有一个点超过(身高是等间距的,最两端的杠杆也只有 0.24),答案就是 0,不要怀疑自己;which.max(abs(rstudent(wm))) → 第 15 个,2.970;离群点检验自由度 n − p − 1 = 12:2*pt(-2.970125, 12);PRESS(wm)。

Mock 2

Question 1 [25 marks]

Part I [10 marks]. TRUE or FALSE with justification:

  1. In the general linear model with an intercept, the residuals always sum to zero.
  2. The leverage hii of the i-th observation depends on the value of the response yi.
  3. If the overall F-test in a multiple linear regression is significant at the 5% level, then at least one of the partial t-tests must also be significant at the 5% level.
  4. For the same predictor values and confidence level, the prediction interval for a new response is always wider than the confidence interval for the mean response.
  5. Adding a predictor to a linear model can never decrease R².

Part II [15 marks]. Consider y = Xβ + ε with X an n×p full rank design matrix, E(ε) = 0, Cov(ε) = σ²I, b = (XᵀX)⁻¹Xᵀy and H = X(XᵀX)⁻¹Xᵀ.

(a) [5 marks] Show that the residual vector e = y − Xb can be written as e = (I − H)ε, and hence show that Var(e) = σ²(I − H).

(b) [5 marks] Show that the leverages satisfy ∑i=1nhii=p\sum_{i=1}^n h_{ii} = p, and hence state the average leverage.

(c) [5 marks] In the simple linear regression model yi = β₀ + β₁xi + εi with independent N(0, σ²) errors, SSreg = b₁²Sxx. Show that E(SSreg) = σ² + β₁²Sxx, and explain why this justifies rejecting H0: β₁ = 0 for large values of F = MSreg/MSres.

参考答案

Part I:1 True(X⊤e=0X^\top e = 0 且 X 第一列为 1);2 False(hii=xi⊤(X⊤X)−1xih_{ii} = x_i^\top(X^\top X)^{-1}x_i 只依赖 X);3 False(Lab 4 Q4 inflation 反例:F 的 p = 0.0157,t 的 p 都 > 0.1);4 True(多了"1");5 True(SSres 不增)。

(a) 第 11 章 P6(f) + P6(d):e=(I−H)y=(I−H)(Xβ+ε)=(I−H)εe = (I-H)y = (I-H)(X\beta + \varepsilon) = (I-H)\varepsilon 因为 (I−H)X=0(I-H)X = 0;Var(e)=(I−H)σ2I(I−H)⊤=σ2(I−H)\mathrm{Var}(e) = (I-H)\sigma^2I(I-H)^\top = \sigma^2(I-H)(对称幂等)。

(b) P4:∑hii=tr(H)=tr((X⊤X)−1X⊤X)=tr(Ip)=p\sum h_{ii} = \mathrm{tr}(H) = \mathrm{tr}((X^\top X)^{-1}X^\top X) = \mathrm{tr}(I_p) = p;平均杠杆 p/np/n。

(c) P20:E(b12)=Var(b1)+(Eb1)2=σ2/Sxx+β12E(b_1^2) = \mathrm{Var}(b_1) + (Eb_1)^2 = \sigma^2/S_{xx} + \beta_1^2,乘以 SxxS_{xx} 得 σ2+β12Sxx\sigma^2 + \beta_1^2S_{xx}。H0 下 E(MSreg) = σ² = E(MSres),F 应在 1 附近;H0 不成立时 E(MSreg) 多出 β12Sxx>0\beta_1^2S_{xx} > 0,F 偏大,所以 F 大时拒绝 H0。

Question 2 [25 marks]:stackloss 数据 + cars(MOCK 2)

Part I (a) R² =
(a) σ̂ =
(b) Observed F =
(b) null distribution(如 F1,17)
(b) p-value =
(c) Observed F =
(c) p-value =
(d) 95% CI for β_WaterTemp: lower
upper
(d) 99% CI for mean StackLoss: lower
upper
Part II (a) leverage of obs 1 =
(b) count h > 2p/n =
(c) which observation?
(c) its rstudent =
(c) outlier p-value =
(d) PRESS =
解题思路
  • (b) "AcidConc useful given AirFlow and WaterTemp":anova(lm(StackLoss ~ AirFlow + WaterTemp, data = Plant), pm)。这里大模型就是全模型,所以结果 = AcidConc 的 partial t 的平方((−0.973)2=0.947(-0.973)^2 = 0.947),p 相同 0.344。
  • (c) H0:βWaterTemp=βAcidConc=0H_0: \beta_{WaterTemp} = \beta_{AcidConc} = 0:小模型只有 AirFlow,anova(lm(StackLoss ~ AirFlow, data = Plant), pm),F = 6.668 ~ F2,17F_{2,17}。
  • (d) confint(pm)["WaterTemp", ];均值 CI 用 interval = "confidence", level = 0.99(题目说 MEAN)。
  • Part II:n = 50,p = 2,门槛 0.08;外学生化残差检验自由度 n − p − 1 = 47:2 * pt(-abs(t), 47)。

Mock 3(Lab 7 风格:模型选择)

Question 1 [25 marks]

Part I [10 marks]. TRUE or FALSE with justification:

  1. The maximum likelihood estimator of σ² in the normal linear model, SSres/n, is an unbiased estimator of σ².
  2. When Mallows' Cp is computed using the full model to estimate σ², the full model always has Cp = p.
  3. Under the usual assumptions, the i-th externally studentized residual follows a t distribution with n − p degrees of freedom.
  4. The sequential sums of squares in the anova() output do not depend on the order in which the predictors are entered.
  5. The PRESS statistic is always at least as large as the residual sum of squares.

Part II [15 marks].

(a) [4 marks] Let y be a random vector with mean μ and covariance matrix V, and let A be a matrix of constants. Show that E(yᵀAy) = tr(AV) + μᵀAμ.

(b) [4 marks] For the model y = Xβ + ε with E(ε) = 0 and Cov(ε) = σ²I, use (a) to show that σ̂² = yᵀ(I − H)y/(n − p) is an unbiased estimator of σ².

(c) [4 marks] Suppose now ε ~ N(0, σ²I). Use the method of maximum likelihood to show that the MLE of β equals the least squares estimator b = (XᵀX)⁻¹Xᵀy.

(d) [3 marks] Consider the mean shift outlier model in which E(εj) = Δ for one observation j and E(εk) = 0 for k ≠ j. Find E(ej) and E(ej,−j).

参考答案

Part I:1 False(E=n−pnσ2E = \frac{n-p}{n}\sigma^2);2 True;3 False(tn−p−1t_{n-p-1});4 False;5 True(∣ei∣/(1−hii)≥∣ei∣|e_i|/(1-h_{ii}) \ge |e_i|)。

(a) P7(这题就是要你证明它,不能只引用 formula sheet,必须写出推导);(b) P8;(c) P10 第 1 步(写出似然函数和 log 似然);(d) P21:E(ej)=(1−hjj)ΔE(e_j) = (1-h_{jj})\Delta,E(ej,−j)=ΔE(e_{j,-j}) = \Delta。

Question 2 [25 marks]:swiss 数据 + mtcars(MOCK 3)

Part I (a) Cp =
(c) PRESS(full) =
(c) PRESS(model in a) =
(e) Observed F =
(e) p-value =
Part II (a) rstandard(Toyota Corolla) =
(b) rstudent(Toyota Corolla) =
(b) outlier p-value =
(c) largest leverage =
(d) PRESS =
解题思路 + 文字题答案
  • (a) 用手写的 Cp 函数或公式:p = 5,σ^p2\hat\sigma^2_p 来自不含 Examination 的模型,σ^F2\hat\sigma^2_F 来自全模型。
  • (b) leaps(x = Swiss[, 2:6], y = Swiss$Fertility, ...)。Cp 最小 (5.03):Agriculture + Education + Catholic + InfantMortality(不含 Examination)。adjusted R² 最大:全模型(0.67097,只比 (a) 的 0.67071 大一点点)。两个准则选出不同模型是正常的。
  • (c) (a) 的模型 PRESS 更小 → 预测更好。
  • (d) 路径:Fertility ~ 1 → +Education → +Catholic → +InfantMortality → +Agriculture → 停(加 Examination 不能降低 AIC)。最终模型 Fertility ~ Education + Catholic + InfantMortality + Agriculture。
  • (e) anova(m_a, full):F = 1.0328,p = 0.3155 > 0.05 → no evidence that Examination is needed.
  • Part II (b) 自由度 n − p − 1 = 32 − 3 − 1 = 28;p = 0.0145 < 0.05 → reject H0:Toyota Corolla is a potential outlier。(c) Maserati Bora。

做完之后