开始之前:期末考什么、怎么用这份材料
这份材料在 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,证明题写在答题本上 |
| 电脑上有的 PDF | formula 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 考了什么 | 本材料 |
|---|---|---|---|---|
| Q1 | 15 | Möbius | 比较 mpg~disp 和 log-log 模型的诊断图;SLR 的 F 检验、斜率、CI;哑变量离群点检验 | 第 4、14、16、22 章 |
| Q2 | 15 | Möbius | regsubsets 最优子集 + adjusted R² + PRESS;overall F、嵌套 F、98% 预测区间 | 第 6、7、9、13、22 章 |
| Q3 | 15 | 答题本 | 无截距模型的加权最小二乘:推导、期望方差、MLE、乘 √r 变换、特例 | 第 17 章 |
| Q4 | 15 | 答题本 | 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 题。
怎么用这份材料
- 左边看网页,右边开 RStudio。在 RStudio 里 File → Open File…,打开
final_study/R/里对应章节的.R文件。 - 每个代码框都真的去运行:代码框左上角的灰色标签(如「ch15 · 15.7」)= 脚本里
# ---- 15.7那一段。脚本要从开头按顺序运行,因为后面会用到前面的变量。注意:标签编号是脚本段落的编号,和网页小标题(如"15.7 看图找影响点")是两套编号,不一定相同。对照网页上的"Console 输出",确认数字一样。 - 橙框"原题"是课程 PDF 和真题里的原题(英文原文)。先自己做,再展开答案。
- 紫边框"✍️"是证明:先遮住自己写,再对照。
- 每章结束勾选"我已经学完",左上角显示进度(只存在这台电脑的浏览器里,和 Lab Test 网页的进度分开)。
章节和优先级
第 0–12 章是 Lab Test 网页原有的内容(Week 1–7),已经学过的复习即可;标"新"的是期末新增的。★★★ 必学,★★ 强烈建议,★ 有时间再看。
| 章 | 内容 | 状态 | 优先级 |
|---|---|---|---|
| 0–2 | RStudio、分布、检验与置信区间 | Lab Test 已学 | 复习 ★ |
| 3–7 | SLR、矩阵形式、MLR 推断、ANOVA 与 F 检验家族 | Lab Test 已学 | 复习 ★★★(R 题天天用) |
| 8–10 | 杠杆、模型选择、残差诊断 | Lab Test 已学 | 复习 ★★ |
| 13 | regsubsets、验证集、K 折 CV、LASSO | 新 | ★★★ |
| 14 | 残差的性质、哑变量离群点检验 | 新 | ★★★ |
| 15 | 影响点:Cook's D、DFFITS、DFBETAS、COVRATIO + 证明 | 新 | ★★★ |
| 16 | 变换、比较诊断图、多项式回归 | 新 | ★★★ |
| 17 | WLS / GLS + 证明 | 新 | ★★★ |
| 18 | 分类变量、交互项 | 新 · Week 10 | ★★ |
| 19 | 非满秩、单因素模型、一般线性假设 | 新 · Week 10 | ★★ |
| 20 | Logistic 回归(可能考) | 新 · Lab 10 | ★ |
| 11 | Week 1–7 证明模板 + 39 道判断题 | Lab Test 已学 | 复习 ★★ |
| 21 | 期末证明题地图 + 2021 Q4、2020 Q1/Q3 + 24 道新判断题 | 新 | ★★★ |
| 25 | 诊断图图鉴:四张图"坏了"分别长什么样(模拟数据可视化) | 新 | ★★★ |
| 22 | 2023、2021 期末 R 题逐题精讲 | 新 | ★★★ |
| 26 | 2023 期末完整解答(4 题逐小问,R 输出全部核对) | 新 | ★★★ |
| 27 | 2021 期末完整解答(6 题逐小问 + 原图) | 新 | ★★★ |
| 24 | 2020 期末完整解答(4 题逐小问 + 原图) | 新 | ★★★ |
| 28 | 2019 期末完整解答(4 题,纸笔考试,含 Gauss–Markov、logistic) | 新 | ★★ |
| 29 | 2014 期末完整解答(7 题,基础题为主) | 新 | ★ |
| 23 | 两套模拟期末(2 小时 × 2) | 新 | ★★★ |
| 12 | Lab Test 三套模拟(Week 1–7 练手) | Lab Test 已学 | ★ |
考前一周 / 考前一天
- 考前一周:按 ★★★ 顺序过一遍第 13–17 章;把 2023、2021 两份真题限时做一遍(第 22 章);做第 23 章两套模拟。
- 考前一天:默写第 15 章 P15-2、P15-4、P15-5 和第 17 章 (a)–(f);过一遍第 21 章判断题;看第 22 章 22.6 的"下拉选项怎么选"。
- 考试当天早上:用无痕窗口测试 zPass + MFA 能登录;带实体学生证和手机。
第 0 章 · 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 新建一个脚本,左上角就会出现):
另外两个好用的:Alt + - 打出赋值符号
<-;Ctrl + L 清空 Console。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 个数"的编号,不用管。
2^3 # 2 的 3 次方
sqrt(16) # 开平方
log(100) # 注意:R 的 log 是自然对数 ln
a <- 5 # 把 5 存进名字 a 里,"<-" 读作"赋值给"
b <- 3
a + b[1] 8 [1] 4 [1] 4.60517 [1] 8
运行 a <- 5 之后,看右上角 Environment,a 出现了。之后写 a 就等于写 5。# 后面的内容是注释,R 会忽略。
0.3 向量:一串数
统计永远在处理"一串数"(比如 15 个植物的锌含量)。R 用 c()(combine)把数串起来,叫向量:
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[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),运行。然后一定要检查:
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 # 用 $ 取出一列[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
lengths(list(向量1, 向量2, ...)),确认每个都是 43(拼完之后再查就晚了:长度不一样时 data.frame 要么报错,要么会偷偷把短的向量循环补齐)。拼完再用 dim(数据框名) 确认行数。复制时漏掉最后几个数是最常见的丢分方式(Möbius 网页上的长行很容易没选全)。0.5 读数据文件(平时练习用)
tutorial / lab 的题目用的是 cheese.txt 这类文件,已经放在 MATHLAB/datasets/ 里。读文件之前要先告诉 R "去哪个文件夹找",这叫工作目录(working directory):
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.csvtaste 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)
head(trees) # 不用读文件,直接能用
dim(trees) # 31 棵树,3 列
?trees # 打开帮助:每一列是什么意思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 画图 + 第一个线性模型
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."
- 直接从 Console 里选中数字复制(Linux 上是 Ctrl+C,Console 里选中后右键 Copy 也行)。
1.7294e-09是科学计数法,意思是 1.7294 × 10⁻⁹。Möbius 接受这种写法,直接粘贴。- 想要更多位小数:
print(x, digits = 10);或者从summary(model)$coefficients里取(显示的位数比 summary 的表多)。
round(pi, 4) # 3.1416
print(pi, digits = 10) # 3.141592654
0.000000017294 # R 自动显示为 1.7294e-080.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 章 · 随机变量与四大分布
pnorm / pt / pf / qt 算概率和临界值。配套脚本:
R/ch01_distributions.R 考试关联:每一个 p 值、每一个 "null distribution: F4,38" 都来自这里。1.1 随机变量、期望、方差(用大白话)
随机变量就是"结果还没出来的数"。比如明天随机抽一棵树量它的体积 Y:在量之前,Y 可能是很多值,每个值有不同的可能性。分布就是"每个值有多大可能"的完整描述,画出来就是一条曲线(密度曲线):曲线越高的地方,越容易出现。
- 期望 :如果能反复抽无数次,结果的长期平均。是分布的"中心"。
- 方差 :离中心的平均"距离平方",衡量有多分散。标准差 = 。
- 协方差 :两个变量是否"一起变大一起变小"。独立 ⇒ 协方差 = 0。
整门课的证明题都靠下面几条运算规则( 是普通常数):
记忆方法:常数可以提出来,提出来的时候方差/协方差里要平方(或者两边各提一次)。第 5 章会把它们升级成矩阵版本 ,那是 2025 年证明题 (a)。
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[1] -4.025731 [1] 45.02488
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):
每一步只用了"期望是线性的"。
独立 ⇒ Cov = 0:,独立时 ,所以等于 0。
Var(aX+bY):把 用双线性展开成四项:。
1.2 正态分布 N(μ, σ²)
钟形曲线。两个参数:中心 (均值)和宽度 (标准差)。 叫标准正态。任何正态都能变成标准正态:。
为什么重要?线性模型假设误差 。由此可以推出估计量 也是正态的 —— 这是所有检验的出发点。
R 的四个函数(所有分布都是同一套命名):
| 前缀 | 意思 | 正态 | t | 卡方 | F |
|---|---|---|---|---|---|
d | 密度:曲线高度(画图用) | dnorm | dt | dchisq | df |
p | 左边面积 | pnorm | pt | pchisq | pf |
q | 分位数:左边面积为 p 的那个 x | qnorm | qt | qchisq | qf |
r | 随机数 | rnorm | rt | rchisq | rf |
pnorm(1.96) # P(Z <= 1.96) = 0.975:左边面积
1 - pnorm(1.96) # 右边面积 0.025
qnorm(0.975) # 反过来:哪个数左边有 97.5%? -> 1.96[1] 0.9750021 [1] 0.0249979 [1] 1.959964
1 - p...(),或者加参数 lower.tail = FALSE。p 值非常小(比如 1e-10)时用 lower.tail = FALSE 更精确。1.3 卡方分布 χ²(k):k 个标准正态的平方和
如果 独立且都是 ,那么 。 叫自由度。它永远 ≥ 0,均值 = ,右偏。
在回归里它出现在:。直觉:残差平方和就是"一堆正态的平方加起来"。
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 = k1.4 t 分布 t(k):正态除以"估计出来的标准差"
定义: 和 独立,则
为什么要它?如果知道真实的 , 是标准正态。但 不知道,只能用估计值 代替。代替之后多了一份"估计 σ 的不确定性",分布就从正态变成 t:形状一样是钟形,但尾巴更厚(极端值更容易出现)。自由度越大,越接近正态。
qt(0.975, df = 4) # 2.776:自由度小,临界值比 1.96 大很多
qt(0.975, df = 100) # 1.984:自由度大,接近 1.96[1] 2.776445 [1] 1.983972
1.5 F 分布 F(d₁, d₂):两个卡方(各自除以自由度)之比
有两个自由度:分子 、分母 ,顺序不能反。F 永远 ≥ 0。在回归里:,"模型解释的变异"除以"没解释的变异"。F 越大,模型越有用,所以 F 检验永远只看右尾。
一个超重要的关系:如果 ,那么 。这就是为什么简单线性回归里 F = t²(第 4 章)。
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) 的临界值[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) |
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[1] 0.04073866 [1] 2.311451e-11
看,两个数和 2025 年官方答案完全一样。实际考试时 summary 会直接给出这些 p 值,你只需复制;但理解它们怎么来的,判断题和"写出 null distribution"就不会错。
1.7 样本均值和样本方差的分布(Tutorial Week 1 Q7)
设 独立同分布 ,,。四个关键结论:
- (平均值更集中,方差缩小 n 倍)
- (少了 1 个自由度,因为用 代替了 )
- 和 独立
- (= 正态 / √(卡方/自由度),正好是 t 的定义)
回归里完全是同一个套路,只是 换成 ( = 参数个数):。
答案
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[1] 0.5012749
- 能用一句话说出 χ²、t、F 分别是怎么构造的
- 知道 t 检验看两侧、F 检验只看右侧
- 会写
2*(1-pt(abs(t), df))和1-pf(F, d1, d2) - 知道
第 2 章 · 假设检验与置信区间
配套脚本:
R/ch02_tests_ci.R 考试关联:2025 年 Q2(a) 要求 "Type your conclusion in plain language",这一章教你怎么写。2.1 假设检验 = 法庭审判
把检验想成法庭:
- H0(原假设):"被告无罪" = "没有效应"。例如 (x 和 y 没有线性关系)。
- H1(备择假设):"有罪" = "有效应"。例如 。
- 先假设 H0 是真的,然后看证据(数据):如果 H0 为真,看到这么极端的数据的概率有多大?这个概率就是 p 值。
- p 值很小(小于事先定的显著性水平 ,通常 0.05)→ "无罪的话不太可能出现这种证据" → 拒绝 H0。
- p 值不小 → 证据不足 → 不拒绝 H0(注意:不是"证明 H0 是对的",只是证据不够)。
2.2 万能五步模板
- 写假设: vs
- 检验统计量:大多数情况是
- 零分布(null distribution):H0 为真时统计量服从什么分布,比如 或 。考试会让你从下拉框里选。
- p 值:t 检验 ;F 检验
- 结论:p < α → reject H0;用题目的语言解释
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 值[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 检验在 时拒绝。
crit <- qt(1 - 0.05 / 2, df = 7) # 临界值
crit
abs(t_obs) > crit # TRUE:落在拒绝域[1] 2.364624 [1] TRUE
"p < α" 和 "|t| > 临界值" 永远同时成立或同时不成立。在第 1 章的分布演示里:红线越过绿线 ⇔ 红色面积 < 0.05。
2.5 置信区间:估计 ± 临界值 × 标准误
mean(sugar) + c(-1, 1) * qt(0.975, 7) * sd(sugar) / sqrt(n)[1] 10.14245 11.15755
区间和检验的关系:95% CI 不包含 10 ⇔ 5% 水平的双侧检验拒绝 。回归里也一样:系数的 95% CI 不包含 0 ⇔ partial t 检验 p < 0.05。
每点一次"再抽 100 个样本",就像重新做 100 次实验。大约 95 个区间会盖住真值。"95%"描述的是方法的可靠程度,不是"真值有 95% 概率在这个区间里"。(这句话可能出判断题。)
2.6 单侧检验(了解即可)
时只看右尾:1 - pt(t_obs, df_t); 时只看左尾: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 对数据 。简单线性回归(simple linear regression, SLR)假设:
- :响应变量(response),我们想解释/预测的东西,比如树的体积。
- :预测变量(predictor),比如树的高度。
- (截距)、(斜率):未知的真实参数。 的含义:"x 每增加 1,y 的平均值增加 "。
- :误差,所有没被 x 解释的随机波动。
模型假设(第 10 章会教你怎么检查,Lab 2 Q1(f) 问过):
- 误差互不相关(uncorrelated)
- 误差均值为 0 ⇒ y 的均值和 x 是线性关系
- 误差方差都相同 (constant variance)
- (做检验时还需要)误差服从正态分布
真实的 我们永远看不到,只能用数据估计:估计值写成 (有的书写 )。
3.2 最小二乘:画一条"离所有点最近"的线
对任何一条线 ,每个点到线的竖直距离叫残差 。最小二乘(least squares)就是选 让
最小。为什么平方?正负残差不会抵消,而且数学上好算(可以求导)。
自己拖两个滑块,试着让 SSres 尽量小,再点"跳到最小二乘答案"对比。你会发现怎么调都不可能比答案更小 —— 这就是"最小"二乘。
求导得到公式(Week 1 讲义的推导)
对 分别求偏导并令其为 0,得到两个正规方程(normal equations):
也就是"残差之和 = 0"和"残差与 x 的乘积之和 = 0"。解出来:
其中
(Tutorial Week 1 Q3 就是证明这两个等号。)误差方差的估计:
分母是 而不是 :因为估计了 2 个参数,"用掉"了 2 个自由度。这样 才是无偏的(Tutorial Week 3 Q1)。
3.3 Lab Week 2 Q1:第一次完整地跑一个回归
(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²)?
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)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-063.4 summary 输出逐行解剖(考试 Q2 天天用)
| 输出里的位置 | 含义 | 符号 | 本例 |
|---|---|---|---|
Call: | 你拟合的是哪个模型 | EPS ~ year | |
Residuals: | 残差的五数概括(最小、四分位、中位、最大) | 大致对称就好 | |
(Intercept) 行 Estimate | 截距估计 | 0.158056 | |
year 行 Estimate | 斜率估计:year 每 +1,EPS 平均 +0.0908 | 0.090833 | |
Std. Error 列 | 估计值的标准误(估计有多不准) | 0.007057 | |
t value 列 | 检验 的 t 统计量 = Estimate / Std. Error | 12.87 | |
Pr(>|t|) 列 | 上面那个检验的双侧 p 值 | p | 3.97e-06 |
星号 *** | p 值的快速标记:*** < 0.001,** < 0.01,* < 0.05,. < 0.1 | ||
Residual standard error | 误差标准差的估计 (注意是 σ 不是 σ²!) | 0.05466 | |
on 7 degrees of freedom | 残差自由度 (这里 9 − 2) | 7 | |
Multiple R-squared | 模型解释了 y 的多少比例的变异 | 0.9595 | |
Adjusted R-squared | 考虑了参数个数的 R²(第 6 章) | 0.9537 | |
F-statistic … on 1 and 7 DF, p-value | overall F 检验:: 所有斜率 = 0;分布 | F | 165.7, F(1,7) |
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) # 只要系数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)
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 一模一样[1] 0.15805556 0.09083333 0.05465984
fitted(wendys_mod) # y-hat_i
residuals(wendys_mod) # e_i = y_i - y-hat_i
sum(residuals(wendys_mod)) # 有截距时 = 0(显示成 1e-18 这种就是 0) 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-183.6 Lab Week 2 Q3:只给"求和"也能算
(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。;;。
;;。
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) 验证 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) :88.78% 的变异被 cyear 解释。(注意 ,和手算的 对上了。)
Residual standard error是 ,题目问 "error variance" 要平方。lm(y ~ x)左边是响应变量。题目说 "EPS as the response" → EPS 在左边。- 新建变量写成
数据框$新列名 <- ...,否则lm(..., data = 数据框)找不到它。
- 能写出 SLR 模型和 4 个假设
- 会 、、
- 能在 summary 里指出 、se、t、p、、、F
第 4 章 · SLR 的推断:t 检验、置信区间、ANOVA、预测区间
配套脚本:
R/ch04_slr_inference.R 主例子:zinc 数据(讲义 Week 2) 原题:Lab Week 2 Q1(d)(e)(f)、Q24.1 估计量的分布(为什么能做检验)
在正态假设下(Week 2 讲义 "Distribution theory"):
而且 和 独立。把 σ 换成 ,得到(正态 / √(卡方/自由度) = t):
分母 就是 summary 里的 Std. Error,记作 。
Tutorial Week 1 Q5、Q6 让你证明 和 ,第 11 章有完整证明。
4.2 检验 H0: β₁ = 0("有没有线性关系")
setwd("C:/Users/Cestbon/Desktop/MATHLAB/datasets")
zinc <- read.csv("zinc.csv")
model_zinc <- lm(plant ~ sediment, data = zinc)
summary(model_zinc)
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,自由度 , < 0.05 → 有很强的证据说明 sediment 和 plant 有线性关系。验证:
2 * (1 - pt(5.595527, df = 13))[1] 8.690339e-05
4.3 β₁ 的置信区间
0.8565889 + c(-1, 1) * qt(0.975, 13) * 0.1530846 # 手算
confint(model_zinc) # 一行搞定(默认 95%)
confint(model_zinc, level = 0.99) # 99%
[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):每个点有 。平方再求和,交叉项正好是 0:
ANOVA 表就是把这个分解排成表格(p = 参数个数,SLR 里 p = 2):
| Source | Df | Sum Sq | Mean Sq | F value |
|---|---|---|---|---|
| Regression(R 里显示为变量名) | SSreg | MSreg = SSreg/(p−1) | F = MSreg/MSres | |
| Residuals | SSres | MSres = SSres/(n−p) = | ||
| Total(R 不显示) | SStotal |
anova(model_zinc)
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 就是 ()。第 7 章"补全 ANOVA 表"全靠这两条。
4.5 R²,以及 F = t²
在 SLR 里,F 检验 () 和 t 检验是同一个检验:,p 值完全相同(,p 都是 8.69e-05)。这是因为 。多元回归里不再成立:overall F 检验的是所有斜率一起是否为 0。
(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.
答案
Pr(>|t|) 列)。(e) F = 165.7,。
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]))t_squared F 165.6933 165.6933
4.6 预测:均值的置信区间 vs 新观测的预测区间(必考)
给一个新的 ,点预测都是 。但有两种问法:
| Confidence interval for the mean response | Prediction interval for a new response | |
|---|---|---|
| 问的是 | 所有 的个体的平均 y 在哪里 | 一个新个体的 y 会落在哪里 |
| 公式 | ||
| R | interval = "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"。
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
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。
newdata必须是data.frame(...),列名和建模时完全一致(大小写也要一样)。- 多元回归时每一个预测变量都要给值(第 6 章)。
level = 0.97写小数,不是 97。
4.7 Bonferroni:同时给多个参数做区间
分别做两个 95% 区间,"两个同时都对"的把握不到 95%。Bonferroni 的办法:k 个区间,每个用 的水平,那么同时成立的概率至少 。
confint(model_zinc, level = 1 - 0.05 / 2) # beta0 和 beta1 的"至少 95%"联合区间
1.25 % 98.75 %
(Intercept) -46.7808106 16.919350
sediment 0.4688811 1.2442974.8 Lab Week 2 Q2(Forbes)
答案
(b) tax 的 partial t 检验 p = 0.0175 < 0.05(b₁ = −0.293),有证据表明存在负的线性关系:税越高,储蓄率越低。((a) 只有 8 个点,散点图大致线性,可以用但样本很小。)
forbes <- read.table("forbes.txt", header = TRUE, sep = ",") # 这个文件用逗号分隔
forbes_mod <- lm(save ~ tax, data = forbes)
summary(forbes_mod)
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 章 · 矩阵形式的一般线性模型
配套脚本:
R/ch05_matrix_glm.R 原题:Lab Week 4 Q1、Tutorial Week 3 Q5–Q75.1 矩阵速成(只学要用的)
矩阵就是一个数字方阵,"" 表示 n 行 p 列。向量是只有一列的矩阵()。
| 操作 | 写法 | 意思 | R |
|---|---|---|---|
| 转置 | 行变列、列变行;(顺序反过来!) | t(A) | |
| 矩阵乘法 | A 的列数 = B 的行数才能乘;一般 | A %*% B | |
| 单位矩阵 | 对角线是 1,其余 0; | diag(n) | |
| 逆矩阵 | ,只有方阵(且满秩)才有 | solve(A) | |
| 迹 trace | 对角线元素之和;(循环性,超常用) | sum(diag(A)) | |
| 对称 | 关于对角线对称 | ||
| 幂等 | 乘自己还是自己(投影矩阵的特征) |
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
[,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] 55.2 一般线性模型 y = Xβ + ε
有 k 个预测变量时,。把 n 个方程摞起来:
- 叫设计矩阵(design matrix)。第一列全是 1,对应截距。
- = 参数个数(含截距)。全课最重要的记号之一:残差自由度是 ,overall F 是 。
- 假设:,(不相关、等方差);推断时再加正态 。
- "满秩"(full rank):X 的列线性无关,这样 才可逆。
SLR 就是 的特例:X 有两列,(1, )。
5.3 最小二乘的矩阵解
最小化 。展开:。对 β 求导(讲义里的向量求导引理:,,A 对称):
(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.
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) # 第二个公式
[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 戴上帽子
拟合值 。中间那一坨叫帽子矩阵:
几何意义:(不管 b 取什么)组成一个"平面"(X 的列空间)。最小二乘就是在这个平面上找离 最近的点,也就是把 垂直投影到平面上。 就是投影操作。
H 的性质(证明题和判断题天天考,必须会证):
| 性质 | 一行证明 |
|---|---|
| 对称 | ( 对称,它的逆也对称) |
| 幂等 | |
| 由上一条: | |
| 也对称、幂等 | |
| (迹的循环性) | |
max(abs(H - t(H))) # 对称:≈ 0
max(abs(H %*% H - H)) # 幂等:≈ 0
sum(diag(H)) # 迹 = p = 2
max(abs(H %*% X - X)) # HX = X[1] 8.326673e-17 [1] 5.551115e-17 [1] 2 [1] 3.552714e-15
(8e-17、3e-15 这种数就是 0,电脑做小数运算有微小误差。) 的对角线元素 叫杠杆值(leverage),第 8 章专门讲。
5.5 随机向量的期望和协方差(证明题的"计算器")
随机向量 :
- 均值向量
- 协方差矩阵 ,一个 矩阵:对角线是各自的方差, 位置是
- 两个随机向量的协方差
三条核心规则(A、B 是常数矩阵,c 是常数向量):
它们就是第 1 章"常数提出来要平方"的矩阵版:提到左边是 A,提到右边是 。
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ᵀ.
证明:由定义 ,且 ,:
关键两步:① ;② 常数矩阵可以提到期望外面(期望的线性)。令 、 就得到 。
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) # 理论
[,1] [,2]
[1,] 16.15811 13.24897
[2,] 13.24897 32.31738
[,1] [,2]
[1,] 16 13
[2,] 13 325.6 b 的均值和方差(Tutorial Week 3 Q5)
写 , 是常数矩阵。已知 ,:
所以 —— 这就是 summary 里 Std. Error 的来源。
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"]
x
0.13635601 0.01499716
(Intercept) Cyear
0.13635601 0.01499716Gauss–Markov 定理(Tutorial Week 5 Q7,可能考陈述/判断题):在 、 下(不需要正态),最小二乘估计 是 BLUE:Best Linear Unbiased Estimator,在所有线性、无偏的估计量中方差最小。
5.7 二次型的期望 & σ̂² 无偏(Tutorial Week 3 Q7、Week 5 Q10b)
迹的三条性质:;;。一个数(1×1 矩阵)的迹就是它自己。
二次型期望公式:若 ,,则
用它证明 无偏:取 ,,:
(因为 。)除以 得 。而极大似然估计用 ,是有偏的(偏小)。
5.8 多元正态分布(只需要知道结论)
(多元正态)时:
- 线性变换还是正态: → 所以
- 多元正态的分量:不相关 ⇔ 独立
- (Tutorial Week 5 Q6)
答案(用 Cov(AY) = AΣAᵀ)
,,,。
;。
所以 (正态的线性组合仍是正态)。
- 能写出 ,知道 X 是 ,p 含截距
- 会推
- 能一行证明 H 对称、幂等、、
- 会用 证明 、
第 6 章 · 多元线性回归的推断
配套脚本:
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 个预测变量。
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)
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先把三个数对上:,(7 个斜率 + 截距),残差自由度 ("on 17 degrees of freedom")。overall F 的自由度是 。
6.2 partial t 检验:这个变量"在其他变量都在的情况下"有没有用
summary 每一行的 t 和 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)。
6.3 overall F 检验:所有预测变量一起有没有用
它比较的是"只有截距的模型" vs "全模型"。答案在 summary 最后一行:F-statistic: 6.972 on 7 and 17 DF, p-value: 0.0005272。
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: = (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。
fs <- summary(risk_mod)$fstatistic # F 值、分子自由度、分母自由度
fs
pf(fs[1], fs[2], fs[3], lower.tail = FALSE)
value numdf dendf
6.97226 7.00000 17.00000
value
0.00052720626.4 Lab Week 4 Q3(capmodel)
(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?
capital <- read.table("capmodel.txt", header = TRUE)
cap_model <- lm(Price ~ PE_ratio + TSE300, data = capital)
summary(cap_model)
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 却显著?
(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?
inflation <- read.table("inflation.txt", header = TRUE)
summary(lm(INF ~ QUES + LEGAL + DEV, data = inflation))
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 系数的置信区间
confint(risk_mod, level = 0.99)
0.44264 + c(-1, 1) * qt(0.995, 17) * 0.14170 # Div 手算,自由度 n - p = 17
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.85331926Div 的 99% CI 不含 0,和 partial t 的 p = 0.00618 < 0.01 一致。
6.7 多元回归的 CI 和 PI(2025 (d) 3 分)
新观测的预测变量向量写成 (第一个 1 对应截距):
套路: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。
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)
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.481733ch06 脚本 6.7 节还用矩阵公式手算了 97% PI,结果完全一样,可以运行看看。
6.8 adjusted R²
有个缺点:只要加变量,R² 就不会下降(哪怕加的是纯噪声),所以不能用 R² 比较参数个数不同的模型。adjusted R² 把平方和换成均方:
加一个没用的变量时 可能下降。它甚至可以是负数(当 时,Lab 7 Q1(b)ii)。
n <- 25; p <- 8; R2 <- summary(risk_mod)$r.squared
1 - (n - 1) / (n - p) * (1 - R2)[1] 0.6352906
6.9 summary 给的 p 值不能直接用的三种情况
summary 里的 t 和 p 只针对 的双侧检验。题目一变就要自己算。
(1) 检验 βj 等于某个非 0 的数
例:zinc 数据,检验 vs ("斜率是不是 1")。统计量还是 (估计 − 假设值)/标准误,只是假设值不再是 0:
(2) 单侧检验
→ p 值只算左尾 pt(t, df); → 只算右尾 1 - pt(t, df)。(slides Week 2 "One-sided test for βj")
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 < 1sediment -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)再粘贴:
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 值(更多位数)
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.004240843summary 里 Girth 的 p 显示为 < 2e-16,真实值是 8.644334e-19。
- 看到 "in the presence of …" → partial t → summary 那一行
- 看到 "H0: β₁ = … = βₖ = 0" → overall F → summary 最后一行,分布
- 会写 "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 多了多少":
- 第 1 行 Div:只有截距时加入 Div,SSreg 增加多少,记作
- 第 2 行 Ratio:已经有 Div 了,再加 Ratio,SSreg 又增加多少,记作
- ……以此类推,每一行都"只考虑排在它前面的变量,不管排在后面的"
重要事实:所有 sequential SS 加起来 = SSreg(2025 判断题第 4 题,答案 True):
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
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() 的输出。
7.2 Lab Week 4 Q2:补全 ANOVA 表
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,差别来自表里的四舍五入)
c(X1X = 4376.7 * 1, X2X = 2668.4 / 102.6, X3X = 617.2 / 102.6)
(4376.7 + 617.2 + 0.6) / 3 / 102.6
X1X X2X X3X
4376.700000 26.007797 6.015595
[1] 16.226457.3 万能 F 公式:比较两个嵌套模型
"嵌套"(nested)= 小模型的变量全都在大模型里。检验"多出来的那些变量有没有用":
大白话:分子 = "加了这些变量后,残差平方和平均每个变量减少了多少";分母 = 大模型的 。减少得越多(相对于噪声),F 越大,越说明多出来的变量有用。
R 里一行:anova(小模型, 大模型)(先小后大)。
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 个系数都 = 0Model 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 = 各自的 ;RSS = 各自的 SSres;Df = 多了几个参数;Sum of Sq = RSS 减少了多少;F 和 Pr(>F) 就是答案。零分布 ,比如第二个是 。
第一个例子说明:overall F 就是"只有截距"vs"全模型"的特例,F = 6.9723 和 summary 最后一行一样。
7.4 Lab Week 4 Q4 (c):一次检验两个变量
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)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
。F = 1.0365 ~ ,p = 0.3749 > 0.05 → 不拒绝 H0:没有证据表明 QUES 和 LEGAL 有用。
用 sequential SS 手算(课程答案的做法):把 DEV 放在第一个拟合,anova(inf_mod_full) 里 QUES、LEGAL 两行的 Sum Sq 加起来就是 :F = ((1122.5 + 0.3)/2) / 541.7 = 1.036。
7.5 sequential F 检验 & 2025 年 (b) 的关键细节 ★
inf_mod_1 <- lm(INF ~ DEV + QUES, data = inflation)
anova(inf_mod_null, inf_mod_1) # 小 = DEV,大 = DEV + QUESModel 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 ~ ,p = 0.1555。注意分母用的是 "DEV + QUES" 这个模型自己的 MSres(自由度 19),不是全模型(含 LEGAL)的 MSres。
原题:"(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)
有两种看似合理的算法:
- 直接读全模型
anova(full)里 Opening 那一行:分母是全模型的 MSres,自由度 (1, 38) anova(lm(USRevenue ~ Budget), lm(USRevenue ~ Budget + Opening)):分母是 "Budget + Opening" 模型的 MSres,自由度 (1, 40)
官方答案 F = 60.06548,p = 1.7294e-09。用 R 反推:
pf(60.06548, 1, 38, lower.tail = FALSE) # 方法 1 的自由度
pf(60.06548, 1, 40, lower.tail = FALSE) # 方法 2 的自由度[1] 2.432703e-09 [1] 1.729399e-09
结论:官方用的是方法 2。考试里看到 "Is model A better than model B?",就把题目里说的两个模型原样建出来,然后 anova(小, 大)。不要偷懒去读全模型 anova 表里的行。只有当大模型就是全模型、并且被检验的变量在公式里排在最后时,两种算法才给出同一个数。
formula sheet 第 3 页也是这么写的(考场能看到):,分母是含 k 个预测变量的那个模型自己的 SSres。
例外:slides(Week 4 第 80 页)还介绍了另一种 sequential F:分母用全模型的 MSres,自由度 ,也就是 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 检验:,p 值相同。
anova(lm(risk ~ . - Earn2, data = risk), risk_mod) # ". - Earn2" = 除了 Earn2 以外的所有变量
summary(risk_mod)$coefficients["Earn2", "t value"]^2Res.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 F | summary(full) 最后一行 | |
| "Is X related to the response in the presence of A, B, C?" | partial t | summary(full) 中 X 那一行的 t 和 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)" | 嵌套模型 F | anova(lm(y ~ A), lm(y ~ A + B)) | |
| "Test whether β_C and β_D are both zero in the full model" | 一组变量的 F | anova(lm(y ~ A + B), full) | |
| "97% prediction interval for a new …" | PI | predict(full, data.frame(...), interval = "prediction", level = 0.97) | |
| "95% CI for the mean response …" | 均值 CI | predict(..., interval = "confidence") | |
| "99% CI for the coefficient of X" | 系数 CI | confint(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 选 ;比较模型选 。
- 能解释 anova() 每一行是"按顺序加入时的增量",总和 = SSreg
- 会写万能 F 公式,会用
anova(小, 大) - 记住 2025 (b):把题目说的两个模型原样建出来比较
- 会补全 ANOVA 表
第 8 章 · 帽子矩阵与杠杆值 leverage
hatvalues();记住 、平均杠杆 、"高杠杆"的门槛 。配套脚本:
R/ch08_hat_leverage.R 原题:Tutorial Week 5 Q11 考试关联:2025 Part II (a)(b) 共 4 分 + 判断题第 1、2 题 共 4 分。8.1 杠杆值是什么
第 5 章:。写出第 i 行:
(H 的第 i 个对角线元素)就是"第 i 个观测值 对它自己的拟合值 有多大话语权"。 越大,这个点越能把拟合线"拽"向自己。这就是杠杆(leverage):像跷跷板,离中心越远的点力臂越长。
另一个等价写法:,其中 是 X 的第 i 行。所以 只取决于 X(预测变量),和 y 完全无关。(判断题常客。)
在 SLR 里有显式公式(Tutorial Week 5 Q11a):
x 离平均值 越远,杠杆越大;正好在 处杠杆最小,等于 。
玩法:把红点左右拖,看 h 怎么变(上下拖 h 不变!);拖到最右边、再上下拖,看蓝线(含红点)被它拽得多厉害,而灰虚线(不含红点)不动。
8.2 杠杆值的性质(判断题素材)
| 性质 | 为什么 |
|---|---|
| 第 5 章的迹循环性 | |
| 平均杠杆 | p 除以 n 个点 |
| ;有截距时 | H 和 I−H 都幂等对称 ⇒ 对角线 ≥ 0(Tut W5 Q11b,c) |
| 只和 X 有关 | |
| 高杠杆的经验规则:(平均值的两倍) | Lecture Notes 5.2 |
| 高杠杆点的残差方差反而小:线被它拽过去了 | |
| 时所有 | X 是可逆方阵 ⇒ |
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 满秩矩阵,可逆,所以 ,。
2. "The trace of the hat matrix is equal to p, the number of regression parameters β in the general linear model." → True。。
8.3 2025 Part II (a)(b):trees 数据
(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?
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) # 是哪几个[1] 2 [1] 0.06451613 [1] 0.1290323 [1] 4 2 3 20 31 2 3 20 31
答案:(a) 2,(b) 4(和官方答案一致)。which() 输出两行一样的数字:上面一行是行名,下面是位置。
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[1] 1.06859e-15 [1] 8.951173e-16
8.4 看图
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 的两端(特别矮或特别高的树)。这正是 告诉我们的。
8.5 高杠杆点的残差为什么小
因为 ,,所以 。 接近 1 时,残差方差接近 0:线几乎被拽着穿过这个点。所以不能直接用普通残差找离群点,要先除以 标准化(第 10 章)。
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
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.175hatvalues(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、逐步回归
配套脚本:
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 个点拟合,再去预测 :
这就是"留一法交叉验证"(leave-one-out CV)。PRESS 越小,模型对新数据的预测越好。它不会随变量增多而必然下降。
神奇的捷径(不用真的拟合 n 次):
普通残差除以 就行。因为 ,所以 ,于是 PRESS ≥ SSres(Tutorial Week 5 Q12:)。
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[1] 3135.437 [1] 6077.439
Lab 7 原题提示里写的是 lm.influence(linear.model)$hat,和 hatvalues(linear.model) 完全一样。考场上忘了就去 tut_labs.pdf 的 Lab Week 7 Q1 抄。
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]) # 公式 3
14.7147
3
14.71479.3 Mallows' Cp
对一个有 p 个参数的候选模型(全模型有更多参数):
= 候选模型的 , = 全模型的 。选 Cp 最小的模型;好的模型 Cp ≈ p(没有偏差)。
- 第一项 p:模型越复杂越大(惩罚复杂度)
- 第二项:漏掉重要变量 → 偏大 → 这一项变大(惩罚拟合差)
- 全模型的 Cp 恰好等于 p(因为 )
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[1] 2.005401 [1] 4
leaps 包一次算所有子集(讲义和 Lab 7 的写法):
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)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
越小越好。和 Cp 一样是"拟合 + 复杂度惩罚"。对正态线性模型,AIC 和 Cp 是等价的准则(讲义)。注意 R 里有两个函数:extractAIC() 用上面的公式(stepAIC 显示的值),AIC() 包含了所有常数项,两者数值不同,但比较模型时结论一样。
AIC(cheese_mod) # 227.7838(讲义表里的值)
extractAIC(cheese_mod) # 第二个数 140.6475(stepAIC 里显示的值)[1] 227.7838 [1] 3.0000 140.6475
9.5 逐步选择:forward / backward / stepwise
变量多时子集太多(10 个变量就有 1024 个模型),只能一步一步走:
- Forward:从只有截距开始,每一步试着加入一个变量,选让 AIC 降得最多的;没有任何加入能降低 AIC 时停止。
- Backward:从全模型开始,每一步试着删掉一个变量;没有任何删除能降低 AIC 时停止。
- Stepwise(both):每一步既可以加也可以删。
library(MASS) # stepAIC 在 MASS 包里(R 自带)
null_mod <- lm(taste ~ 1, data = cheese)
stepAIC(null_mod, scope = ~ Acetic + H2S + Lactic, direction = "forward")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。
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)—— 助教点名的题型
(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.
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)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. ,当 时 :模型几乎没解释任何东西,而惩罚项让它变成负数。
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))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 的路径
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.
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 的第一行(当前模型):
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 这些方法的问题(判断题素材)
- Forward 和 backward 不一定得到同一个模型,也不保证找到全局最优:它们只看了一小部分子集,路径是确定的、贪心的(2025 判断题第 5 题:True)。
- Stepwise 的结果可能依赖起点。
- 选完模型后再用同一份数据做 CI / p 值(post-selection inference)是无效的:显著性会被高估。
- (以下两条 Lab Test 只要求概念;期末要会实际跑,见第 13 章)验证集方法(随机分成训练集/测试集)结果依赖随机划分,不稳定;K 折交叉验证更稳定。LOOCV 就是 PRESS:。
- LASSO:在最小二乘上加约束 ,会把一些系数压成恰好 0,同时完成"选变量 + 估计"。t 用交叉验证选。(详见第 13 章 13.6。)
- 会写 PRESS 函数,知道
- 会 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 形、弯曲) |
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)。
答案(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 章:。各个残差方差不同,高杠杆点的残差天生就小(线被它拽过去了)。所以要把每个残差除以它自己的标准差,放到同一把尺子上比较。
10.3 三种标准化残差
| 名字 | 公式 | R | 分布 |
|---|---|---|---|
| 标准化残差(σ 已知,理论上的) | N(0,1) | ||
| 内学生化残差 internally studentized (R 叫 standardized residuals) | rstandard(model) | 不是精确的 t( 和 不独立) | |
| 外学生化残差 externally studentized | rstudent(model) |
= 去掉第 i 个点后重新拟合得到的 。为什么要去掉?如果第 i 个点真是离群点,它会让 变大,把自己的 "稀释"掉;去掉它再估计 σ 就没有这个问题,而且 和 独立,所以 精确服从 。
捷径公式(不用重新拟合):。
玩法:把红点往上拖离开其他点,看 r 和 t 怎么变大;t 总是比 r 更"极端"。再把红点拖到最右边(高杠杆)然后上下拖,注意普通残差 e 很小但 t 依然可能很大。
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 就是这个[1] 0 [1] 4.440892e-16
10.4 标准化 PRESS 残差 = 标准化残差(2025 判断题 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)." → True。
理由:,,所以 。因此
正好是标准化的普通残差。
10.5 离群点检验
用外学生化残差做检验(mean shift 模型:第 i 个误差的均值不是 0):
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
21
-3.370171
21
0.003897903p = 0.0039 < 0.05 → 拒绝 H0,第 21 号观测可能是离群点,需要进一步调查。2 * pt(-abs(t), df) 和 2 * (1 - pt(abs(t), df)) 是同一个东西。
10.6 2025 Part II (c):最大的正外学生化残差
model <- lm(Volume ~ Height, data = trees)
max(rstudent(model)) # 答案
which.max(rstudent(model)) # 是第几个观测[1] 2.622258 31 31
| 题目问 | 代码 |
|---|---|
| largest positive externally studentized residual | max(rstudent(model)) |
| largest (in absolute value) externally studentized residual | max(abs(rstudent(model))),再用 which.max(abs(...)) 找是哪个 |
| most negative | min(rstudent(model)) |
| internally studentized / standardized residual of obs 5 | rstandard(model)[5] |
| how many |rstudent| > 2 | sum(abs(rstudent(model)) > 2) |
10.7 plot(model) 的四张图
par(mfrow = c(2, 2)); plot(model); par(mfrow = c(1, 1))- Residuals vs Fitted:线性 & 等方差
- Normal Q-Q:正态(纵轴是 rstandard)
- Scale-Location:纵轴 ,看等方差、找大残差
- Residuals vs Leverage:横轴杠杆,纵轴 rstandard;右上/右下角的点(高杠杆 + 大残差)最值得注意
图上自动标出的数字(如 31)是最极端的几个观测的行号。
每张图"正常"和"不正常"分别长什么样,第 25 章用模拟数据画了对照图。
- 能对着残差图说出哪个假设被违反
- rstandard = 内学生化(用 σ̂);rstudent = 外学生化(用 σ̂₍₋ᵢ₎),~
- 能证明标准化 PRESS 残差 = 标准化残差
- 会
max(rstudent(model))和离群点 p 值
第 13 章 · 模型选择进阶: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 个预测变量时,一共有 个子集模型。最优子集选择(best subset selection)的做法是:对每个大小(1 个变量、2 个变量……)在所有同样大小的模型里挑 RSS 最小的那个。同样大小的模型参数个数一样,所以直接比 RSS 是公平的。
不同大小的模型之间不能比 RSS,因为变量越多 RSS 越小。这一步要用 adjusted R²、Cp、PRESS 或 AIC(第 9 章)。
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)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 行是全模型。
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 <- 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)))[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)." 两个标准可能选出不同的模型,各自报告即可。
答案模板
PRESS = sum of squared prediction errors , where each 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)
思路:把数据随机分成两半,用训练集拟合模型,去预测测试集,算测试误差 。测试误差小的模型预测能力好。
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)[1] 2.525176 [1] 36.4298
同一个模型,只是换了随机划分,测试误差从 2.5 变成 36.4。这就是讲义说的验证集方法的缺点:结果依赖随机划分,很不稳定;而且只用一半数据拟合,浪费了信息。
predict(lm(..., data = risk[test, ])),就变成了在测试集上拟合再预测自己,算出来的只是测试集的 RSS/n,不是测试误差。13.4 Lab 7 Q3 (b):最优子集 + 测试误差
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)[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 次,取平均。
留一法 LOOCV 是 K = n 的特例:每次只留 1 个点。对线性模型不用真的拟合 n 次,因为 。
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)[1] 103.1724 [1] 104.5146
| 方法 | 优点 | 缺点 |
|---|---|---|
| 验证集 | 简单 | 依赖随机划分,不稳定;只用一半数据拟合 |
| K 折 CV(K = 5 或 10) | 稳定得多;每个点都当过一次测试点 | 要拟合 K 次 |
| LOOCV(K = n) | 没有随机性;线性模型有公式 PRESS/n | 一般模型要拟合 n 次 |
13.6 LASSO
LASSO 在最小二乘上加了一个惩罚:最小化 。λ 越大,系数被压得越小,有些会恰好变成 0,所以 LASSO 同时完成"选变量 + 估计"。它是另一种在偏差和方差之间做权衡的方法:牺牲一点偏差,换来更小的预测方差。λ 用交叉验证来选。
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)[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 要的是不含截距列的预测变量矩阵。
- 会用
regsubsets(),会读 * 号,照着写出每个大小的最优模型 - 会对这几个模型用
lm()重新拟合,算 adjusted R² 和 PRESS 并选模型 - 能用一句话解释 PRESS 在模型选择里的作用
- 说得出验证集、K 折 CV、LOOCV 的区别,以及 LOOCV = PRESS/n
- 知道 LASSO 会把一些系数压成 0,λ 用交叉验证选
第 14 章 · 残差的性质 + 用哑变量做离群点检验
配套脚本:
R/ch14_residuals_outlier_dummy.R 原题:讲义 Week 7–8、Tutorial Week 5 Q13。14.1 残差的均值和协方差矩阵
回忆 。把 代进去,用 (第 11 章 T7):
用到:; 对称、幂等。
由此得到三个结论(判断题常考):
- :残差比误差"小",即使模型完全正确,残差的方差也不相等。
- ():残差之间一般相关,不像误差那样不相关。
- 误差正态时,每个分量 。
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][1] 4.4309e-13 [1] 1.526557e-16 [1] 0.06849128
第一行是 0(只差电脑的舍入误差),说明 ;残差和为 0(有截距);,所以 相关。
14.2 Normal Q-Q 图
原理:如果 来自 ,那么把排好序的 对着标准正态的期望顺序统计量画图,应该近似是一条直线(截距 μ、斜率 σ)。R 的 plot(model, which = 2) 画的是内学生化残差 rstandard 的 Q-Q 图。
par(mfrow = c(1, 2))
plot(cap_mod, which = 2)
qqnorm(rstandard(cap_mod)); qqline(rstandard(cap_mod))
par(mfrow = c(1, 1))14.3 mean shift 离群点模型:加一个哑变量
怀疑第 k 个观测是离群点。mean shift 模型假设它的误差均值不是 0:,其他 。等价于在模型里加一个哑变量 (),(其他):
检验 就是看这个哑变量的 partial t 检验。
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)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 freedomwhich.max 的输出上面一行是行名(21),下面一行是位置(19)。哑变量要按位置造。考试题会直接告诉你命令(例如 c(rep(0,5),1,rep(0,23))),照抄就行,但要会数:前面 0 的个数 = k − 1,后面 0 的个数 = n − k,总长 = n。14.4 关键结论:哑变量的 partial t = 外学生化残差 t_k
summary(m_dummy)$coefficients["dummy", "t value"]
rstudent(cap_mod)[k]
ti <- rstudent(cap_mod)[k]
2 * pt(-abs(ti), df = n - p - 1)[1] -3.370171
21
-3.370171
21
0.003897903完全相等,p 值也和第 10 章 10.5 用外学生化残差做的离群点检验一样。所以:
答案模板
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 of the original model, and both follow under .
= 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 残差:
residuals(m_dummy)[k]
coef(m_dummy)["dummy"]
residuals(cap_mod)[k] / (1 - hatvalues(cap_mod)[k]) 21
2.081668e-17
dummy
-1.510269
21
-1.51026914.5 考场答题模板(2023 Q1 Part III (b) 4 分 / 2021 Q2 (b) 4 分)
答案模板(数字用 2023 数据,见第 22 章)
vs (coefficient of dummy).
Test statistic: t = 0.972 (from the summary output, row "dummy").
Null distribution: for the model with the dummy, i.e. (等价地,原模型的 ,同一个数)。
p-value = 0.340 > 0.05, so we do not reject . There is no evidence that the 6th observation is an outlier (its mean is not shifted).
14.6 Tutorial Week 5 Q13:mean shift 下残差的期望
答案
记 为第 j 个标准基向量(第 j 个位置是 1),则 ,:
含义:普通残差把偏移"缩小"了 倍(高杠杆点缩得更厉害,所以普通残差不适合找离群点);PRESS 残差是无偏的。这也是第 11 章判断题第 37 题的来源。
- 能证明 、、
- 知道残差方差不相等、残差之间相关
- 会造哑变量(数清楚前后各几个 0),会读 dummy 那一行的 t 和 p
- 知道 dummy 的 partial t =
rstudent(原模型)[k],自由度 n − p − 1,能回答"是不是同一个检验"
第 15 章 · 影响点:Cook's D、DFFITS、DFBETAS、COVRATIO(含证明)
formula sheet 上已经印了 、、Cook's D、DFFITS 的定义,不用背;要背的是从定义推到捷径公式的证明过程。
配套脚本:
R/ch15_influence.R 原题:讲义 Week 8(rats、fish biomass)、Lab Week 8 Q1(compensation)。15.1 什么是影响点(influential observation)
一个观测放进去或拿出来,会让结论(系数、拟合值、检验结果)发生很大变化,它就是影响点。
- 只是杠杆高(x 离得远),但跟着整体趋势走 → 不一定有影响。
- 只是残差大(y 偏离),但 x 在中间 → 往往影响也不大。
- 杠杆高 + 外学生化残差大 → 影响最大。
玩法:把红点拖到最右边,再上下拖。蓝线(用所有点)和灰虚线(去掉红点)差得越远,红点的影响越大。只上下拖、不往右拖,两条线差别就小得多。
15.2 rats 例子:一个点决定了整个结论
讲义的故事:19 只老鼠,研究者原本认为肝里的药量 y 和体重、肝重、剂量都没关系。但全模型说 Weight 和 Dose 都显著,而单独回归时谁都不显著。
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) 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 只老鼠杠杆 ,远大于 ;它的外学生化残差并不大(0.80)。把它去掉:
summary(lm(y ~ Weight + Liver + Dose, data = rats[-3, ]))$coefficientsEstimate 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 四个影响度量:定义、含义、经验标准
记号: = 去掉第 i 个观测后的最小二乘估计; = 用这个估计在 处的预测值; = 去掉第 i 个观测后的 σ 估计; = 内学生化残差(rstandard), = 外学生化残差(rstudent)。
| 度量 | 定义 | 捷径公式 | 衡量什么 | 经验标准 |
|---|---|---|---|---|
Cook's Dcooks.distance | 去掉第 i 个点后所有参数(因而所有拟合值)变了多少 | 有影响,> 0.5 值得看;或和 的 50% 分位数比 | ||
DFFITSdffits | 第 i 个拟合值变了几个标准误 | |||
DFBETASdfbetas | , = 第 j 个对角元 | (不讲) | 第 j 个系数变了几个标准误 | |
COVRATIOcovratio | 去掉第 i 个点后估计的精度怎么变 | > :去掉后精度变差;< :去掉后精度变好 |
补充两个关系:(所有拟合值变化的平方和);。
15.4 influence.measures:一次全给出
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 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 对杠杆用 的标准)。
解读第 3 只老鼠(讲义原话的意思):
- Cook's D = 1.82 > 1,也 > → 有影响。
- DFFITS = 2.35 > 2 → 去掉它,第 3 个拟合值会变 2.35 个标准误。
- DFBETAS:Weight −2.05、Dose 2.17,绝对值 > 2 → 这两个系数会各变大约 2 个标准误。
- COVRATIO = 5.71 > → 去掉它,参数估计的精度会变差(它的高杠杆在"帮"估计变精确)。
- 。
15.5 用捷径公式和定义两种方式验证(证明题的数值版本)
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]))[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 原题)
题目总会给你下面这个结论,不要求证明,直接用:
其中 是 X 的第 i 行, 是第 i 个普通残差,。
is the least squares estimate of β using all n observations; is the least squares estimate obtained by fitting the model without the i-th observation. So is the change in the estimated parameters caused by deleting the i-th observation.
Cook's distance 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 . A large indicates that observation i is influential.
由 :。代入 Cook's D 的定义:
因为 ,即 。
每一步用到:① 且 对称,所以 ;② 、 是数,可以提出来;③ ;④ 的定义。
is the fitted value at from the model fitted to all the data, so . is the prediction of the i-th response from the model fitted without the i-th observation; that model has estimate and we evaluate it at the same predictor values , so .
= the change in the fitted value at the i-th point when the i-th observation is deleted. 2021 Q6(b) 要求在散点图上画出来:在 处,黑线(全部数据拟合)和红线(去掉第 i 点拟合)之间的竖直距离。
期望:(第 14 章), 只依赖 X,是常数,所以
方差:,所以
用 P15-4 的结果代入定义,再凑出 :
关键一步:,。
- 每道小题第一行先写定义(例如 "By definition, " 或 "Recall "),哪怕后面推不下去也有分。
- 题目写 "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 分)
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 超过了对应值。
答案模板
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 (). 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))
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)[1] -2.545755
11 12 13
1.53966559 0.09794702 1.747255132021 Q6(c): → by the rule of thumb from lectures, observation 14 is influential:去掉它,第 14 个拟合值会变约 2.5 个标准误。
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 using the formula 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 ). Obs 12 has a similar leverage but a small residual, so it is not influential.
(ii) p = 3(截距 + x1 + x2)。注意题目给的是 rstandard,就是公式里的 (内学生化残差):
两个都 > 1,确认是影响点。作对比:,杠杆同样高,但残差小,所以没影响。
15.9 去掉影响点后区间变窄(讲义 fish biomass)
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") 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 < )→ 去掉它们,估计的精度会大幅提高。确实如此:σ̂ 从 138.5 降到 31.1,预测区间宽度从约 685 缩到约 165。
15.10 Lab Week 8 Q1:compensation(33 家公司)
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)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 偏小(残差较大),值得看一眼。
(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.
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)25
25
[1] 0.878591
(Intercept) Profits
all 371.5918 0.1273929
without25 340.7724 0.2751123
Estimate Std. Error t value Pr(>|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 等高线
- 会用给定的 、、 手算 DFFITS 和 Cook's D
第 16 章 · 变换:方差稳定、log、在原尺度比较、多项式回归
配套脚本:
R/ch16_transformations.R 原题:讲义 Week 9(geese、inflation、trees)、Lab Week 8 Q2(fish)、Tutorial Week 9 Q3。16.1 为什么变换能稳定方差(Tutorial Week 9 Q3)
很多数据的方差会随均值变大(残差图呈喇叭形)。对响应做变换 ,在 附近做一阶 Taylor 展开:
选 f 让右边变成常数,方差就"稳定"了:
| 方差和均值的关系 | 变换 | 验证 | 典型场景 |
|---|---|---|---|
| , | 计数数据、Poisson | ||
| , | 指数分布、"按比例"变化的量 | ||
| 比例数据 |
y 有 0 时用 或 。
设 ,比例 :,,方差随均值变化。取 ,用链式法则:
代入 Taylor 公式 :
和 p 无关,是常数,所以方差被稳定了。
答案
(a) 。,所以 ,是常数。
(b) ,。,所以 ,是常数。
16.2 snow geese:试 √ 再试 log
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 数据画出来的图)
思路:对每个模型用 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 的车离其他点很远。考试时如实写出你在图上看到的东西就行。
16.4 inflation:log(INF)
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 拟合模型。第 i 个 PRESS 残差在 z 尺度上是 。要在原尺度上比较,就把预测值变回去:,然后算
拿它和原模型的 PRESS 比。
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)[1] 16070.89 [1] 21610.81
和讲义表格里"with obs 20, 22"那一列一致(16,071 和 21,611):按这个标准原模型反而更好。讲义解释:这是离群点造成的,去掉观测 20、22 后结论反过来,log 模型更好(6501.7 < 6738.5)。代码里的关键一步:。
16.6 Lab Week 8 Q2:fish(幂函数关系)
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)))(Intercept) log(length)
-13.763624 3.368046
1
611.4922为什么取 log: 两边取 log 得 ,在 log 尺度上是线性的。原模型的 Residuals vs Fitted 有明显 U 形(线性不成立),Q-Q 图右偏;log-log 模型的残差图好得多。
拟合线:,即 。预测 400mm 的鱼:先在 log 尺度预测,再 exp 回去,约 611.5 克。
log(length),newdata 里填原始的 length = 400,R 会自己取 log。如果像真题那样先建了一列 log.disp 再用 log.mpg ~ log.disp,那 newdata 里要填 log.disp = log(240)(第 22 章)。16.7 多项式回归:trees
均值结构不是线性时,可以加入预测变量的平方项。 对参数仍然是线性的,所以还是线性模型,照样用 lm()。
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)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() 不能省)。
- 会用 Taylor 展开说明 √y、log y 为什么能稳定方差
- 能写"比较两个模型诊断图"的答案:逐条说假设,选出更好的模型,再提一下影响点
- 知道不同尺度的模型不能比 R²;会在原尺度上算 PRESS
- log 模型的预测要
exp回去;newdata 填原值还是 log 值要看公式怎么写 - 会加平方项做多项式回归,用 AIC 或 F 检验判断要不要
第 17 章 · 加权最小二乘 WLS 与广义最小二乘 GLS(含证明)
配套脚本:
R/ch17_wls_gls.R 原题:讲义 Week 9、Tutorial Week 9 Q1–Q2。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)) (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 = ) 结果一致。
17.2 GLS 与 MLE(Tutorial Week 9 Q1)
更一般地,设 ,V 是任意已知的协方差矩阵(不一定对角)。广义最小二乘 GLS 最小化 。WLS 是 (对角)的特例;普通最小二乘是 的特例。
,似然(formula sheet 第 2 页有多元正态密度):
只有指数部分含 β,所以最大化 L ⇔ 最小化 ,即 MLE = GLS 估计。展开。中间两项 和 都是 1×1 的数,数的转置等于它自己:(V 对称,所以 也对称),因此两项合并成 。求导用 formula sheet 的 和 ;这里 对称,所以 :
记 ,:
是正态向量 y 的线性变换,所以 。取 就得到 WLS 的 、。
| 权重怎么定义 | V | 出现在 | |
|---|---|---|---|
| (σ² 未知, 只给相对大小) | 讲义;期末 2021 Q5、2023 Q3(权重叫 ) | ||
| (每个方差都已知) | ,没有 σ² | Tutorial Week 9 Q2 |
17.3 期末证明题:无截距模型的 WLS(2023 Q3 / 2021 Q5,各 15 分)
(a) [2] Derive the weighted least squares estimator of β by minimizing .
(b) [2] Find and .
(c) [3] Find the mle of β if, in addition, the errors are normally distributed. Does the mle coincide with ?
(d) [3] Multiply both sides of (1) by … Show that the new model (2) is the ordinary least squares regression model with no intercept, that is, the errors 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 .
(f) [3] Find an expression for when , . Write down the model (2) in this case and comment on your findings.
二阶导 ,所以是最小值(写一句即可)。
,, 互不相关。 是 的线性组合:
方差那一步用了"不相关":协方差项都是 0。
误差正态且不相关 ⇒ 独立,:
"const" 不含 β。所以最大化 ⇔ 最小化 ,得 。Yes, the mle coincides with .(也可以对 log L 求导令其为 0,得到和 (a) 一样的方程。)
, 是常数:
- ii) ;
- iii) ,对所有 i 相同;
- i) 时 。
因此 (2) 是误差不相关、零均值、方差恒为 σ² 的普通无截距回归模型。
无截距模型的普通最小二乘估计是 (2021 Q5(a) 要求推导它并求期望和方差:就是 (a)(b) 中 的情形,,,)。用在模型 (2) 上:
⇒ 。代入 (a):
模型 (2):,两边除以 :
Comment:after the transformation, the model is simply a constant-mean (intercept-only) model for the ratios with constant variance σ², so the WLS estimator is just the sample mean of the ratios . Observations with large (large variance) are effectively down-weighted.
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)xi x_new 2.077146 2.077146 2.077146 [1] 2.077146
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)wls ols 0.03394474 0.05157578 [1] 0.03333333
模拟方差 0.0339 ≈ 理论值 ;同样数据下 OLS 的方差(0.052)更大。方差不恒定时 OLS 仍然无偏,但不再是最有效的。
17.4 讲义 EPS 例子(R 写法)
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)$coefficientsEstimate 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 = 填的是 (与方差成反比),不是方差本身。讲义里的 lm.gls 来自 MASS 包,考试不会要求。
- 说得出 WLS 最小化什么,权重和方差什么关系()
- 会写 、,能用 GLS 的 MLE 推出来
- 能独立写完 2023 Q3 的 (a)–(f)(15 分,2021 年考过主干相同的题)
- R:
lm(y ~ x, weights = w);无截距lm(y ~ x - 1)
第 18 章 · 分类变量(哑变量)与交互项
配套脚本:
R/ch18_categorical_interactions.R 原题:讲义 Week 10、Lab Week 10 Q1–Q4。18.1 两水平的分类变量:哑变量
inflation 数据里 DEV = 1 表示发达国家、0 表示发展中国家。0 和 1 只是标签,用来区分两组。把它当作预测变量放进模型( = DEV):
两条平行线:斜率都是 ,截距差 。 = 在 x(QUES)相同的情况下,两组 y 的期望差("after adjusting for x")。检验组效应:看 的 partial t,。
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)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 . Holding QUES constant, going from a developing to a developed country changes inflation by , i.e. reduces it by 22.79.
18.2 用文字标签时,R 自动编码
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)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 交互项:不平行的线
= 截距之差, = 斜率之差。三种情况:
| 情况 | 含义 | 怎么检验 |
|---|---|---|
| 两组完全一样(同一条线) | → 嵌套 F 检验:anova(lm(y ~ x), lm(y ~ x * w)) | |
| , | 平行线:组间差别不随 x 变 | |
| 不平行:x 的效应在两组不同 | → 交互项的 partial t |
inf_int <- lm(INF ~ QUES + DEV + QUES:DEV, data = inflation)
summary(inf_int)$coefficients
anova(lm(INF ~ QUES, data = inflation), inf_int)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:,F = 2.13,p = 0.148 → no evidence of a difference in inflation between the two groups. B:,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 的简写。讲义还提醒:这个模型的残差图显示两组方差差别很大,检验结论可能不可靠。
18.4 讲义 mussel 例子(数据没发,只看输出)
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:;地点 2:。这里也先做了 log 变换来稳定方差(第 16 章)。
18.5 三个及以上水平:r 个水平用 r − 1 个哑变量
讲义 real estate:房价 y、面积 x、取暖方式 z ∈ {electricity, heating oil, natural gas}。定义 (electricity),(heating oil);两个都是 0 就是 natural gas(参照组):
= electricity 和 natural gas 的差, = heating oil 和 natural gas 的差。为什么不能用 3 个哑变量:三个加起来恒等于 1,等于截距那一列,X 不满秩(第 19 章)。
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 ***"取暖方式对房价有没有影响" = ,不能看 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(三组,看均值)
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]])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- (a) 安慰剂(参照组)均值 = 截距 10.27;新药 = 10.27 − 2.13 = 8.13;维生素 C = 10.27 − 3.87 = 6.40。
- (b) "三组均值相同" ⇔ ,这正是 summary 最后一行的 overall F 检验(模型里只有这两个哑变量):F = 2.66,p = 0.082 → 5% 水平下不拒绝,只有弱证据。
- (c) 新药 vs 安慰剂:Dummy1 的 t 检验,p = 0.21 → 没有证据表明新药更好。维生素 C vs 安慰剂:p = 0.026 → 有证据表明维生素 C 组感冒天数更少。
18.7 Lab 10 Q1、Q3、Q4(同样套路)
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 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(石油危机)。
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))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)。
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) 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 检验 ,即四组均值都相同;p = 0.004 → 至少有一组不同。factor(..., levels = ) 决定水平顺序,第一个就是参照组。
18.8 换参照组:relevel
summary 里每个哑变量的 t 只比较"这一组 vs 参照组"。想比较两个非参照组(比如 Light Brunette vs Dark Brunette),就把其中一个设为参照组重新拟合:
hair$Colour2 <- relevel(hair$Colour, ref = "DarkBrunette")
summary(lm(Pain ~ Colour2, data = hair))$coefficientsEstimate 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 章)。
- 能写出每组的 ,说清楚每个系数的含义(参照组、组差、斜率差)
- "组之间有没有差别"用嵌套 F(或模型里只有哑变量时用 overall F);单个组 vs 参照组看 partial t
- 交互: 的 t 检验 = 斜率在组间是否相同;能写出每组的拟合线
- 会
factor、relevel、model.matrix,知道 R 默认按字母顺序选参照组 - r 个水平只用 r − 1 个哑变量(否则不满秩)
第 19 章 · 非满秩模型、单因素分类模型、一般线性假设
配套脚本:
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 组, = 第 i 组的第 j 个观测():
μ = 总体均值(grand mean), = 第 i 组的组效应,即第 i 组均值偏离 μ 多少。目的:检验各组均值是否相同、比较两组之间的差。
写成回归:,(属于第 v 组)否则 0。讲义 height 例子(4 男 4 女):
X 的第 1 列 = 第 2 列 + 第 3 列(每个人恰好属于一组),所以 X 不满秩, 不可逆,正规方程没有唯一解,μ 和 不能唯一估计。
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)[1] 2 [1] 0
3 列但秩只有 2。解决办法:重新参数化,让 X 满秩。
19.2 方法 1:哑变量编码(选参照组 m)
把参照组 m 的那一列去掉,令 :
截距 = 参照组的均值; = 第 i 组均值和参照组均值的差。检验"第 i 组和参照组一样": 的 partial t;检验"所有组均值相同":: 所有 ,即 overall F。这就是第 18 章 R 默认的做法。
height <- data.frame(Height, Gender)
height$Gender <- relevel(height$Gender, ref = "M")
model1 <- lm(Height ~ Gender, data = height)
model.matrix(model1)
coef(model1) (Intercept) GenderF
1 1 0
...
5 1 1
...
(Intercept) GenderF
173.25 -6.25男性均值 173.25;女性 = 173.25 − 6.25 = 167。
19.3 方法 2:去掉截距,直接估计每组均值
利用 ,令 :
X 去掉全 1 列,每组一列 0/1,满秩。参数就是各组均值。R 里写 y ~ group - 1(或 -1 + group)。
model2 <- lm(Height ~ Gender - 1, data = height)
model.matrix(model2)
coef(model2)GenderM GenderF 1 1 0 ... 5 0 1 ... GenderM GenderF 173.25 167.00
19.4 tax forms(Lab 10 Q5 / Tutorial Week 9 Q4)
答案
以 Current Format 为参照组,3 个哑变量:(Format A),(Format B),(Format C)。X 有 4 列 :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))讲义没讲,不考。
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 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 一般线性假设
想检验 ?在方法 2 下就是 ,partial t 和 overall F 都不能直接回答。把它写成参数的线性组合:
多个约束一起检验(如 且 )就把它们堆成矩阵:
m = 1 时的推导(讲义给了,m 一般时不要求证明):,所以 。标准化后平方:
σ² 未知,要换成 。用 F 分布的定义:两个独立的卡方各自除以自由度再相除,就是 F 分布。已知 ,并且 与 b 独立,所以
σ² 上下约掉了,所以能用数据算出来。m = 1 时 ,。
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) 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:F = 12.83 ~ ,p = 0.0025 → 拒绝,B 和 C 的平均用时不同(和讲义 linearHypothesis 的结果一致)。:F = 6.50 ~ ,p = 0.0086 → 三种新格式不全相同(和 Lab 10 答案一致)。
coef(model));② 每个等式移项成"… = 0",一个等式一行;③ 系数按参数顺序填,没出现的参数填 0。同一个假设在不同参数化下 C 不同:方法 1 的 β = (μ_a, A−a, B−a, C−a),"μ_A = μ_B" 变成 (A−a) − (B−a) = 0,即行 (0, 1, −1, 0)。结果完全一样: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)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 **
第二种算法: 成立时 A、B、C 是同一个均值,相当于只有两组(a 和 ABC)的约束模型;约束模型 vs 全模型的嵌套 F 检验给出同一个 F = 6.4987。这说明一般线性假设就是第 7 章"万能 F 公式"的推广。
讲义第二个例子(Week 10 slide 92): 且 。第二个约束不是"两个均值之差",所以换参照组时 C 的写法变化更大,正好练手:
| 参数化 | β 的顺序 | 这一行 | 这一行 |
|---|---|---|---|
| 方法 2(无截距) | (0, 0, 1, −1) | (1, −1, 1, 0) | |
| 方法 1,参照组 B | (0, 0, 0, 1) | (1, 1, −1, 0) |
参照组 B 下第二行怎么来:,,代入得 ,所以截距 的系数是 1,不是 0。
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) 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 ~ ,p = 5.1e-08 → 拒绝 ,和讲义 linearHypothesis 的结果一样。(输出用科学计数法:5.733133e+01 = 57.33。)
library(car); linearHypothesis(model, C)。考场电脑如果没装 car,就用上面的 GLH 函数(6 行,可以照讲义公式现场写出来),或者用"约束模型 vs 全模型"的 anova。三种方法结果相同。- 能说出 为什么不满秩(第一列 = 其余列之和)
- 方法 1 / 方法 2 的设计矩阵长什么样、参数是什么意思、R 怎么写(
~ groupvs~ group - 1) - 能把文字假设写成 C 和 d,会算 F 和自由度
- 知道 m = 1 时 F = t²,能写出 m = 1 的推导思路
第 20 章 · Logistic 回归(可能考,优先级最低)
配套脚本:
R/ch20_logistic.R 原题:Lab Week 10 Q6。20.1 模型
响应是 0/1(是/否)。线性模型会预测出 0–1 之外的值,所以改为对log odds 建线性模型:
叫 odds(几率)。参数用最大似然估计,R 用 glm(..., family = binomial)。
20.2 Lab 10 Q6
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")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- (a)(b): 是 log odds;odds ;概率 。
predict(m, new)默认给 log odds,加type = "response"给概率。 - (c):summary 里 Sepal.Length 一行,z = −0.378,p = 0.706 > 0.05 → 不显著。logistic 回归里是 z 检验(近似正态),不是 t。
20.3 比较嵌套模型:偏差(deviance)之差 ~ χ²
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))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):似然比检验,:Sepal.Length 和 Petal.Length 的系数都是 0。统计量 = 两个模型 residual deviance 之差 = 6.60, 下近似 (df = 多出来的参数个数),p = 0.037 < 0.05 → 全模型更好。这和线性模型里"嵌套 F 检验"的角色一样。
- 会写 log odds = ,会从系数算 odds 和概率
glm(..., family = binomial);单个系数看 z 检验- 嵌套模型:
anova(m_small, m_big, test = "Chisq"),deviance 之差 ~ χ²
第 11 章 · 理论题专项:证明模板 + 判断题库(Q1 的 25 分)
配套脚本:
R/ch11_theory_check.R(每个结论都用数字验证一遍,先看到它成立再证明)考场上可以翻 tut_labs.pdf 里的 tutorial 答案和 Lecture Notes:这些证明都在里面,你练过就知道去哪找、怎么改。
11.1 答题策略(先看这个)
- 判断题:每题 2 分,答案对 + 理由对才拿满。理由写 1–3 行即可,最好带一个公式(比如 "tr(H) = tr((XᵀX)⁻¹XᵀX) = tr(I_p) = p")。False 的题最好给一个反例或者正确的版本。
- 证明题:分步给分。先写定义/已知条件(例如 "Cov(U,V) = E[(U−EU)(V−EV)ᵀ]"、"b = (XᵀX)⁻¹Xᵀy"、"Cov(y) = σ²I"),哪怕后面卡住也有分。每一步写清楚用了哪条性质("since H is symmetric and idempotent"、"by part (a)")。
- 后面小题可以用前面小题的结论,即使前面没证出来。2025 年 (b) 就明确用了 (a)。
- 老师原话:学生在证明题上最差,经常整题空着。所以哪怕只会第一步,也要写。
- formula sheet 考场上能看,可以直接当已知结论引用(写 "by the formula sheet"):第 4 页有 、、向量求导 、;第 2 页有多元正态密度(写似然函数用);第 3 页有 、 和 F 统计量的分布。
但只能在证明别的结论时引用:如果题目让你证明的正是这条公式(如 Mock 3 (a) 证 E(yᵀAy),2025 (a) 证 Cov(AY,BZ)),只写 "by the formula sheet" 得 0 分,必须写完整推导。
11.2 工具箱:所有证明只用这 12 条
| # | 工具 |
|---|---|
| T1 | ; |
| T2 | ;; |
| T3 | ;; 对称 |
| T4 | ;;数的迹是它自己 |
| T5 | 模型:,, ⇒ , |
| T6 | ;;; |
| T7 | ,,,,, |
| T8 | , |
| T9 | (formula sheet 第 4 页有;证明别的结论时可引用,题目要你证它时必须推导) |
| T10 | SLR:,,,, |
| T11 | , |
| T12 | 有截距时,(全 1 向量)是 X 的一列 ⇒ ,,(残差和为 0) |
11.3 证明模板库(按出现概率排序)
用到:T1()、T3(转置顺序)、常数矩阵提到期望外面。
记 ,。由 P1(取 ,,)和 :
(因为 。)又 ,所以协方差是零矩阵。∎
意义:残差和估计量不相关(正态时独立)—— 这正是 和 b 独立、t 统计量服从 t 分布的原因。
最后一步: 对称且幂等(T7)。
对称:。
幂等:。
迹:。
推论:,平均杠杆 。
(a) 。
(b) ;H 是 ,对称。
(d) 。
(e) ,,一般不为 0(残差是相关的)。
(f) 。
,且 ,所以
(V 对称,;。)
另一种写法(更短): 是一个数,等于它的迹:。
用 P7,,,:
因为 ,。所以 。∎ SLR 版本(Tutorial Week 3 Q1)就是 。
矩阵:。 ⇒ ⇒ (满秩时 可逆)。
SLR:,。第一式 ⇒ ,代入第二式 ⇒ 。
⇒ ,似然函数
- 对 β:对任意固定的 σ²,最大化 log L ⇔ 最小化 ⇒ (就是最小二乘)。
- 对 σ²: ⇒ 。
- 它是有偏的:(由 P8)。
如果误差协方差是一般的 (Tutorial Week 5 Q2a),log L 里的二次型换成 ,同样求导得 ;当 时退化成 b。
写 ,(因为 )。 独立,。
(a) SLR 里 ,。
(b) ⇒ ⇒ ⇒ 。并且 。
。只需证交叉项为 0:
因为 ,且有截距时 (T12)。矩阵写法:,J 是全 1 矩阵。
,所以 。
⇒ 标准化 PRESS 残差 = 标准化残差。
()⇒ ⇒ PRESS ≥ SSres(有 就严格大于)⇒ 。
⇒ (第 5 章例题)。,所以 。
Statement:In the linear model with and , the least squares estimator is the best linear unbiased estimator (BLUE) of β: for any other linear unbiased estimator , for all c.
注意:不需要正态假设。
补充模板(tutorial 里出现过的其他证明)
任取另一个线性估计 ,写成 。
- 无偏性逼出 BX = 0:。要对所有 β 都等于 β,必须 。
- 算方差:(交叉项含 或 ,消失)。
- 比较:对任意向量 c,。所以 b 的方差最小:b 是 BLUE。∎
( 半正定:Tutorial Week 3 Q12,。)
(a) (代入 ),平方求和:
(b) ,所以 。又 ,所以 。相减:,除以 得无偏。∎
- 是 m 个标准正态平方和 ⇒ 。
- 下 ⇒ 。
- 一般情况:(P14),。H0 不成立时更大(多了 )—— 这就是 F = MSreg/MSres 大时拒绝 H0 的原因。
- (P19);;H0 下为 。
第 j 个误差均值为 Δ:( 是第 j 个位置为 1、其余为 0 的向量)。
结论:普通残差把偏移"缩水"了 倍,PRESS 残差不缩水 —— 所以找离群点要用 PRESS/学生化残差。
记 (全 1 矩阵)。有截距 ⇒ ⇒ ;又 。令 :
M 对称幂等,同 P12(b) 的论证,它的对角线 ,即 。∎
(b)
(因为 ),除以 即得。
(c) 移项:。 与 联合正态且不相关 ⇒ 独立,所以右边两项独立;用矩母函数(左边的 MGF = 右边两项 MGF 的乘积)⇒ ,且与 独立。
Q4:, 独立。(a) 。(b) 两个分量都是独立 N(0,1),。(c) ,,。
Q5:,,,
Q3: 与 。正态下 MLE = 最小二乘:;。(P11),联合正态 ⇒ 独立。
Q4(两组共同斜率、不同截距):最小化 。对两个截距求导得 ,代回对 β₁ 求导得 。
Q8–Q11:,, 正交。,,投影 ;检查 与 都垂直 ✓。这就是"最小二乘 = 投影"(第 5 章演示)。
mean(rss / (n - p)) # 无偏估计的平均:约等于 sigma^2 = 2.25
mean(rss / n) # MLE 的平均:偏小[1] 2.24836 [1] 1.68627
11.4 判断题题库(先自己判断,再点按钮看理由)
前 5 道是 2025 年原题,其余是根据课程内容出的同类题(共 39 道)。
- P1、P2、P3 能不看答案默写(2025 原题,同类题概率极高)
- P4–P8、P10 能写出主要步骤;P18(Gauss–Markov)、P19–P21 至少会写框架
- 判断题错的那几道,把理由抄一遍
第 21 章 · 期末证明题总表 + 新增判断题
21.1 证明题地图
| 题型 | 出现过 | 模板在 | 优先级 |
|---|---|---|---|
| Cook's D、、DFFITS 捷径公式 | 2014 Q7、2020 Q4、2021 Q6、2023 Q4 | 第 15 章 P15-1 ~ P15-5 | ★★★ |
| 无截距模型的 WLS:推导、期望方差、MLE、乘 √r 变换 | 2021 Q5、2023 Q3 | 第 17 章 | ★★★ |
| ,Var(b),RSS = ε'(I−XS)ε,σ̂² 无偏 | 2021 Q4 | 本章 21.2 | ★★★ |
| (中心化)SLR:推导 b₀ b₁、无偏、不相关、χ² 分布 | 2020 Q1 | 本章 21.3,第 3、11 章 | ★★ |
| SSreg 二次型:、、 | 2020 Q3 | 本章 21.4 | ★★ |
| GLS = MLE,分布 | 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 | ★★ |
21.2 2021 Q4:用 b = β + Sε 证明 σ̂² 无偏(15 分)
(a) [2] Show that we can write b in the form , where . Using this form, show that 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: .)
(c) [4] Using part (a), show that we can write the residual sum of squares in the form .
(d) [5] Apply the results from parts (a) and (c) to show that the usual estimator is unbiased. (Hint: use the formula for .)
进一步:,所以 。( 因为 。)
对称且幂等,所以 也对称幂等:
(如果时间紧,也可以直接展开验证 ,因为 。)
用 ,,:
(迹的循环性:,。)所以 ,unbiased。
21.3 2020 Q1:中心化的 SLR(15 分)
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 and by minimizing .
iii) [3] Show that and are unbiased.
iv) [4] Prove that and are uncorrelated. Then show that .
v) [2] Assume the errors are iid . Find the distribution of .
完整答案
i) ,:,,。
ii) 利用 :
iii) :;。
iv) 记 ,,, 不相关:
;。(或用矩阵:,。)
v) b 是正态 y 的线性变换 ⇒ 联合正态;不相关 + 联合正态 ⇒ 独立。,,平方各 ~ ,独立相加 ⇒ 。
21.4 2020 Q3:SSreg 的期望(15 分)
i) [2] For the ordinary SLR, what is X? What is ?
ii) [3] Show that .
iii) [3] Hence show that .
iv) [2] Find .
v) [5] Prove that . (Hint: use the formula for .)
完整答案
i) X 的第 i 行是 ;。
ii) ,,所以 ,除以 n 即得。
iii) ⇒ 。。
iv) , ⇒ 。
v) ,,:
21.5 判断题:Week 7–10 新内容
和第 11 章同样的用法:先自己判断并写理由,再点按钮看答案。
- 看到题目能马上对上"证明题地图"里的题型,知道模板在哪章
- 能默写 21.2(2021 Q4),这是 Week 3–5 最核心的证明
- 24 道判断题全部能说出理由
第 25 章 · 诊断图图鉴:四张图"坏了"分别长什么样
本章用模拟数据:我们自己故意破坏一个假设,然后看四张图各自怎么反应。每一节都是:
左边 = 数据 + 拟合线(每个点到线的竖线就是残差;红点 = 在线上方,残差为正;蓝点 = 在线下方,残差为负)
右边 = 对应的诊断图(就是
plot(model) 画出来的那张)配套脚本:
R/ch25_diagnostic_gallery.R(运行一遍就能重新生成本章所有图)。左图里点在线上方(红),右图里就在 0 上方;左图里点在线下方(蓝),右图里就在 0 下方。所以左图里红蓝点的排列规律,会原样出现在右图里。看诊断图其实就是在找这种规律:理想情况下红蓝点应该随机交错,没有任何规律。
25.1 线性假设 → 看 Residuals vs Fitted(左上)
| 行 | 左图(数据 + 拟合线) | 右图(Residuals vs Fitted) |
|---|---|---|
| A 正常 | 真实关系就是直线。红蓝点在线两侧随机交错 | 点在 0 上下随机散开,红线基本是平的 ✅ |
| B 违反 | 真实关系是弯的,却硬用直线拟合。两头的点都在线上方(红),中间的点都在线下方(蓝) | 拉平之后就是"红—蓝—红":U 形 ❌ |
| C 补救 | 模型加上 ,拟合线能弯了,红蓝点又随机交错 | U 形消失,红线又变平 ✅ |
- U 形:真实关系向上弯(像 B)。倒 U 形(∩):真实关系向下弯,例如增长越来越慢(对数型、饱和型)。两者都说明 linearity violated。
- 补救办法:加多项式项(如 ),或者对 y / x 做变换(log、sqrt,见第 16 章)。2020 Q2 就是用 log(Price) 和 log(Age) 把 U 形修好的。
- A 里红线在两端也有一点点弯,是因为两端点少、平滑曲线不稳定,这种程度不算违反。判断标准是:大部分点有没有系统性的上下规律。
对照:2020 期末 Figure 1 的左上图就是 B 这种情况(第 24 章)。
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 图的样子 | 结论 |
|---|---|---|---|
| A 正态 | 对称的钟形 | 几乎全部贴着虚线 | 正态 ✅ |
| B 重尾 | 中间很尖,两边有离得很远的点 | 中间贴线;左端往下翘、右端往上翘(两端比虚线更远离 0) | 尾巴太重 ❌(有极端残差 / 离群点) |
| C 右偏 | 左边堆积,右边拖一条长尾巴 | 整体向上弯:左端在线上方变平,右端远远在线上方 | 右偏 ❌(常见于价格、收入,log 常能修好) |
| D 轻尾 | 平平的,没有尾巴 | 左端在线上方、右端在线下方,两端被"压平"(两端比虚线更靠近 0) | 尾巴太轻 ❌ |
2020 期末 Figure 1 的 Q-Q 图:左端一排点在 −1.4 附近变平(在线上方),右端在线下方 → 就是 D 这种轻尾形状。
- R 4.3 以后这张图的标题是 "Q-Q Residuals",旧版本和考卷上是 "Normal Q-Q",是同一张图。
- 样本小的时候,即使误差真的是正态,两端也会有一两个点稍微偏离。只有一两个点偏离不要说成"正态被违反",要看是不是有系统性的弯曲。
如果只是一两个端点偏离: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 的纵轴是 (标准化残差取绝对值再开方):只看残差有多大,不管正负。所以 Residuals vs Fitted 里向右张开的"喇叭",在这里就变成了一条往上走的红线,更容易看出来。
| 行 | 左图 | 中图(Residuals vs Fitted) | 右图(Scale-Location) |
|---|---|---|---|
| A 正常 | 点到线的竖线长短差不多 | 上下宽度处处一样,像一条水平的带子 | 红线水平 ✅ |
| B 违反 | x 越大,竖线越长:点离线越来越远 | 左边窄、右边宽:喇叭形(funnel) | 红线明显往上走 ❌ |
| C 补救 | WLS,权重 :噪声大的点权重小 | 加权残差 的宽度变均匀 | 红线又变平 ✅ |
plot(m, which = 1),画的是没有加权的残差,喇叭形还在(数据本身没变)。要看加权残差 weighted.residuals(m),或者看 Scale-Location(它用的是标准化残差,已经考虑了权重)。另一种常见补救是对 y 做变换:方差随均值变大时,log(y) 或 sqrt(y) 常常能让方差变稳定(第 16 章)。
没问题时:The Scale-Location plot shows no clear trend, so the constant variance assumption looks reasonable.
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 在量的东西。
| 行 | 红点 | Cook's | 右图里的位置 | 影响点? | ||
|---|---|---|---|---|---|---|
| A | 没有加点 | — | — | — | 所有点都在虚线(Cook's 0.5、1)里面,虚线几乎看不到 | 没有 ✅ |
| B | x 在中间,y 离谱 | 0.05(低) | 3.87(大) | 0.39 | 很高但在最左边,没越过虚线 | 离群点,但不是影响点:线几乎没动 |
| C | x 很远,但正好落在直线上 | 0.62(高) | 0(小) | 0 | 在最右边,但纵坐标是 0 | 不是:高杠杆但"听话",线没动 |
| D | x 很远,y 也偏离直线 | 0.62(高) | −4.15(大) | 13.8 | 右下角,越过 Cook's 1 的虚线 | 是 ❌:一个点把整条线拽歪了 |
所以 Residuals vs Leverage 图的危险区在右上角和右下角,Cook's 虚线也正是画在那里。读法:有没有点越过 0.5 或 1 的虚线。
没有影响点时:No observation lies outside the Cook's distance contour of 0.5, so there are no influential observations.
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 形;喇叭形 | 加 ;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,并能说出补救( 或变换)
- 能区分 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 推断 + 哑变量离群点
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%.
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]
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) | vs ;F = 31.64;;p = 5.715e-06 | p < 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,,p = 0.340 | p > 0.05 → do not reject ,no evidence that obs 6 is an outlier。t 值 = rstudent(m_log)[6](第 14 章) |
22.2 2023 Q2 [15 分]:regsubsets + PRESS + F 检验 + 预测区间
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.
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)
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(>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) | vs 至少一个 ≠ 0;F = 20.51;;p = 7.294e-08 → reject,模型比只有截距的好 |
| (e) | ;F = 9.668;;p = 0.000167 → reject:cyl、disp、hp 里至少一个在有 wt 的模型里有用 |
| (f) | (9.12, 26.53) |
anova(full) 是按顺序加变量的平方和:wt 先进,然后 cyl、disp、hp 依次加入。后三行的 Sum Sq 加起来 185.65 + 116.18 + 32.04 = 333.87,正好是嵌套 F 检验里的 "Sum of Sq 333.88"。所以 (e) 也可以直接从 anova 表手算:。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 章)。
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)
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.33320542021 Q1:(b) R² = 0.5024;(c) F = 30.29,,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,,p = 0.333 → 1% 水平不拒绝;(c) 是同一个检验, = 0.9841,p 值相同,命令 2*pt(-abs(rstudent(m21)[25]), df = 29)。
22.4 2021 Q3 [10 分]:MLR 的 F 检验家族 + 预测区间
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)
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,,p = 8.9e-09 → reject。(b) wt vs 全模型:F = 8.019,,p = 0.00056 → reject。(c) wt vs wt + disp:F = 0.791,,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)
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 . 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
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)[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 图接近直线 → 更合适。预测:(log 单位; 是自然对数)。 |
| ii b) | vs :至少一个 ≠ 0。F = 167.2 ~ ,p = 6.2e-16 < 0.05 → reject,比只有截距的模型好。 |
| ii c) | (在有 log(Age) 的模型里)vs 。看 anova 表的 Bidders 那一行(它就是在 log(Age) 之后加入 Bidders):F = 112.59 ~ ,p = 3.9e-11 → reject,Bidders 有用。也等于 summary 里 。 |
| ii d) | :第 20 个观测不是离群点(均值漂移 )。统计量 (n = 30,p = 3)。 qt(0.975, 26) = 2.0555 → reject at 5%(p ≈ 0.033),第 20 个观测是 unusual。 |
22.6 Möbius 下拉选项怎么选
真题里 "Null and alternative hypothesis" 和 "Null distribution" 是下拉列表(Select from the list)。你要能一眼认出正确选项:
| 检验 | H0 | Null distribution |
|---|---|---|
| SLR 的 F 检验 | ||
| overall F(k 个预测变量) | ||
| 嵌套 F(去掉 q 个变量) | 这 q 个系数都 = 0 | |
| partial t | ||
| 外学生化残差 / 哑变量 | (原模型的 p) |
- 2023 Q1、Q2 和 2021 Q1–Q3 能在不看答案的情况下 40 分钟内全部做完
- 每个 F/t 检验都能写出 H0、统计量、分布(带自由度)、p 值、结论五件套
- CI 还是 PI、置信水平多少、newdata 填原值还是 log 值,做完每题都核对一遍
第 26 章 · 2023 T3 期末完整解答(4 题 × 15 分)
卷子结构: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 章,本章会先补 |
| Q4 | Cook's D、DFFITS 的证明 | ❌ 新内容 | 第 15 章,本章会先补 |
26.1 Q1 [15 分]:log 变换 + SLR 推断 + 用哑变量检验离群点
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 against the alternative in the mean shift outlier model with , 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。
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考什么:会画诊断图,并能说出哪个假设被违反、在哪张图上看到的(读图方法见第 25 章)。
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:
- Residuals vs Fitted:红线先下后上,是一个浅 U 形:两头残差偏正、中间偏负 ⇒ 线性关系不完全成立。
- Scale-Location:红线从左到右明显上升;左上图里拟合值大的地方点也散得更开 ⇒ 方差随拟合值变大,等方差假设不成立。
- Normal Q-Q 大致在线上,Residuals vs Leverage 没有点越过 Cook's 0.5。
log 模型 log.mpg ~ log.disp:
这张图看起来反而更乱,原因只有一个:第 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 的虚线()⇒ 强影响点。
- 其他三张图里红线被 26 号一个点拉歪(左上图最右边那一段斜线就是它造成的)。
看除了 26 号以外的大部分点:残差在 0 上下随机,没有 U 形;Scale-Location 也没有原模型那种持续上升。为了确认,可以把 26 号去掉再画一次(题目没要求,只是帮你理解):
去掉 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 号拉乱就选原模型。
考什么:SLR 的 overall F 检验(Lab Test 学过)。"只有截距的模型"就是 ,也就是说 x 完全没用;所以"比它好吗"就是检验斜率是不是 0。
summary(m_log)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(下拉) | vs | 是 log.disp 的系数 |
| F statistic | 31.64 | "F-statistic: 31.64" |
| Null distribution(下拉) | "on 1 and 27 DF":分子 df = 预测变量个数 1,分母 df = n − 2 = 29 − 2 = 27 | |
| p-value | 5.715E-6 | "p-value: 5.715e-06",Möbius 接受科学计数法 |
| Conclusion | Since 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²:,p 值也和 log.disp 那一行的 t 检验相同。
坑:注意这题是 1% 水平,不是 5%。结论一定要写比较(p < 0.01)+ 拒绝 H0 + 用题目的语言说结论。
这就是斜率:模型 ,log.disp 增加 1,期望增加 。估计值在 summary 里 log.disp 那一行的 Estimate:−0.24151(题目说减少就填负数)。
confint(m_log, "log.disp", level = 0.99)0.5 % 99.5 % log.disp -0.3604691 -0.1225489
填 (−0.3605, −0.1225)。
手算核对(明白 R 在算什么):,其中 qt(0.995, 27) = 2.771。99% 双侧,每边留 0.5%,所以分位数是 0.995。
坑:level = 0.99 别忘了写,默认是 95%。
predict(m_log, newdata = data.frame(log.disp = log(240)),
interval = "confidence", level = 0.99)fit lwr upr 1 2.89347 2.769225 3.017715
填 (2.7692, 3.0177)。
三个要点,每一个都容易错:
- newdata 里要填 log(240),不是 240。模型的预测变量是 log.disp,所以给它的必须是 log 尺度的值(log(240) = 5.48)。填 240 会得到荒唐的结果。
- 问的是均值的区间 ⇒
interval = "confidence";如果问"一辆车"的 log.mpg,才用"prediction"。 level = 0.99。
结果是 log 尺度的区间(题目问的就是 mean log.mpg,所以不用再取 exp)。
怀疑第 6 个观测"不正常",做法是给它单独加一个截距:
- 对其他观测,dummy = 0,模型和原来一样。
- 对第 6 个观测,均值多了一个 :它可以"单独往上或往下挪"。
- 如果第 6 个观测本来就符合模型,就不需要挪,;如果它是离群点,。
所以"检验第 6 个观测是不是离群点"就变成了一个普通的 partial t 检验:检验 dummy 的系数是不是 0。
重要结论:这个 t 值正好等于原模型里第 6 个观测的外学生化残差 = rstudent(m_log)[6](2021 Q2(c) 专门考过这一点)。
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)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。
看 summary 里 dummy 那一行:
| 要写的 | 答案 | 说明 |
|---|---|---|
| Hypotheses | vs | 题目已经给了 |
| Test statistic | t = 0.972 | dummy 行的 t value |
| Null distribution | 新模型有 3 个参数,df = n − 3 = 29 − 3 = 26(也就是原模型的 n − p − 1 = 29 − 2 − 1);summary 里 "on 26 degrees of freedom" | |
| p-value | 0.34 | dummy 行的 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 检验 + 预测区间
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.
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,和列名同名也没关系- regsubsets(leaps 包):对每一个"变量个数"(1 个、2 个、3 个……)把所有组合都试一遍,挑出 RSS 最小(等价于 R² 最大)的那个。同样个数的变量,RSS 小的就是"最好"的。
- 为什么不能直接用 R² 比较不同个数的模型:加变量 R² 只会变大,永远选最大的模型。所以要用会"惩罚变量个数"的标准:
- adjusted R² :变量没用时会下降。越大越好。
- PRESS :每次去掉一个点,用剩下的点拟合,再去预测这个被去掉的点,把预测误差平方加起来。衡量的是预测新数据的能力。越小越好。第二个等号是捷径公式,R 里一行就能算。
library(leaps)
best <- regsubsets(mpg ~ wt + cyl + disp + hp, data = mpg)
summary(best)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 输出也复制进去。
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)))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"不写理由会扣分。
The PRESS statistic is the sum of squared prediction errors , 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.
full <- lm(mpg ~ wt + cyl + disp + hp, data = mpg)
summary(full)
anova(full) 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| 空格 | 填什么 |
|---|---|
| Hypotheses | vs : at least one (j = 1, …, 4) |
| F statistic | 20.51 |
| Null distribution | (分子 = 预测变量个数 4;分母 = n − p = 32 − 5 = 27) |
| p-value | 7.294E-8 |
| Conclusion | p-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。
考什么:比较两个嵌套模型(一个是另一个的一部分)。小模型(只有 wt)就是在大模型里令 cyl、disp、hp 的系数都为 0。
reduced <- lm(mpg ~ wt, data = mpg)
anova(reduced, full)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 ***
| 空格 | 填什么 |
|---|---|
| Hypotheses | (在含 wt 的模型里)vs : at least one of them |
| F statistic | 9.6683 |
| Null distribution | |
| p-value | 0.0001668 |
| Conclusion | p-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 的公式):
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。
predict(full, newdata = data.frame(wt = 3.6, cyl = 6, disp = 220, hp = 160),
interval = "prediction", level = 0.98)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 分]:无截距模型的加权最小二乘(答题本)
(a) [2 marks] Derive the so called weighted least squares estimator of β by minimizing the weighted version of the sum of squares with respect to β.
(b) [2 marks] Find the and for the estimator obtained in part (a).
(c) [3 marks] Find the maximum likelihood estimator (mle) of β if, in addition, the errors are normally distributed. Does the mle of β coincide with from part (a)?
(d) [3 marks] Multiply both sides of the equation (1) by and get . Denote , and . Show that the new model is the ordinary least squares regression model with no intercept, that is, the errors 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 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 , . Write down the model (2) in this case and comment on your findings.
普通最小二乘假设所有误差的方差都是 σ²。这里第 i 个误差的方差是 : 大 ⇒ 方差小 ⇒ 这个点更可靠。所以在平方和里给它更大的权重 ,让拟合更"听"可靠的点。 全是 1 时就回到普通最小二乘。
整道题只用到四个工具,Lab Test 都学过:① 求导令为 0 求最小值;② ;③ 不相关时 (交叉项是 0,展开方法见第 24 章 Q1 iv);④ 、。
模型里的 和 都是已知的常数,只有 (所以 )是随机的。由 (1):,, 之间互不相关。
对 β 求导(链式法则:括号对 β 求导得 )并令其为 0:
移项,β 提出来:
二阶导 (),所以这是最小值。
得分点:求导正确 1 分,解出 1 分。二阶导写一句更完整。
先把 写成"常数 × "的和:分母 是常数,记作 ,
期望(期望可以穿过常数和求和):
方差( 互不相关,交叉项为 0,只剩 ):
得分点:写出"uncorrelated"这个理由。 无偏。
思路:MLE = 让"观测到这组数据的概率(密度)"最大的参数值。步骤固定:写似然 → 取 log → 求导令为 0。
第 1 步:误差正态 + 不相关 ⇒ 独立(正态时不相关等价于独立)。所以 相互独立,似然是各自密度的乘积(正态密度见 formula sheet):
第 2 步:取 log(乘积变成求和,exp 消失):
第 3 步:前面有个负号,所以最大化 log L ⇔ 最小化 ,这正是 (a) 的问题。(也可以直接求导:,得到和 (a) 一样的方程。)
Yes, the mle of β coincides with .
得分点:似然写对 1 分;log 后指出与 的关系 1 分;结论 1 分。
, 是常数。三条逐一验证:
- ii) zero mean:。
- iii) common variance:,对所有 i 都一样。
- i) uncorrelated: 时 。
所以模型 (2) 的误差不相关、均值为 0、方差都是 σ²,正是普通(无截距)最小二乘模型的假设。
这一步的意义:乘以 正好把"方差不同"的问题消掉了:方差大的点( 小)被缩小,方差小的点被放大。
无截距模型 的普通最小二乘估计是 (就是 (a) 中 的情形:最小化 )。对模型 (2) 用这个公式,把 、 换成 、:
另一种写法:模型 (2) 的普通平方和 ,和 (a) 最小化的是同一个函数,所以解相同。
第 1 步:找权重。对比 ⇒ 。
第 2 步:代入 (a):
第 3 步:写出模型 (2)。(),所以 ,,:
Comment(可以直接写):After the transformation the model is an intercept-only model for the ratios with constant variance σ², so the least squares estimate of β is simply the sample mean of the ratios . Observations with large have large error variance and are down-weighted (weight ).
得分点: 1 分; 的表达式 1 分;模型 (2) 和评论 1 分。
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)formula lm_weights ols_on_new mean_ratio 2.077146 2.077146 2.077146 2.077146
四种算法完全一致。
26.4 Q4 [15 分]:Cook's D 和 DFFITS 的捷径公式(答题本)
PART I. Recall that the Cook's distance for the ith observation is the influence measure given by (a) [2 marks] Use the definition of given in lectures to explain in words what does represent. What does the Cook's distance measure?
In part (b) below, you can make use of the following result (you are not asked to prove this): where is the ith row of design matrix X, is the ith raw residual and is the ith leverage.
(b) [4 marks] Show that the Cook's distance , defined in (1), can be computed using the following formula , where is the ith internally studentized residual.
PART II. Recall that the ith DFFITS value is defined as (c) [2 marks] Use the definition of given in lectures to explain in words what does the numerator in (3), represent.
(d) [1 mark] Explain in words why we can express and as and ?
(e) [4 marks] Show that and hence compute and . In your answer, you can use the result (2).
(f) [2 marks] Show that the influence measure , defined in (3), can be computed using the following formula , where is the ith externally studentized residual.
| 符号 | 意思 | 公式 |
|---|---|---|
| 用全部 n 个点得到的最小二乘估计 | ||
| 去掉第 i 个点后重新拟合得到的估计 | 题目给的 (2) | |
| X 的第 i 行(第 i 个点的预测变量,含开头的 1) | 1 × p 行向量; 是 p × 1 列向量 | |
| 第 i 个普通残差 | ||
| 第 i 个杠杆值(帽子矩阵 H 的对角元) | (一个数) | |
内学生化残差(rstandard) | ||
外学生化残差(rstudent) | , 是去掉第 i 点后的 σ 估计 |
证明里反复用的三条矩阵规则:① ;② 是对称矩阵,转置不变;③ 数(1×1)可以随便提到前面。formula sheet 上有 、、、DFFITS 的定义,不用背定义,要会的是推导。
is the least squares estimate of β based on all n observations, and is the least squares estimate obtained by fitting the model without the i-th observation. So is the change in the estimated regression coefficients caused by deleting the i-th observation.
Cook's distance measures the overall influence of the i-th observation: it is a scaled (by ) squared distance between and , i.e. how much all the estimated coefficients (equivalently, all the fitted values, since ) change when the i-th observation is deleted. A large (e.g. ) indicates an influential observation.
中文要点: = 删掉第 i 点后系数变了多少; = 这个变化"有多大"(标准化后的长度平方)。各 1 分。
第 1 步:由 (2) 得到 (移项):
第 2 步:写出它的转置。、 是数,转置不变;(规则 ① ②):
第 3 步:代入 (1) 的分子,数提到前面,中间的 消掉:
第 4 步:除以 ,凑出 。把 拆成两个 ,一个给 ,一个留下:
因为 ,平方得 。∎
得分点:第 1 步 1 分,第 3 步(消掉中间、认出 )2 分,第 4 步 1 分。第一行先写出 (1) 和 (2),就算后面卡住也有分。
is the fitted value for the i-th observation from the model fitted to all n observations. is the predicted value at the i-th observation's predictor values from the model fitted without the i-th observation. So 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.
A fitted/predicted value is obtained by plugging the predictor values of the i-th observation, (the i-th row of X), into the estimated regression equation. Using all the data the estimated coefficients are , so ; using the data without the i-th observation the estimated coefficients are , and we evaluate that fitted equation at the same , so .
证明:由 (d) 和 (2):
求期望和方差要用残差的两个性质(第 14 章;如果不记得,下面是推导):残差向量 ,,,而 、 对称且 :
取第 i 个分量:,。
期望( 只由 X 决定,是常数):
方差(常数提出来要平方):
得分点:证明 2 分,期望 1 分,方差 1 分。最容易丢分的是方差里忘了平方。
把 (e) 代入定义 (3),然后把分母拆开凑出 :
用两个拆分:,:
就算 (e) 没证出来,这一问也可以直接用 (e) 的结论,照样拿满分。
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])D_def D_short 0.2053734 0.2053734 diff_def diff_short 1.368005 1.368005 DFFITS_short DFFITS_R 0.8288662 0.8288662
用定义(真的删掉一个点重新拟合)和用捷径公式算出来完全相同。
- Q1:log 模型更好,但要指出第 26 辆车是强影响点;F = 31.64 ~ ;(e) newdata 填 log(240);dummy 的 t = 0.972 ~ ,p = 0.34,不拒绝
- Q2:1 个变量最优是 cyl;PRESS 最小、adjusted R² 最大都是 wt + cyl + disp;嵌套 F = 9.668 ~ ;98% prediction 区间 (9.12, 26.53)
- Q3:,;MLE = ;(f) = 的平均
- Q4:每问第一行先写定义;(b) 的关键是中间的 ;(e) 要用
- 限时练习:Q1 + Q2 共 45 分钟(R 题),Q3 + Q4 共 50 分钟(手写),留 25 分钟检查
第 27 章 · 2021 T3 期末完整解答(6 题:3 道 R + 3 道证明)
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 章,本章会先补 |
| Q3 | overall F、嵌套 F、预测区间 | ✅ 学过 | 第 6、7 章 |
| Q4 | 矩阵形式的 b 的期望、方差、 | 学过一部分 | 第 5、11 章,本章会先补 |
| Q5 | 无截距 OLS、WLS、MLE | ❌ WLS 是新内容 | 第 17 章;和 2023 Q3 几乎相同 |
| Q6 | 影响点、DFFITS | ❌ 新内容 | 第 15 章;和 2023 Q4 Part II 几乎相同 |
27.1 Q1 [10 分]:log 变换 + SLR 推断
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.).
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) # 应该是 32m_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:
- Residuals vs Fitted:明显的 U 形(两头残差为正,中间为负)⇒ 线性假设不成立。
- Scale-Location:红线在拟合值大于 20 以后明显上升 ⇒ 方差随拟合值变大。
- Normal Q-Q:两端偏离直线(左端变平、右端在线下方,轻尾形状)⇒ 正态性也值得怀疑。
log 模型 log.mpg ~ log.disp:
和 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.
summary(m21)
confint(m21, "log.disp", level = 0.97)
predict(m21, newdata = data.frame(log.disp = log(290)),
interval = "confidence", level = 0.99)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] | vs ;F = 30.29;;p = 5.617E-6 | summary 最后一行。分母 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):,qt(0.985, 30) = 2.278,得 (−0.3894, −0.1614)。
27.2 Q2 [10 分]:用哑变量检验第 25 个观测
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.
哑变量做法:给第 25 个观测单独加一个"挪动量" :
如果第 25 个观测符合模型,就不需要挪,。所以检验"是不是离群点"= 检验 dummy 的系数是否为 0 = 一个普通的 partial t 检验。
外学生化残差(Lab Test 学过):,R 里是 rstudent(model)。如果第 i 个观测不是离群点,(p 是原模型的参数个数)。
关键定理(讲义里证明过):上面 partial t 检验的 t 统计量正好等于 ,自由度也相同(新模型有 p + 1 个参数,残差 df = n − p − 1)。所以两种做法是同一个检验。
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)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整个输出复制进答题框。
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、、p = 0.333、结论。用临界值也行:qt(0.995, 29) = 2.756,|0.984| < 2.756。
t25 <- rstudent(m21)[25]; t25 # 原模型(没有 dummy)的外学生化残差
2 * pt(-abs(t25), df = 32 - 2 - 1) # 双侧 p 值,df = n - p - 1 = 29 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 = 0.9841, which is exactly the t statistic of the dummy variable in part (b). Under H0 (the 25th observation is not an outlier) , 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))).
得分点:说"是同一个"+ 的值 + p 值 + R 命令,各 1 分。
坑:① 用的是原模型(没有 dummy)的 rstudent;② df 是 n − p − 1 = 29,不是 30;③ 双侧检验要乘 2,而且用 -abs(...) 保证取的是尾部概率。
27.3 Q3 [10 分]:多元回归的 F 检验家族 + 预测区间
(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.
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) 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.18vs : at least one ;F = 25.21;;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.
m_wt <- lm(mpg ~ wt, data = mpg)
anova(m_wt, full)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 ***
vs : at least one of them ;F = 8.0194;;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.
手算核对:。也等于 anova(full) 里 cyl、disp、hp 三行 Sum Sq 之和 166.84 + 39.80 + 14.09 = 220.73 除以 3、再除以 9.18。
anova(m_wt, lm(mpg ~ wt + disp, data = mpg))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
(在只含 wt 和 disp 的模型里)vs ;F = 0.7911;;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 不显著。同一个变量有没有用,取决于模型里已经有谁,这就是为什么检验时一定要说清楚"在哪个模型里"。
predict(full, newdata = data.frame(wt = 3.8, cyl = 6, disp = 220, hp = 160),
interval = "prediction", level = 0.92)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 分]:用 证明无偏性(手写)
(a) [2 marks] Show that we can write b in the form , where . Using this form, show that 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 .)
(c) [4 marks] Using part (a), show that we can write the residual sum of squares in the form , 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 is unbiased. (Hint: use the formula for .)
- "uncorrelated with variance σ²" 写成矩阵:,(对角线是方差 σ²,非对角线是协方差 0)。
- 常数矩阵可以穿过期望:,。
- 转置规则 ; 对称。
- (p × p 单位矩阵),这是全题最常用的一步。
- (formula sheet 有)。
- 迹的性质:,,(乘法顺序可以"转一圈")。
把 代入 ,展开:
取期望(β、S 都是常数,):
所以 b 是 β 的无偏估计。各 1 分。
按提示的定义,,所以 :
每一步的理由:(转置规则);S 是常数矩阵,可以提到期望外面; 因为 。
(可以再化简一步,加分),所以 ,和讲义的结果一致。题目要求"in terms of σ² and S",所以写到 就已经满分。
第 1 步:残差向量。用 (a) 的 :
第 2 步:平方和:
第 3 步:证明 。
- 对称:,所以 。
- 幂等:。
所以 。∎
( 就是帽子矩阵 H,所以这一步其实是" 对称且幂等"。)
第 1 步:套公式,,,:
第 2 步:算迹。注意 I 是 n × n,迹是 n:
中间一步用 ,取 、:把 X 从最前面"转"到最后面,得到 p × p 的单位矩阵,迹是 p。
第 3 步:结论。由 (c):
所以 是 σ² 的无偏估计。
得分点:套公式并写出 Var(ε) = σ²I(2 分);迹 = n − p 并说明用了 tr(AB) = tr(BA)(2 分);结论(1 分)。
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[1] 0.9926575 2.0004237 -0.9987113 3.9930384
27.5 Q5 [15 分]:无截距模型的 OLS 和 WLS(手写)
(a) [3 marks] Show that the least squares estimate of β is given by . Show that and .
Suppose now that in the model (1), the errors are uncorrelated with zero mean, but the error variance is not constant and it is given by for some positive weights , i = 1, …, n.
(b) [2 marks] Find the weighted least squares estimate of β by minimizing with respect to β.
(c) [3 marks] Find the maximum likelihood estimator (mle) of β if, in addition, the errors are normally distributed. Does the mle of β coincide with from part (b)?
(d) [2 marks] Find and for the estimate obtained in part (b).
(e) [5 marks] Multiply both sides of the equation (1) by and get . Denote , and . Show that the errors are uncorrelated with zero mean and common variance σ², therefore , 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 from part (b).
这道题和 2023 Q3 几乎一模一样(权重叫 而不是 ,小问顺序不同)。区别是:2021 多了 (a) 普通 OLS;2023 多了 (f) 特例。下面把每一问写完整,详细的每一步解释见第 26 章 Q3。
推导:,
二阶导 ,是最小值。
期望:,
方差: 互不相关,,把 b 看成 ,:
二阶导 。
正态 + 不相关 ⇒ 独立,:
const 不含 β。最大化 log L ⇔ 最小化 ,所以 。Yes, they coincide.(似然的完整写法见第 26 章 Q3 (c)。)
方差一步用了 不相关。和 (a) 比: 时就回到 OLS 的结果。
误差满足 OLS 假设( 是常数):
- ;
- ,对所有 i 相同;
- :。
所以 (2) 是普通无截距模型。用 (a) 的公式(把 x、y 换成新变量):
得分点:三条性质各 1 分;估计 1 分;"等于 "1 分。注意 (a) 的结论在这里直接拿来用,这就是 (a) 先让你推 OLS 的原因。
27.6 Q6 [15 分]:影响点和 DFFITS
(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 (1). Use the definitions given in lectures to explain in words what does the numerator in (1) represent. Copy the second plot of Figure 1 in your answer book (draw it by hand) and show on the plot the change , 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 for the observation identified as influential in part (a) using the following formula . Based on this value of 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 (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): (2), where denotes the least squares estimate of β obtained by fitting the model without the i-th observation, is the ith row of design matrix X, is the ith raw residual and is the ith leverage.
(d) [1 mark] Explain in words why we can express and as and ?
(e) [5 marks] Show that and hence find and .
(f) [2 marks] Show that , defined in (1), is equal to , where is the ith externally studentized residual.
Figure 1(原卷截图):
题目给的输出(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
怎么读第一张图(读法见第 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",只说一张图会丢分。
is the fitted value at from the model fitted to all the data, and is the predicted value at from the model fitted without the i-th observation. So is the change in the fitted value at the i-th point caused by deleting the i-th observation.
怎么画:在答题本上照着画出散点图和两条线。在 14 号点的横坐标 处画一条竖线段,从黑线上的点(,约 3.3)连到红线上的点(,约 4.1),标上 ""。这段长度约 −0.8(黑线在红线下面,所以是负的)。
常见错误:画成从点到线的距离(那是残差),或者画在别的 x 处。必须是同一个 x = x₁₄ 处、两条线之间的竖直距离。
从输出里读 14 号:,。
|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.
(有的教材用 当界限,结论一样。讲义用的是 2。)
计算器步骤:先算 0.23573 ÷ 0.76427 = 0.30844,开方 0.55537,再乘 −4.58391。
(d) A fitted value is obtained by plugging the predictor values of the i-th observation, (the i-th row of X), into the estimated regression equation. With all the data the coefficient estimate is b, so ; with the i-th observation deleted the estimate is , evaluated at the same , so .
(e) 证明:
由 :,,所以 ,。于是
2021 这一问是 5 分(2023 是 4 分),所以 、 的来历一定要写出来。
(f)
每一步的详细解释见第 26 章 Q4 (d)(e)(f)。
- Q1:(b) 填 R² = 0.5024;F = 30.29 ~ ;(e) 是 97%;(f) newdata 填 log(290)
- Q2:dummy 的 t = 0.984 ~ ,p = 0.333;和 rstudent 是同一个检验;命令
2*pt(-abs(rstudent(m21)[25]), 29) - Q3:(a) F = 25.21 ~ ;(b) F = 8.019 ~ ;(c) 要单独拟合 wt + disp,F = 0.791 ~ ,不拒绝;(d) 92% 预测区间
- Q4: ⇒ 无偏;; 对称幂等;
- Q5:OLS ;WLS ;MLE = WLS;变换后 OLS = WLS
- Q6:14 号是影响点(两张图都要说);DFFITS₁₄ = −2.55,|·| > 2;(e) 的期望 0、方差
第 24 章 · 2020 T3 期末完整解答(4 题 × 15 分)
这份卷子 4 题 × 15 分:Q1、Q3 是 Week 1–5 的推导(中心化 SLR、),Q2 是"只给输出、不用 R"的分析题,Q4 是影响点(Cook's D)。老师说今年重点看 2020、2021、2023 三份,这份要能独立做完。
原卷:
past_final_exams/MATH2831_2020.pdf 配套脚本:R/ch24_2020_final.R(只用来核对数字,考试时这些题不用 R)。| 题 | 知识点 | Lab Test 学过? | 详细讲解 |
|---|---|---|---|
| Q1 | 最小二乘求导、 和 的线性性质、协方差的拆分、 的定义 | ✅ 大部分学过;协方差拆分和"联合正态 ⇒ 独立"本章会讲 | 第 1、3、5 章 |
| Q2 | 读诊断图、log 变换后预测、overall F、序贯 F、外学生化残差 | F 检验学过;诊断图、变换是新内容 | 第 7、10、16、25 章 |
| Q3 | 、帽子矩阵、迹、 | 部分学过 | 第 5、8、11 章,本章逐步写出 |
| Q4 | 杠杆、内学生化残差、Cook's D | 杠杆、残差学过;Cook's D 是新内容 | 第 15 章;符号表见第 26 章 Q4 |
24.1 Q1:中心化的简单线性回归 [15 分]
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 , where and . Clearly identify design matrix X and vector of responses y using the given data.
ii) [4 marks] Derive the least squares estimators and of the parameters and in model (1) by minimizing with respect to and . You must show your work.
iii) [3 marks] Show that and derived in part ii) are unbiased estimators of and , respectively. You must show your work.
iv) [4 marks] Prove that and derived in part ii) are uncorrelated. Then show that the covariance matrix of is given by .
v) [2 marks] Assume that errors in (1) are independent and identically distributed and follow distribution. Find the distribution of the sum You must give reasons for your answer.
整道题的关键事实:中心化之后 。后面每一问几乎都靠这一行化简,答题时第一次用到要写出来。另外记号 ,(formula sheet 第 1 页有)。
,所以中心化后的 x 是 。设计矩阵第一列全是 1(对应 ),第二列是 (对应 ):
常见错误:第二列直接写 10, 8, 12(没中心化)。题目问的是模型 (1) 的 X,第二列必须是 。
对 分别求偏导,令其为 0(链式法则:括号里对 求导是 −1,对 求导是 )。
对 :
对 :
最后一步用到 ,因为两者相差 。
(可选)说明这是最小值:二阶导矩阵是 ,正定,所以是最小值。
和普通 SLR 比:斜率完全相同;截距变成了 ,因为中心化后 x = 时模型的均值就是 。用 i) 的数据:,,,(题目没要求算,脚本 24.1 有核对)。
x 是固定的(不是随机变量),所以 。
得分点:写出 这种"y 的线性组合"形式再取期望;直接写 不展开会丢分。
把两个估计都写成 y 的线性组合:,;,。
互不相关,且 ,所以 :
第二个等号是怎么来的(最容易卡住的一步):协方差像乘法分配律一样可以拆开,常数可以提出来:,。以 n = 2 为例,四项全部写出来:
下标不同的交叉项是 0(误差不相关,而 只比 多一个常数),下标相同的是 ,所以只剩 。一般的 n 同理:。用 i) 的数据核对:,,。
为什么能写成 :,后一项是 0,所以 消失了。如果不先消掉 ,每一项都含同一个 ,各项之间不独立,就没法直接相加方差。
所以 、 不相关。再求两个方差:
放进矩阵(对角线是方差,非对角线是协方差)就是题目给的 。
另一种写法(矩阵):,所以 。用这种写法要先说明 的来历(,)。
- iid 正态 ⇒ y 是多元正态;、 都是 y 的线性组合 ⇒ 联合正态。
- 由 iii) iv):,,标准化:
- 联合正态 + 不相关 ⇒ 独立(这一步只对正态成立,必须写出"联合正态")。
为什么:二元标准正态的密度里,只有相关系数 ρ 把两个变量连在一起;ρ = 0 时密度拆成两个一元密度的乘积 ,这就是独立的定义。
为什么一定要"联合":反例 ,W 以各 1/2 概率取 ±1 且与 X 独立,。Y 也是 N(0, 1),,但 ,显然不独立,因为 (X, Y) 不是联合正态。
为什么 是联合正态:它们的任意线性组合 仍是独立正态 的线性组合,所以是正态,这正是联合正态的定义。 - 题目的和 ,两个独立标准正态的平方和 ⇒ 。
脚本 24.2 用 10000 次模拟验证:这个和的均值 ≈ 2、方差 ≈ 4,正是 的均值和方差。
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
xc
[1,] 1 0
[2,] 1 -2
[3,] 1 2
xc
3 0
xc 0 8
[,1]
10.66667
xc 4.75000是对角矩阵 diag(3, 8) = diag(n, ),这就是 iv) 里 、 不相关的原因。
24.2 Q2:拍卖钟表价格,只看输出作答 [15 分]
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 . 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 的诊断图
四张图逐张看(方法见第 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 的诊断图
题目给的数值输出(节选):
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
看图(约 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 单位,写 7.298 即可)。
常见错误:把 177 直接代进去(模型里是 log(Age)),或者对 Bidders 也取 log(Bidders 没有变换)。
- 假设:(log(Age) 和 Bidders 的系数都为 0,即只有截距的模型就够了) vs :、 至少一个不为 0。
- 统计量:F = 167.2,在 下 ~ (分子 df = 预测变量个数 2,分母 df = 残差 df = 30 − 3 = 27)。
- 结论:p = 6.189e-16 < 0.05 ⇒ 拒绝 。这个模型显著好于只有截距的模型。(或者比临界值:,167.2 远大于它。)
数字从 summary 最后一行 "F-statistic: 167.2 on 2 and 27 DF" 直接读。
- 假设:在含有 log(Age) 的模型里, vs 。等价于比较"只有 log(Age)"的简化模型和"log(Age) + Bidders"的完整模型。
- 统计量:看 anova 表的 Bidders 那一行。anova 是按顺序加变量的:log(Age) 先进,Bidders 后进,所以这一行正是"已有 log(Age) 时再加 Bidders"的 F 检验(第 7 章的 sequential F):
- 结论:p = 3.919e-11 < 0.05 ⇒ 拒绝 。即使模型里已经有 log(Age),Bidders 仍然和 log(Price) 显著相关,应该保留。
检查:只加一个变量时 F = 。summary 里 Bidders 的 t = 10.611,,和 anova 一致。所以用 partial t 检验作答(t = 10.611 ~ )也对。
常见错误:用 log(Age) 那一行(221.74)。那一行检验的是"在只有截距的模型里加 log(Age)",不是本题问的。
- 假设::第 20 个观测不是离群点(均值漂移模型里 ,见第 14 章) vs :它是离群点()。
- 统计量:外学生化残差 ,在 下 ~ 。这里 n = 30,p = 3(截距 + 2 个预测变量),所以自由度 = 30 − 3 − 1 = 26。
- 临界值:双侧 5% 用 qt(0.975, 26) = 2.0555。
- 结论: ⇒ 在 5% 水平拒绝 (p ≈ 0.033),第 20 个观测是 unusual 的(离群点)。
这题的陷阱:题目同时给了 df = 26 和 27、0.95 和 0.975 四个分位数。
- df 用 26 不用 27:算 时要用去掉第 i 个观测后的 ,少了一个观测,所以比模型残差 df 少 1。
- 用 0.975 不用 0.95:问的是"是否 unusual",偏大偏小都算,是双侧检验。
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)[1] 7.298078 [1] 1477.458 [1] 3.354131 [1] 4.210008 [1] 112.5933 [1] 0.03310697
24.3 Q3: [15 分]
i) [2 marks] The ordinary simple linear regression model can be written in the form of the general linear model for suitable design matrix X. What is X? What is ?
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 .
iii) [3 marks] Hence show that .
iv) [2 marks] Find 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 . You must show your work. (Hint: use the formula for .)
的 (j, k) 元素 = X 第 j 列和第 k 列的内积:1·1 求和 = n,1· 求和 = , 求和 = 。
关键技巧:全 1 矩阵可以写成 ,其中 是 n × 1 的全 1 向量。于是
而 = X 每一列的和 = ,所以
不想用 也可以直接乘: 的每一行都是 ,再左乘 即可。
先算 :
(也可以用 :H 把 X 的列投影到 X 的列空间,投影后不变。)再用 i)、ii):
最后一步:。这个恒等式要写出来,是得分点。
迹是线性的:。
- (用 )。
- (对角线上 n 个 1)。
用到的公式(formula sheet 最后一页):若 ,,则 。
这里 ,,(误差不相关、方差 σ²)。
第一项(用 iv):
第二项(用 iii):
合起来:。∎
这个结果说明什么(可以加一句,显得理解了): 成立时 ,所以 F = SSreg / 应该在 1 附近; 时分子期望更大,F 偏大。这正是 SLR 的 F 检验"F 大就拒绝"的理由。
五分怎么给:写出公式和 A、μ、V(2 分);第一项(1 分);第二项(2 分)。一定要写 Var(y) = σ²I,很多人漏掉。
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))
xq
0 0.00000
xq 0 24.14372
[1] 24.14372
[1] 1
simulated theory
105.2031 105.574924.4 Q4:影响点和 Cook's D [15 分]
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 using the formula given in lectures and the following R-output (hatvalues(model) and rstandard(model) for 13 observations).
Consider now the full rank general linear model (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 (2). Use the definition of to explain in words what does represent. What does Cook's distance () 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): (3), where the ith row of design matrix X, is the ith raw residual and is the ith leverage, which can be written as . Show that Di is equal to , where is the ith internally studentized residual. (Hint: obtain the expression for from (3) and then substitute into (2).)
Figure 3:y ~ x1 + x2 的 Cook's distance 图和 Residuals vs Leverage 图
> 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
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 为什么不是,显示你懂"高杠杆 ≠ 影响点"。
p = 参数个数 = 截距 + x1 + x2 = 3(不是 2!)。题目给的 rstandard 就是内学生化残差 ,直接代:
两个都 > 1,和图一致,确认是影响点。(讲义另一条标准:和 比,两个也都更大。)
常见错误:p 用 2;把 当成 (rstudent);忘了平方后负号消失。
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)[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
is the least squares estimate of β obtained by fitting the model with the ith observation deleted. So 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 measures the overall influence of the ith observation on the estimated coefficients: it is the squared distance between b and , measured in the metric and scaled by . Since , it equivalently measures how much all n fitted values change when observation i is deleted. A large (e.g. greater than 1) indicates an influential observation.
中文要点: = 删掉第 i 个点后系数估计变了多少; = 这个变化的"标准化长度的平方",也等于所有拟合值一起变了多少。 大 ⇒ 第 i 个点单独就能明显改变拟合结果 ⇒ 影响点。
第 1 步:从 (3) 得到 (移项):
第 2 步:代入 (2) 的分子。 和 都是数,可以提到外面;转置时 对称,所以 :
第 3 步:除以 ,凑出 。内学生化残差 ,所以 。把分母里的两个 拆开,一个给 ,一个留下:
结论的含义(加一句加分): 由两部分相乘:(残差大不大)和 (杠杆高不高)。两者都大才会是影响点,这正是 i) 里 11、13 是影响点而 12 不是的原因。
6 分怎么给:写出 (1 分);代入并正确转置(2 分);用 的定义化简(1 分);用 的定义凑出结果(2 分)。
- Q1:中心化后 是所有化简的关键;、;不相关 + 联合正态 ⇒ 独立 ⇒
- Q2:Residuals vs Fitted 看线性,Q-Q 看正态,Scale-Location 看方差,Residuals vs Leverage 看影响点;预测时代 log(177);Bidders 的检验看 anova 的第二行;外学生化残差 df = n − p − 1
- Q3:;;;,写出
- Q4:p 是参数个数(含截距);Cook's D > 1 是影响点;能默写 iv) 的三步证明
- 限时练习:不看答案,Q1 + Q3 各 20 分钟,Q2 + Q4 各 15 分钟
第 28 章 · 2019 T3 期末完整解答(4 题 × 15 分,纸笔考试)
今年是机房 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、 | ✅ 学过 | 第 3、4 章 |
| Q1 (b)(c) | 随机向量的协方差矩阵、帽子矩阵、 | 部分学过 | 第 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 的方差估计 + 协方差矩阵(证明)
i) [3 marks] Show that .
ii) [3 marks] Hence or otherwise show that and . Hint: Use the fact that .
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 . Suppose A and B are n × n and p × p matrices respectively, show that .
c) [5 marks] Consider the multiple linear regression model , where X is an n × p full rank design matrix, β is a p × 1 vector of parameters and , where I is an n × n identity matrix. The n × n hat matrix is denoted by .
i) [3 marks] Show that the covariance between and the least squares estimator of β, (1), is a matrix of zeros. Hint: Use the result in part b).
ii) [2 marks] Prove that the estimator of the error variance is an unbiased estimator of σ².
,,;,。
两个马上要用的等式:(由 的定义);(ANOVA 分解)。
第 1 步:把 代掉。,所以每个残差
第 2 步:平方再求和,用 :
第 3 步:用 :
两边除以 n − 2,得证。∎
第一部分:(由 i)),而 ,所以
(也可以直接算:,平方求和就是 。)
第二部分:关键是 。由 得 。用提示 、:
得分点: 这一步是核心(2 分)。 只和 x 有关,是常数,可以提到期望外面。2020 Q3 用矩阵方法证明了同一个结论(第 24 章)。
A、B 是常数矩阵,所以 ,。按定义:
每一步的理由:提出 A、B(分配律);;常数矩阵可以提到期望外面(左边的 A 和右边的 )。∎
注意:证明里没用到 A、B 是方阵,只要乘法尺寸对得上就成立。c) i) 里的 B 就是 p × n 的,结论照样能用。
两个都是同一个 y 的线性变换:(n × n),(p × n),Y = Z = y,所以 。由 b):
(转置:,因为 对称。)关键一步:
所以协方差 (n × p 的零矩阵)。∎
意义:残差和系数估计不相关;正态时就是独立,这正是 t 检验里分子 b 和分母 独立的原因。
用 (formula sheet),,,:
迹:()。所以 。∎
和 2021 Q4 (d) 是同一个结论,那里用 ε 写,这里用 y 写:用 y 时多了 那一项,要说明它是 0。
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)def short 3.503262 3.503262 simulated theory 83.14182 82.83362
28.2 Q2 [15 分]:汽车油耗,只看输出作答
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 vs or , 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(立方根)
第二组图:log(Mpg)
The model is , with X a fixed n × p full rank design matrix, and:
- Linearity: the mean response is a linear function of the parameters, , i.e. .
- Constant variance: for all i.
- Uncorrelated (independent) errors: for i ≠ j; together with 2, .
- Normality: are normally distributed (needed for t and F tests and intervals), so .
"Give details" 就是每条都写成公式。写全四条 2 分。
两组图逐张对比(读法见第 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.
- 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).
- Weighted least squares: if with known (or estimated) weights, minimise , giving with ; 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
先定好记号:模型 。所以 β₂ 是 weight,β₃ 是 displacement(按 summary 的行顺序)。
,即 77.79% of the variation in log(Mpg) is explained by the model.(用 Multiple R-squared,不是 adjusted。)
vs (其他预测变量都在模型里)。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.
公式 ,n − p = 398 − 4 = 394,题目给了 qt(0.975, 394) = 1.966003:
区间不包含 0,和 ii) 的结论一致。坑:题目还给了 qt(0.95, 396),那是单侧、df 也不对,是干扰项。
想清楚在比较哪两个模型:H0 成立时模型只剩 cylinders;所以是比较"只有 cylinders"和"全模型"。多出来的平方和就是 anova 表里 cylinders 之后加进来的 weight、displacement 两行(anova 是按顺序加变量的):
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.
为什么能这样拆:(序贯平方和可以相加)。分子 df = 2(检验 2 个系数),分母用全模型的 MSE。
就是检验 (displacement 最后加入)。anova 表最后一行(displacement 是最后进入的):F = 4.6487,p = 0.03168;也等于 summary 里 ,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 检验)。
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)[1] -0.0002945384 -0.0001902616 [1] 85.12398 [1] 4.64714 [1] 4.648336
28.3 Q3 [15 分]:广义线性模型的 MLE、BLUE 和 Gauss–Markov 定理
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 .
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: (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 be any other unbiased linear estimator. Note that when B = 0 we get . Then, show that .
矩阵求导(formula sheet 上有):对向量 β 求导,,(A 对称时 = 2Aβ)。和一元的 、 一个道理。
半正定:矩阵 M 叫半正定(记 M ≥ 0),如果对任意向量 c 都有 。"估计 1 的协方差矩阵 − 估计 2 的协方差矩阵 ≥ 0"的意思是:估计任何线性组合 时,估计 2 的方差都不比估计 1 大。
一个常用事实:任何 都是半正定的,因为 。
第 1 步:写似然。,ε ~ N(0, V),所以 。代入提示的密度,μ = Xβ,Σ = V:
第 2 步:取 log:
第 3 步:把二次型展开。 对称,而 是一个数,等于它的转置 ,两个交叉项合并:
第 4 步:对 β 求导令为 0(, 对称):
第 5 步:解出 β(X 满秩、V 正定 ⇒ 可逆):
这就是广义最小二乘(GLS)估计。二阶导 负定,所以是最大值。
得分点:似然 1 分;log 1 分;展开 1 分;求导 1 分;结果 1 分。
,代入 a):
(,两个 σ² 抵消。)
BLUE stands for Best Linear Unbiased Estimator. An estimator of β is:
- Linear if it is a linear function of the observations, for some fixed p × n matrix C;
- Unbiased if for all β;
- Best if, among all linear unbiased estimators, it has the smallest variance, in the sense that is positive semi-definite for any other linear unbiased ; equivalently for every vector c (in particular each has the smallest variance).
三个词各 1 分。BLUE 只需要 、,不需要正态(2014 Q6(c) 专门问过这一点)。
设 是任意一个线性无偏估计(B 是 p × n 常数矩阵)。
第 1 步:无偏 ⇒ BX = 0。
要对所有 β 都等于 β,必须 对所有 β 成立,所以 (因此也有 )。
第 2 步:算方差。记 ,。展开 的四项:
所以 ,这就是提示要你证的式子。
第 3 步:比较。(B = 0 的情形),所以
而 半正定:对任意 c,。因此 对所有 c 成立,特别地 。所以最小二乘估计 b 在所有线性无偏估计中方差最小,即 b 是 BLUE。∎(等号只在 B = 0 即 时成立。)
得分点:BX = 0(1 分);展开 并消掉交叉项(2 分); 半正定的论证 + 结论(2 分)。
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) # 直接数值最大化似然optim [1,] 0.4375022 0.4375898 [2,] 2.1354933 2.1353150
公式和数值最大化的结果一致(差别只是 optim 的数值误差)。
28.4 Q4 [15 分]:logistic 回归 + Mallows' Cp
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 and it links the mean response and the linear model through the equality . 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 , 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 . Let the proposed model contain only p predictors. Write for the vector of fitted values using the proposed model with p predictors. Show that . 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
y 只能是 0 或 1, 是概率,必须在 0 和 1 之间,所以不能直接写 。做法是对概率做一个变换:
左边叫 log-odds(odds = 成功概率 / 失败概率)。读系数的方法: = 预测变量 j 增加 1(或从基准类变成这一类)时 log-odds 的变化; = odds 变成原来的几倍(odds ratio)。
哑变量的基准类:输出里有 PClass2nd、PClass3rd、Sexmale,说明基准是 1st class 和 female(R 按字母顺序取第一个当基准)。
偏差检验(deviance):作用相当于线性模型里的 F 检验。Null deviance − Residual deviance 在 H0 下近似服从 ,自由度 = 两个 df 之差。
令 ,由 (η = Xβ)反解:
把 β 换成估计 b,逐个元素:
其中 exp 对向量 Xb 的每个元素分别作用。
1st class 和 female 都是基准类,所以 PClass2nd = PClass3rd = Sexmale = 0,只剩截距和 Age:
估计生存概率约 0.88。
其他条件相同时,男性的 log-odds 比女性多 ,所以
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.
:PClass2nd、PClass3rd、Age、Sexmale 四个系数全为 0;:至少一个不为 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 三个临界值,就是考你这一点。
提议的模型用 n × p 设计矩阵 ,帽子矩阵 ,拟合值 。不管真模型是什么,。
第 1 步:( 对称、幂等)。
第 2 步: 是这个矩阵的第 i 个对角元,所以 。
第 3 步:()。
意义:用的参数越多,拟合值的总方差越大。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.
- Q1:;;;
- Q2:log 模型更好(点名图);β₂ 是 weight;CI (−2.945e-4, −1.903e-4);F = 85.12 ~ ;v) 用 anova 最后一行 F = 4.65
- Q3:;BLUE 三个词;Gauss–Markov:BX = 0 ⇒
- Q4:概率 0.88;odds ratio 0.072;偏差检验 330.43 ~ ;
第 29 章 · 2014 S2 期末完整解答(7 题共 70 分,纸笔考试)
它的价值:题目短、基础,几乎全是 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 章 |
| Q2 | step() 向前选择、序贯 F 检验、嵌套 F | ✅ 学过 | 第 7、9 章 |
| Q3 | PRESS、Cp、adjusted R²、R² | ✅ 学过 | 第 9 章 |
| Q4 | 的证明、 的均值 | 公式学过,证明是新的 | 第 1、11 章,本章会先补 |
| Q5 | 无偏、 的均值方差、Var(Syy) | 部分学过 | 本章会先补 |
| Q6 | MLE、BLUE、Gauss–Markov | ❌ 新内容 | 第 28 章 Q3(同一题) |
| Q7 | SLR 的矩阵形式、Var(b₀)、Var(b₁)、Cov、杠杆公式 | ✅ 学过 | 第 5、8 章 |
29.1 Q1 [12 分]:读 SLR 输出(原油和汽油价格)
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-05a) [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 versus , 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 versus the one sided alternative ?
e) [3 marks] In the following, you may use the fact that for , and , . 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.
i) 截距 ,斜率 (Estimate 列)。
ii) 误差方差是 ,输出给的 "Residual standard error" 是 (标准差),要平方:。
坑:直接填 6.833 会丢分,那是标准差不是方差。
,即 91.92%。
i) F = 79.64("F-statistic: 79.64 on 1 and 7 DF"),在 H0 下服从 (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.
t = 8.924(crude 那一行)。等价是因为 SLR 里 :。
单侧 :p 值只算右尾 。输出给的 4.51e-05 是双侧的 ,t 分布对称,所以
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,会很大。
第 1 步:点预测:。
第 2 步:两个根号里的东西(formula sheet 上的公式),n = 9:
第 3 步:区间,,,:
- i) 预测区间(一个新的汽油价格,根号里多一个 1):。
- ii) 置信区间(平均汽油价格):。
预测区间比置信区间宽很多:它还要包括单个观测本身的随机误差 σ²。
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[1] 101.709 [1] 84.651 118.767 [1] 96.2273 107.1907
29.2 Q2 [10 分]:step() 向前选择的输出
>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 and . 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" 是当前模型;表里每一行是"再加一个变量"会怎样。
<none>那一行是"什么都不加",也就是当前模型本身。 - RSS:加了这个变量以后模型的残差平方和。Sum of Sq = 当前模型的 RSS − 加变量后的 RSS = 加这个变量让 RSS 减少了多少(额外平方和)。
- F value:序贯 F 检验 , 是加变量后模型的参数个数(含截距)。
- AIC 越小越好;R 每一步加 AIC 最小的那个,直到 <none> 最小为止。这里
k = 0.2表示 AIC 的惩罚项是 0.2 × 参数个数(默认是 2),惩罚很弱,所以 AIC 倾向于多加变量。核对:。
第 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 稍微变小就会加变量。
(δ) = 从只有截距的模型加入 weight 后 RSS 的减少量:
It is the extra (regression) sum of squares due to weight when weight is added to the intercept-only model, .
(γ) = 第三步 <none> 那一行的 RSS,也就是当前模型 rings ~ length + diameter 自己的 RSS。它在第二步已经出现过("+ data$diameter" 那一行的 RSS):
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。
n = 14。加 length 后模型有 2 个参数,分母 df = 14 − 2 = 12:
在 length + diameter 上再加 weight,模型有 4 个参数,分母 df = 14 − 4 = 10:
核对:用 R 算 pf(5.752, 1, 12, lower.tail = FALSE) = 0.0336,pf(0.0385, 1, 10, lower.tail = FALSE) = 0.848,和输出的 p 值一致。
坑:分母要用加变量后模型的 RSS 和 df,不是加之前的。
比较"只有 length"(RSS = 50.842)和"length + diameter + weight"(RSS = 46.223,4 个参数):。
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.
坑:题目给了 和 两个,正确的分母 df 是全模型的 n − 4 = 10。
29.3 Q3 [6 分]:PRESS、Cp、adjusted R²、R²
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.3854512a) [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.
- 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。)
可以。
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 , 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 分]:证明
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 .
b) [2 marks] Let be i.i.d. normal random variables with mean μ and variance σ². By using part a), show that , and deduce the value of the expectation of a random variable.
- 一个数(1 × 1 矩阵)的迹就是它自己:。
- ,所以 (把 从前面"转"到后面)。
- 迹和期望都是线性的,可以交换:。
- 再加一个协方差的老公式:,所以 (就是一元的 )。
每一步:一个数等于它的迹;;期望和迹交换、A 是常数提出来;;迹的线性;再用一次 , 是一个数。∎
令 ,i.i.d. ⇒ (全是 μ 的向量),。取 A = I,:
推论: 的定义是 k 个独立 N(0, 1) 的平方和,即 μ = 0、σ² = 1,所以 。
29.5 Q5 [10 分]: 无偏、 的矩、Var(Syy)
a) [2 marks] Show that .
b) [3 marks] By using part a), show that is an unbiased estimator of σ².
c) [3 marks] Let 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 .
⇒ 。平方求和:
用了 。除以 n − 2 得证。
第 1 步:。,,所以
平方后取期望:交叉项期望为 0(),而
(,因为 只和自己相关)。求和:
第 2 步: 。
第 3 步:相减:
矩母函数 。用 的密度(formula sheet 上有):
换元 ,积分变成 (最后一步是 的密度积分为 1)。所以
求导:,。代入 t = 0:
不用矩母函数的快捷方法(今年更可能用到):,Z ~ N(0, 1), ⇒ ;独立的方差相加 ⇒ 。
题目想要的答案(用 c 的结果,在 也就是 y 和 x 无关时):这时 是 i.i.d. ,,所以
一般情形( 任意,完整答案):,正态误差下 和残差独立(2019 Q1 c i),所以两部分独立,方差相加。
- ⇒ 。
- ,其中 ,。,,所以 ,。
时回到 。脚本 29.4 用模拟核对了这个公式(模拟 313.2,理论 312.6)。
29.6 Q6 [7 分]:MLE、BLUE、Gauss–Markov
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 β: (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,这里写出完整但紧凑的答案。
:
(i) Best Linear Unbiased Estimator: among all estimators that are linear in y () and unbiased ( for all β), it has the smallest variance ( is positive semi-definite).
(ii) No. The Gauss–Markov theorem only uses and (zero mean, uncorrelated errors with constant variance); normality is not required.
任意线性无偏估计写成 。无偏: 对所有 β ⇒ 。于是
(交叉项含 或 )。所以 ,对任意 c 有 ,半正定 ⇒ b 方差最小,是 BLUE。∎
29.7 Q7 [20 分]:SLR 的矩阵形式、方差公式、杠杆公式
a) [4 marks] The simple linear regression model can be written in the form of the general linear model 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 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 .
d) [8 marks] In the general linear model, the leverages are defined as the diagonal elements of the matrix . 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 , where x̄ is the mean of the predictors, n is the sample size and .
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 分。
第 1 步:写成 y 的线性组合。,(因为 );。
第 2 步:三个基本量( 不相关、方差 σ²,交叉项为 0):
第 3 步:( 是常数):
和 2020 Q1 对照:那道题把 x 中心化了( 变成 0),所以协方差是 0;这里没中心化,协方差是 。
,a = 1、b = x₀:
这正是 formula sheet 上置信区间根号里的东西。x₀ 离 越远,方差越大。
第 1 步:(两列的内积,见第 24 章的表格算法):
第 2 步:求逆。2 × 2 矩阵 。行列式:
(用了 和 。)
第 3 步:, 是 X 的第 i 行:
第 4 步:配方:,所以
另一种思路(更快):,所以 (因为 );而 c) 给出 ,比较就得 。但题目说 "from this definition",所以主要按上面的矩阵算法写。
得分点:(2 分)、逆矩阵和行列式 (3 分)、乘出来并配方(3 分)。
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 可以看到)。
- Q1:(要平方);单侧 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 ~
- Q3:四个统计量的作用;adjusted R² 可以为负
- Q4: 是证明的钥匙
- Q5:; 均值 k、方差 2k;Var(Syy)
- Q6:同 2019 Q3;BLUE 不需要正态
- Q7:;;配方得
第 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)。
F1,26)文字部分参考答案
(a) brain ~ body:几个巨大的动物(大象、恐龙)杠杆极高,残差图几乎所有点挤在左边,Q-Q 图严重偏离直线,线性、等方差、正态都不成立。log-log 模型的点分布均匀得多,更合适;但恐龙(Brachiosaurus 等,脑小身体大)残差很大,需要调查。
(c) vs ,p < 0.01 → reject。(f) newdata 填 log.body = log(100)。
(h) ;t = −2.506 ~ ;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 同构)
F5,23)文字部分参考答案
(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) :privileges、learning、raises、critical、advance 的系数都是 0。p = 0.51 → 不拒绝:有 complaints 时,其他 5 个变量整体上没有额外作用。
Question 3 [15 marks]:σ̂² 无偏 + mean shift(写在纸上)
(a) [3] Show that .
(b) [3] Find and . Are the residuals uncorrelated?
(c) [4] Show that is an unbiased estimator of σ².
(d) [5] Now suppose the mean shift model holds for observation j: and for . Find and the expected value of the PRESS residual . Which of the two is more useful for detecting the shift, and why?
参考答案
(a)(b) 第 14 章 14.1:;,;,一般不为 0,所以残差相关。
(c) 第 21 章 21.2 (d):,。
(d) 第 14 章 14.6:,。PRESS 残差更有用:普通残差把偏移缩小了 倍,高杠杆点被缩得最厉害,可能看不出来;PRESS 残差对 Δ 无偏。
Question 4 [15 marks]:影响度量(写在纸上)
(a) [2] Show that Cook's distance can be written as , where . Interpret.
(b) [4] Show that .
(c) [4] Show that and find its variance.
(d) [2] Show that .
(e) [3] In a model with n = 20 and p = 3, an observation has and . Compute , the externally studentized residual (use ) and , and comment using the rules of thumb.
参考答案
(a) 。含义:Cook's D 是用全部数据和删去第 i 个点得到的两组拟合值向量之间的欧氏距离的平方,再除以 。
(b)(c)(d) 第 15 章 P15-2、P15-4、P15-5。
(e) ;;。D 接近 1(> 0.5,值得调查),|DFFITS| 接近 2 → 这个观测可能有影响,应进一步检查。注意 r 和 t 不能随便给:知道 、n、p 就能算出 。
Mock B
Question 1 [15 marks]:stackloss 的影响点(Lab 8 风格)
文字部分参考答案
(b) 最大的是第 21 天, ~ ,p = 0.004 → 有证据表明是离群点。
(c) < 1,也 < ,按 Cook's D 不算强影响;但 |DFFITS| = 2.10 > 2,COVRATIO = 0.217 < (删掉它精度会明显提高)。结论:第 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) 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),,C = (0, 1, −1),d = 0。F = 9.63 ~ ,p = 0.0045 → 拒绝。用 relevel(pg$group, ref = "trt1") 重新拟合,group2trt2 的 t = 3.103,,p 相同。summary 里两个和 ctrl 比的 partial t 都不显著(p = 0.19、0.088),但 trt1 vs trt2 显著(p = 0.0045):trt1 和 trt2 分在 ctrl 两边,各自离 ctrl 不远,彼此却差很多。summary 不直接给的两两比较,要用一般线性假设或 relevel 来做。
(e) OJ(参照组):;VC:。(f) 交互项 p = 0.025 → dose 的效应在两种补充方式之间不同(VC 斜率更大);:F = 8.83 ~ ,p = 0.0005 → supp 有效应。
Question 3 [15 marks]:GLS 与方差稳定(写在纸上)
(a) [4] Derive the maximum likelihood estimator of β and show it minimizes .
(b) [4] Find the distribution of the MLE.
(c) [2] Write down the weighted least squares estimator when , , and its covariance matrix.
(d) [5] Using a first order Taylor expansion, show that if then is approximately constant, and if Y is exponential then is approximately constant.
参考答案
(a)(b)(c) 第 17 章 17.2;(d) 第 16 章 16.1 原题答案。
Question 4 [15 marks]:单因素模型与一般线性假设(写在纸上)
(a) [3] For k = 2, , write the model in matrix form with . Show that X is not of full rank.
(b) [4] Re-parametrize as (no intercept). Write X for general k and show that . Hence show that the least squares estimate of is the group sample mean .
(c) [3] In this parametrization, find . Are the estimated group means uncorrelated?
(d) [5] For k = 3, write the hypothesis in the form , state the F statistic and its null distribution. For a single contrast , show that the F statistic equals the square of .
参考答案
(a) X 的行:(1,1,0)、(1,1,0)、(1,0,1)、(1,0,1);第 1 列 = 第 2 列 + 第 3 列 ⇒ 列线性相关,秩 2 < 3。
(b) X 的第 v 列是第 v 组的指示变量。:u = v 时是第 v 组的人数 ;u ≠ v 时没有人同时属于两组,是 0。 的第 v 个元素 = 第 v 组的 y 之和。所以 的第 v 个元素 = 组和 / = 。
(c) ,对角 ⇒ 不相关。
(d) ,d = 0,m = 2;。m = 1 时 是一个数,。
做完之后
- R 题错的地方,回到对应章节(第 13–19、22 章)重做那一节的代码。
- 证明题对照答案,把写不出来的那一步抄三遍。第 15 章和第 17 章的证明最可能原样出现。
- 还有时间就把
past_final_exams/里 2020、2019、2014 的题按第 21 章的地图挑着做。
第 12 章 · Lab Test 三套模拟考试(Week 1–7 练手)
- 每套 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):
- 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)
- 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.
- 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).
- 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.
- 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)
F4,45)解题思路
- (a)
summary(m_full)最后一行:F-statistic: 5.756 on 4 and 45 DF, p-value: 0.0007904。n = 50, p = 5 → 。结论: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:
- In the general linear model with an intercept, the residuals always sum to zero.
- The leverage hii of the i-th observation depends on the value of the response yi.
- 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.
- 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.
- 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 , 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 第一列为 1);2 False( 只依赖 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): 因为 ;(对称幂等)。
(b) P4:;平均杠杆 。
(c) P20:,乘以 得 。H0 下 E(MSreg) = σ² = E(MSres),F 应在 1 附近;H0 不成立时 E(MSreg) 多出 ,F 偏大,所以 F 大时拒绝 H0。
Question 2 [25 marks]:stackloss 数据 + cars(MOCK 2)
F1,17)解题思路
- (b) "AcidConc useful given AirFlow and WaterTemp":
anova(lm(StackLoss ~ AirFlow + WaterTemp, data = Plant), pm)。这里大模型就是全模型,所以结果 = AcidConc 的 partial t 的平方(),p 相同 0.344。 - (c) :小模型只有 AirFlow,
anova(lm(StackLoss ~ AirFlow, data = Plant), pm),F = 6.668 ~ 。 - (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:
- The maximum likelihood estimator of σ² in the normal linear model, SSres/n, is an unbiased estimator of σ².
- When Mallows' Cp is computed using the full model to estimate σ², the full model always has Cp = p.
- Under the usual assumptions, the i-th externally studentized residual follows a t distribution with n − p degrees of freedom.
- The sequential sums of squares in the anova() output do not depend on the order in which the predictors are entered.
- 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();2 True;3 False();4 False;5 True()。
(a) P7(这题就是要你证明它,不能只引用 formula sheet,必须写出推导);(b) P8;(c) P10 第 1 步(写出似然函数和 log 似然);(d) P21:,。
Question 2 [25 marks]:swiss 数据 + mtcars(MOCK 3)
解题思路 + 文字题答案
- (a) 用手写的 Cp 函数或公式:p = 5, 来自不含 Examination 的模型, 来自全模型。
- (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。
做完之后
- Q2 错的题:回到对应章节,看"看到什么题 → 敲什么代码"(第 7 章最后)。
- Q1 判断题错的:第 11 章题库里同一个知识点再看一遍。
- 证明题:对照第 11 章模板,把卡住的那一步单独抄写三遍。