完整教师版讲义,附两小时核心授课路线
本文档将 GLM_part1.pdf 和 GLM_part2.pdf
扩展为完整教师参考资料。内容包括一条集中的两小时核心授课路线,以及估计、推断、交互作用、预测评估、敏感性分析、练习与答案等扩展模块。两小时只用于课堂内容取舍,不限制完整讲义的覆盖范围。
配套脚本 GLM_Complete_ZH.R
按相同顺序包含相同的可执行分析。Quarto 文档用于讲解与课堂讨论,R
脚本用于现场演示或学生练习。为保证跨平台输出一致,两个语言版本使用相同的英文图题和坐标轴标签;中文版的解释与授课提示完全对应。
学完整套材料后,学生应能够:
glm() 拟合
Logistic、Probit、Poisson、quasi-Poisson 和带 offset 的模型。ggplot2
绘制有明确诊断目的的图,而不是把每张残差图都当作正态性检验。| 时间 | 内容 | 核心问题 |
|---|---|---|
| 0–8 分钟 | GLM 框架 | 从 lm() 到 glm(),究竟改变了什么? |
| 8–25 分钟 | Logistic 基础 | 对数优势、优势比和概率有什么区别? |
| 25–45 分钟 | Default 案例 | 如何拟合、解释和预测? |
| 45–60 分钟 | Logistic 诊断 | 每张图分别回答哪个诊断问题? |
| 60–70 分钟 | Probit 与 Logit | 两种链接及解释有何不同? |
| 70–75 分钟 | 休息或提问 | — |
| 75–90 分钟 | Poisson 计数模型 | 为什么系数取指数后表示发生率比? |
| 90–103 分钟 | 过度离散与诊断 | 当 Var(Y) 大于 Poisson 均值时会发生什么? |
| 103–115 分钟 | 率模型与 offset | 如何比较暴露量不同的计数? |
| 115–120 分钟 | 总结与出门测 | 应选什么族、链接、解释尺度和诊断方法? |
删去可选的 mtcars 演示、校准图和 Logit/Probit
曲线比较。不要删去优势比与概率的区别、基于拟合模型的过度离散检查以及
offset。这些是核心学习目标。
所有文件都不会自动安装包。上课前,如果本机尚未配置,请先安装 R、Quarto 和所需 R 包。
install.packages(c(
"ggplot2", "ISLR", "AER", "faraway", "ISwR", "statmod", "car", "knitr"
))在终端中渲染本文档:
quarto render GLM_Complete_ZH.qmdrequired_packages <- c(
"ggplot2", "ISLR", "AER", "faraway", "ISwR", "statmod", "car"
)
missing_packages <- required_packages[
!vapply(required_packages, requireNamespace, logical(1), quietly = TRUE)
]
if (length(missing_packages) > 0L) {
stop(
"Missing packages: ", paste(missing_packages, collapse = ", "),
". Install them manually before running this file."
)
}
library(ggplot2)
theme_set(theme_minimal(base_size = 12))
set.seed(303)
pearson_dispersion <- function(model) {
sum(residuals(model, type = "pearson")^2) / df.residual(model)
}data("Default", package = "ISLR")
data("HMDA", package = "AER")
data("gala", package = "faraway")
data("eba1977", package = "ISwR")
default_data <- Default
default_data$default01 <- as.integer(default_data$default == "Yes")
hmda <- HMDA
hmda$deny01 <- as.integer(hmda$deny == "yes")
gala_data <- gala
gala_data$island <- rownames(gala_data)
cancer_data <- eba1977一个 GLM 包含三个组成部分:
方差函数也是模型的一部分。在本文的标准例子中,Bernoulli 响应有 ,Poisson 响应有 。因此,GLM 不只是“换了一个误差分布的线性模型”;均值、链接以及均值—方差关系都需要考虑。
| 模型 | 响应变量 | 常用链接 | glm() 中的族 |
|---|---|---|---|
| Logistic | 二分类或分组二项 | Logit | binomial("logit") |
| Probit | 二分类或分组二项 | Probit | binomial("probit") |
| Poisson | 计数 | Log | poisson("log") |
| Quasi-Poisson | 过度离散计数 | Log | quasipoisson("log") |
写下 并始终保留。之后每遇到一个模型,都让学生指出 、、,以及系数在哪一个尺度上具有线性关系。
对于二分类响应 ,定义
等式左侧是对数优势。逆链接为
曲线被限制在 0 与 1 之间,但“预测概率不越界”本身并不能证明模型拟合良好。
logit_curve <- data.frame(eta = seq(-6, 6, length.out = 200))
logit_curve$probability <- plogis(logit_curve$eta)
ggplot(logit_curve, aes(x = eta, y = probability)) +
geom_line(color = "steelblue", linewidth = 1) +
geom_hline(yintercept = c(0, 1), linetype = 3, color = "grey60") +
labs(
title = "The inverse logit maps a linear predictor to a probability",
x = expression(paste("Linear predictor, ", eta)),
y = expression(paste("Probability, ", pi))
)当 增加一个单位、模型中的其他项保持不变时:
若基线概率为 ,则基线优势为 。优势比为 2 表示优势翻倍,而不是概率翻倍。新概率为
对于连续预测变量, 表示每增加一个单位时,对数优势的改变量。它不是通常 log–log 模型意义下的弹性。概率对 的局部斜率为 ,所以它依赖于当前概率。
提问:“优势比为 2,概率是否翻倍?还需要什么信息?”要求学生明确回答:必须知道基线概率。
mtcarsmtcars 来自 R 基础安装中的 datasets
包,而不是 dplyr 包。这个例子适合展示公式语法和
predict(),但只有 32
个观测,不宜作为详细建模课的主案例。
fit_cars <- glm(
vs ~ wt + disp,
data = mtcars,
family = binomial(link = "logit")
)
summary(fit_cars)##
## Call:
## glm(formula = vs ~ wt + disp, family = binomial(link = "logit"),
## data = mtcars)
##
## Coefficients:
## Estimate Std. Error z value Pr(>|z|)
## (Intercept) 1.60859 2.43903 0.660 0.510
## wt 1.62635 1.49068 1.091 0.275
## disp -0.03443 0.01536 -2.241 0.025 *
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## (Dispersion parameter for binomial family taken to be 1)
##
## Null deviance: 43.86 on 31 degrees of freedom
## Residual deviance: 21.40 on 29 degrees of freedom
## AIC: 27.4
##
## Number of Fisher Scoring iterations: 6
new_cars <- data.frame(wt = c(4, 1.8), disp = c(280, 70))
predict(fit_cars, newdata = new_cars, type = "response")## 1 2
## 0.1783689 0.8933730
type="link" 返回 $,type=“response”` 返回
。0.5
之类的概率阈值属于后续分类决策,不属于 Logistic
系数的极大似然估计过程。
将 default=="Yes" 明确编码为
default01=1,避免模型结果隐含依赖因子水平的排列顺序。
str(default_data)## 'data.frame': 10000 obs. of 5 variables:
## $ default : Factor w/ 2 levels "No","Yes": 1 1 1 1 1 1 1 1 1 1 ...
## $ student : Factor w/ 2 levels "No","Yes": 1 2 1 1 1 2 1 2 1 1 ...
## $ balance : num 730 817 1074 529 786 ...
## $ income : num 44362 12106 31767 35704 38463 ...
## $ default01: int 0 0 0 0 0 0 0 0 0 0 ...
table(default_data$default, useNA = "ifany")##
## No Yes
## 9667 333
ggplot(default_data, aes(x = balance, y = income, color = default)) +
geom_point(alpha = 0.2, size = 0.8) +
labs(
title = "Default status by balance and income",
x = "Credit card balance",
y = "Income",
color = "Default"
)ggplot(default_data, aes(x = default, y = balance, fill = default)) +
geom_boxplot(outlier.alpha = 0.3) +
guides(fill = "none") +
labs(
title = "Balance differs substantially by default status",
x = "Default status",
y = "Credit card balance"
)这些图用于形成预测变量的初步判断,但不能证明因果关系,也不能证明某个变量一定应进入最终模型。
fit_default <- glm(
default01 ~ balance + student + income,
data = default_data,
family = binomial(link = "logit")
)
summary(fit_default)##
## Call:
## glm(formula = default01 ~ balance + student + income, family = binomial(link = "logit"),
## data = default_data)
##
## Coefficients:
## Estimate Std. Error z value Pr(>|z|)
## (Intercept) -1.087e+01 4.923e-01 -22.080 < 2e-16 ***
## balance 5.737e-03 2.319e-04 24.738 < 2e-16 ***
## studentYes -6.468e-01 2.363e-01 -2.738 0.00619 **
## income 3.033e-06 8.203e-06 0.370 0.71152
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## (Dispersion parameter for binomial family taken to be 1)
##
## Null deviance: 2920.6 on 9999 degrees of freedom
## Residual deviance: 1571.5 on 9996 degrees of freedom
## AIC: 1579.5
##
## Number of Fisher Scoring iterations: 8
coef_default <- coef(fit_default)
or_default <- exp(cbind(OR = coef_default, confint.default(fit_default)))
or_default## OR 2.5 % 97.5 %
## (Intercept) 1.903854e-05 7.254792e-06 4.996229e-05
## balance 1.005753e+00 1.005296e+00 1.006210e+00
## studentYes 5.237317e-01 3.296175e-01 8.321610e-01
## income 1.000003e+00 9.999870e-01 1.000019e+00
balance_scaling <- data.frame(
change = "Balance +100 currency units",
log_odds_change = 100 * coef_default[["balance"]],
OR = exp(100 * coef_default[["balance"]])
)
balance_scaling## change log_odds_change OR
## 1 Balance +100 currency units 0.5736505 1.774734
income_scaling <- data.frame(
change = "Income +10000 currency units",
log_odds_change = 10000 * coef_default[["income"]],
OR = exp(10000 * coef_default[["income"]])
)
income_scaling## change log_odds_change OR
## 1 Income +10000 currency units 0.0303345 1.030799
建议按以下顺序讲 summary() 输出:
一个单位的优势比可能不便交流。应在取指数前重新缩放:例如,余额增加 100 个单位时,对数优势改变 ,优势乘以 。不能把“一个单位的概率差”简单乘以或取幂来得到 100 个单位的概率变化。
fit_student_only <- glm(
default01 ~ student,
data = default_data,
family = binomial(link = "logit")
)
summary(fit_student_only)$coefficients## Estimate Std. Error z value Pr(>|z|)
## (Intercept) -3.5041278 0.07071301 -49.554219 0.0000000000
## studentYes 0.4048871 0.11501883 3.520181 0.0004312529
summary(fit_default)$coefficients## Estimate Std. Error z value Pr(>|z|)
## (Intercept) -1.086905e+01 4.922555e-01 -22.080088 4.911280e-108
## balance 5.736505e-03 2.318945e-04 24.737563 4.219578e-135
## studentYes -6.467758e-01 2.362525e-01 -2.737646 6.188063e-03
## income 3.033450e-06 8.202615e-06 0.369815 7.115203e-01
ggplot(default_data, aes(x = student, y = balance, fill = student)) +
geom_boxplot(outlier.alpha = 0.3) +
guides(fill = "none") +
labs(
title = "Students and non-students have different balance distributions",
x = "Student status",
y = "Credit card balance"
)仅含 student 的模型估计边际关联;完整模型估计给定 balance 和 income 后的条件关联。不同学生状态的余额分布不同,因此调整后系数可能变化。应表述为“条件关联发生变化”;没有因果设计和相应假设时,不能称为 student 的因果效应。
new_default <- data.frame(
balance = 1400,
income = 2000,
student = factor(c("Yes", "No"), levels = levels(default_data$student))
)
pred_default_link <- predict(
fit_default,
newdata = new_default,
type = "link",
se.fit = TRUE
)
prediction_default <- data.frame(
new_default,
eta = pred_default_link$fit,
probability = plogis(pred_default_link$fit),
lower = plogis(pred_default_link$fit - 1.96 * pred_default_link$se.fit),
upper = plogis(pred_default_link$fit + 1.96 * pred_default_link$se.fit)
)
prediction_default## balance income student eta probability lower upper
## 1 1400 2000 Yes -3.478647 0.02992594 0.02091917 0.04264169
## 2 1400 2000 No -2.831871 0.05562603 0.03009852 0.10055950
先在链接尺度构造区间,再使用 plogis()
变换,可以保证区间端点位于
。该区间是模型平均概率的置信区间,不是个体二分类结果的预测区间。这两个个体只有
student 状态不同,因此预测概率比单独看系数符号更直观地展示调整后的
student 对比。
ggplot2 做
Logistic 诊断诊断流程应分别回答不同问题:
| 问题 | 有用工具 | 不应得出的结论 |
|---|---|---|
| 函数形式是否合适? | 残差对预测变量或 、平滑曲线、样条比较 | 对 机械地呈直线,不能证明线性假设成立 |
| 是否存在异常观测? | 标准化残差、杠杆值、Cook 距离 | 超过阈值不等于应该删除数据 |
| 预测是否校准? | 校准图,最好使用验证数据 | 准确率高不必然表示校准好 |
| 预测变量是否冗余? | VIF 或广义 VIF,并结合专业知识 | VIF 小于 5 不是绝对保证 |
| 观测是否独立? | 研究设计和残差结构 | Q–Q 图不能证明独立性 |
对于二分类数据,普通 deviance 和 Pearson 残差不需要呈正态。随机分位数残差通过随机化,使其在模型正确时更便于评估分布;其 Q–Q 图是诊断辅助工具,不是模型正确性的普遍证明。
set.seed(303)
diag_default <- data.frame(
observation = seq_len(nobs(fit_default)),
default01 = default_data$default01,
balance = default_data$balance,
fitted = fitted(fit_default),
eta = predict(fit_default, type = "link"),
deviance = residuals(fit_default, type = "deviance"),
pearson = residuals(fit_default, type = "pearson"),
quantile = statmod::qresid(fit_default),
leverage = hatvalues(fit_default),
cook = cooks.distance(fit_default)
)residual_long <- data.frame(
residual = c(
diag_default$deviance,
diag_default$pearson,
diag_default$quantile
),
type = factor(
rep(
c("Deviance", "Pearson", "Randomized quantile"),
each = nrow(diag_default)
),
levels = c("Deviance", "Pearson", "Randomized quantile")
)
)
ggplot(residual_long, aes(x = residual)) +
geom_density(fill = "steelblue", alpha = 0.3) +
facet_wrap(~type, scales = "free") +
labs(
title = "Residual distributions have different shapes by construction",
x = "Residual",
y = "Density"
)这个 ggplot2 版本用分面图替代多次基础 R 的
plot(density(...))。教学重点是不同残差的构造与用途,而不是要求每条密度曲线都呈钟形。
ggplot(diag_default, aes(sample = quantile)) +
stat_qq(alpha = 0.25) +
stat_qq_line(color = "red") +
labs(
title = "Q-Q plot of randomized quantile residuals",
x = "Theoretical normal quantiles",
y = "Sample quantiles"
)不要看到 deviance 或 Pearson 残差 Q–Q 图不呈直线,就宣布 Bernoulli 响应分布错误。二分类结果会按构造产生离散、非对称的残差形态。
ggplot(diag_default, aes(x = eta, y = quantile)) +
geom_point(alpha = 0.15) +
geom_hline(yintercept = 0, linetype = 2, color = "grey50") +
geom_smooth(method = "loess", se = FALSE, formula = y ~ x, span = 0.6) +
labs(
title = "Randomized quantile residuals versus the linear predictor",
x = expression(paste("Fitted linear predictor, ", hat(eta))),
y = "Randomized quantile residual"
)ggplot(diag_default, aes(x = balance, y = quantile)) +
geom_point(alpha = 0.15) +
geom_hline(yintercept = 0, linetype = 2, color = "grey50") +
geom_smooth(method = "loess", se = FALSE, formula = y ~ x, span = 0.6) +
labs(
title = "Check the functional form of balance",
x = "Credit card balance",
y = "Randomized quantile residual"
)当 balance
以线性项进入模型时,保持其他项不变,
必然与 balance
呈线性。因此,
对 balance
的直线图不能验证该假设。应观察残差是否存在系统模式,并考虑更灵活的模型。
fit_default_spline <- glm(
default01 ~ splines::ns(balance, df = 4) + student + income,
data = default_data,
family = binomial(link = "logit")
)## Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred
anova(fit_default, fit_default_spline, test = "LRT")## Analysis of Deviance Table
##
## Model 1: default01 ~ balance + student + income
## Model 2: default01 ~ splines::ns(balance, df = 4) + student + income
## Resid. Df Resid. Dev Df Deviance Pr(>Chi)
## 1 9996 1571.5
## 2 9993 1570.8 3 0.77748 0.8548
似然比比较提供补充证据,但不能替代图形、专业背景判断和模型验证。
p_default <- length(coef(fit_default))
n_default <- nobs(fit_default)
leverage_threshold_default <- 2 * p_default / n_default
cook_threshold_default <- 4 / n_default
ggplot(diag_default, aes(x = observation, y = leverage)) +
geom_point(alpha = 0.3) +
geom_hline(
yintercept = leverage_threshold_default,
linetype = 2,
color = "red"
) +
labs(
title = "Leverage: unusual predictor combinations",
x = "Observation",
y = "Hat value"
)ggplot(diag_default, aes(x = observation, y = cook)) +
geom_point(alpha = 0.3) +
geom_hline(
yintercept = cook_threshold_default,
linetype = 2,
color = "red"
) +
labs(
title = "Cook's distance: potential influence on fitted values",
x = "Observation",
y = "Cook's distance"
)top_influence_default <- head(
diag_default[
order(-diag_default$cook),
c("observation", "fitted", "leverage", "cook")
],
10
)
top_influence_default## observation fitted leverage cook
## 9539 9539 0.0009233701 4.899066e-05 0.013253140
## 9523 9523 0.0055602883 2.831632e-04 0.012667879
## 4160 4160 0.0011516766 5.834825e-05 0.012652825
## 652 652 0.0019521252 9.392420e-05 0.012007228
## 9874 9874 0.9525549066 2.334366e-03 0.011771659
## 8365 8365 0.0035266082 1.406387e-04 0.009937464
## 5015 5015 0.0080747444 3.153124e-04 0.009689585
## 8725 8725 0.0384586675 1.509370e-03 0.009462839
## 3977 3977 0.9009397511 3.942983e-03 0.009036345
## 9438 9438 0.0051257666 1.851092e-04 0.008985414
vif_default <- car::vif(fit_default)
vif_default## balance student income
## 1.076946 2.761184 2.674562
杠杆值关注异常的预测变量组合;大残差关注响应与拟合值的不一致;影响诊断关注观测对拟合结果的作用。三者不是同义词。 和 等阈值只是筛查经验。应检查数据质量并做敏感性分析,而不是自动删除观测。
calibration_breaks <- unique(quantile(
diag_default$fitted,
probs = seq(0, 1, by = 0.1),
na.rm = TRUE
))
calibration_group <- cut(
diag_default$fitted,
breaks = calibration_breaks,
include.lowest = TRUE
)
calibration_default <- data.frame(
mean_predicted = tapply(diag_default$fitted, calibration_group, mean),
observed_rate = tapply(default_data$default01, calibration_group, mean),
n = as.integer(table(calibration_group))
)
ggplot(calibration_default, aes(x = mean_predicted, y = observed_rate)) +
geom_abline(intercept = 0, slope = 1, linetype = 2, color = "red") +
geom_line(color = "steelblue") +
geom_point(aes(size = n), color = "steelblue") +
labs(
title = "In-sample calibration by predicted-risk group",
x = "Mean predicted probability",
y = "Observed event rate",
size = "Group size"
)这里是样本内演示。若目标是预测,还应使用可重复的训练集/测试集划分或重抽样,并评估区分度、校准度和决策成本。残差诊断本身不能衡量样本外预测表现。
Probit 模型为
其中 是标准正态分布的分布函数。系数表示 Probit 指数的改变,而不是对数优势的改变。解释时应报告预测概率或概率差。
fit_probit <- glm(
deny01 ~ pirat,
data = hmda,
family = binomial(link = "probit")
)
summary(fit_probit)##
## Call:
## glm(formula = deny01 ~ pirat, family = binomial(link = "probit"),
## data = hmda)
##
## Coefficients:
## Estimate Std. Error z value Pr(>|z|)
## (Intercept) -2.1941 0.1378 -15.927 < 2e-16 ***
## pirat 2.9679 0.3858 7.694 1.43e-14 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## (Dispersion parameter for binomial family taken to be 1)
##
## Null deviance: 1744.2 on 2379 degrees of freedom
## Residual deviance: 1663.6 on 2378 degrees of freedom
## AIC: 1667.6
##
## Number of Fisher Scoring iterations: 6
fit_logit_hmda <- glm(
deny01 ~ pirat,
data = hmda,
family = binomial(link = "logit")
)
summary(fit_logit_hmda)##
## Call:
## glm(formula = deny01 ~ pirat, family = binomial(link = "logit"),
## data = hmda)
##
## Coefficients:
## Estimate Std. Error z value Pr(>|z|)
## (Intercept) -4.0284 0.2686 -14.999 < 2e-16 ***
## pirat 5.8845 0.7336 8.021 1.05e-15 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## (Dispersion parameter for binomial family taken to be 1)
##
## Null deviance: 1744.2 on 2379 degrees of freedom
## Residual deviance: 1660.2 on 2378 degrees of freedom
## AIC: 1664.2
##
## Number of Fisher Scoring iterations: 5
new_pirat <- data.frame(pirat = c(0.3, 0.4))
p_probit <- predict(fit_probit, newdata = new_pirat, type = "response")
probit_change <- data.frame(
from = 0.3,
to = 0.4,
probability_from = unname(p_probit[1]),
probability_to = unname(p_probit[2]),
change_percentage_points = 100 * unname(p_probit[2] - p_probit[1])
)
probit_change## from to probability_from probability_to change_percentage_points
## 1 0.3 0.4 0.09615344 0.1569678 6.081433
原讲义得到的概率差约为 0.0608,应表述为“增加约 6.08 个百分点”,而不是“增加 6.1%”。若要表达相对百分比变化,还需要将概率差除以初始概率。
pirat_grid <- data.frame(pirat = seq(
min(hmda$pirat, na.rm = TRUE),
max(hmda$pirat, na.rm = TRUE),
length.out = 200
))
pirat_grid$probit <- predict(
fit_probit,
newdata = pirat_grid,
type = "response"
)
pirat_grid$logit <- predict(
fit_logit_hmda,
newdata = pirat_grid,
type = "response"
)
link_curve_long <- data.frame(
pirat = rep(pirat_grid$pirat, 2),
model = factor(
rep(c("Probit", "Logit"), each = nrow(pirat_grid)),
levels = c("Probit", "Logit")
),
probability = c(pirat_grid$probit, pirat_grid$logit)
)
ggplot(link_curve_long, aes(x = pirat, y = probability, color = model)) +
geom_line(linewidth = 1) +
labs(
title = "Probit and logit fitted probabilities on the same data",
x = "Payments-to-income ratio",
y = "Predicted probability of denial",
color = "Model"
)AIC(fit_probit, fit_logit_hmda)## df AIC
## fit_probit 2 1667.585
## fit_logit_hmda 2 1664.188
不要直接比较 Logit 和 Probit 原始系数的大小,因为两者的指数尺度不同。应比较预测概率、诊断、解释便利性和验证表现。AIC 可用于同一数据上的模型比较,但不应把很小的 AIC 差异当成机械选择规则。
对于计数响应,
因此,在基本 Poisson 模型下,。
直方图描述的是响应的边际分布。右偏本身不能说明给定协变量后的响应服从 Poisson;由协变量驱动的多个 Poisson 分布混合,也会产生右偏或过度离散的边际分布。
ggplot(gala_data, aes(x = Species)) +
geom_histogram(bins = 10, fill = "steelblue", color = "white") +
labs(
title = "Marginal distribution of species counts",
x = "Number of plant species",
y = "Number of islands"
)fit_gala_full <- glm(
Species ~ Endemics + Area + Elevation + Nearest + Scruz + Adjacent,
data = gala_data,
family = poisson(link = "log")
)
summary(fit_gala_full)##
## Call:
## glm(formula = Species ~ Endemics + Area + Elevation + Nearest +
## Scruz + Adjacent, family = poisson(link = "log"), data = gala_data)
##
## Coefficients:
## Estimate Std. Error z value Pr(>|z|)
## (Intercept) 2.828e+00 5.958e-02 47.471 < 2e-16 ***
## Endemics 3.388e-02 1.741e-03 19.459 < 2e-16 ***
## Area -1.067e-04 3.741e-05 -2.853 0.00433 **
## Elevation 2.638e-04 1.934e-04 1.364 0.17264
## Nearest 1.048e-02 1.611e-03 6.502 7.91e-11 ***
## Scruz -6.835e-04 5.802e-04 -1.178 0.23877
## Adjacent 4.539e-05 4.800e-05 0.946 0.34437
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## (Dispersion parameter for poisson family taken to be 1)
##
## Null deviance: 3510.73 on 29 degrees of freedom
## Residual deviance: 313.36 on 23 degrees of freedom
## AIC: 488.19
##
## Number of Fisher Scoring iterations: 5
fit_gala <- glm(
Species ~ Endemics + Area + Nearest,
data = gala_data,
family = poisson(link = "log")
)
summary(fit_gala)##
## Call:
## glm(formula = Species ~ Endemics + Area + Nearest, family = poisson(link = "log"),
## data = gala_data)
##
## Coefficients:
## Estimate Std. Error z value Pr(>|z|)
## (Intercept) 2.868e+00 4.883e-02 58.729 < 2e-16 ***
## Endemics 3.551e-02 7.327e-04 48.462 < 2e-16 ***
## Area -4.542e-05 1.568e-05 -2.896 0.00378 **
## Nearest 9.289e-03 1.319e-03 7.043 1.88e-12 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## (Dispersion parameter for poisson family taken to be 1)
##
## Null deviance: 3510.73 on 29 degrees of freedom
## Residual deviance: 330.84 on 26 degrees of freedom
## AIC: 499.67
##
## Number of Fisher Scoring iterations: 5
irr_gala <- exp(cbind(IRR = coef(fit_gala), confint.default(fit_gala)))
irr_gala## IRR 2.5 % 97.5 %
## (Intercept) 17.5995818 15.9932425 19.3672596
## Endemics 1.0361458 1.0346589 1.0376348
## Area 0.9999546 0.9999238 0.9999853
## Nearest 1.0093319 1.0067262 1.0119443
area_effect <- data.frame(
change = "Area +100 square km",
IRR = exp(100 * coef(fit_gala)[["Area"]])
)
area_effect## change IRR
## 1 Area +100 square km 0.9954685
当 增加一个单位、其他模型项保持不变时,期望计数乘以 。这就是发生率比或均值比的乘法解释。对于面积等一个单位效应很小的变量,应先改成每 100 平方千米等有实际意义的尺度再解释。
这里保留精简模型是为了与原讲义对应。不要把“删除所有 的变量”教成普遍建模策略。这样做可能扭曲统计推断,也会删除具有重要调整作用的变量。
过度离散表示条件方差大于 Poisson 模型允许的方差。其后果可能包括标准误被低估、区间过窄以及显著性被夸大。
基于模型的 Pearson 离散参数估计为
它使用拟合回归模型的残差和残差自由度。将原始响应的方差与单一 Poisson 均值比较,会忽略不同协变量对应的条件均值,并不是同一种诊断。
phi_gala <- pearson_dispersion(fit_gala)
phi_gala## [1] 11.72483
fit_gala_quasi <- update(fit_gala, family = quasipoisson(link = "log"))
summary(fit_gala_quasi)##
## Call:
## glm(formula = Species ~ Endemics + Area + Nearest, family = quasipoisson(link = "log"),
## data = gala_data)
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 2.868e+00 1.672e-01 17.152 1.08e-15 ***
## Endemics 3.551e-02 2.509e-03 14.153 9.96e-14 ***
## Area -4.542e-05 5.370e-05 -0.846 0.4054
## Nearest 9.289e-03 4.516e-03 2.057 0.0499 *
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## (Dispersion parameter for quasipoisson family taken to be 11.72483)
##
## Null deviance: 3510.73 on 29 degrees of freedom
## Residual deviance: 330.84 on 26 degrees of freedom
## AIC: NA
##
## Number of Fisher Scoring iterations: 5
se_comparison_gala <- data.frame(
term = names(coef(fit_gala)),
poisson_se = summary(fit_gala)$coefficients[, "Std. Error"],
quasi_poisson_se = summary(fit_gala_quasi)$coefficients[, "Std. Error"]
)
se_comparison_gala$se_ratio <-
se_comparison_gala$quasi_poisson_se / se_comparison_gala$poisson_se
se_comparison_gala## term poisson_se quasi_poisson_se se_ratio
## (Intercept) (Intercept) 4.883194e-02 0.1672080721 3.424154
## Endemics Endemics 7.326869e-04 0.0025088326 3.424154
## Area Area 1.568405e-05 0.0000537046 3.424154
## Nearest Nearest 1.318855e-03 0.0045159627 3.424154
对于同一个均值模型,quasi-Poisson 保持系数估计不变,并将标准误乘以 。它没有提供完整的分布似然,因此普通 AIC 不可用。它也不能修复缺失预测变量、错误链接或错误函数形式。负二项模型可以作为后续扩展,但不是每个数据集的自动下一步。
ggplot2 做
Poisson 诊断随机分位数残差使用 Poisson 拟合对象计算;quasi-Poisson 用于离散参数调整后的 Wald 推断。两者的均值模型点估计相同。
set.seed(303)
diag_gala <- data.frame(
island = gala_data$island,
observation = seq_len(nobs(fit_gala)),
eta = predict(fit_gala, type = "link"),
quantile = statmod::qresid(fit_gala),
std_deviance = rstandard(fit_gala, type = "deviance"),
leverage = hatvalues(fit_gala),
cook = cooks.distance(fit_gala)
)ggplot(diag_gala, aes(x = eta, y = quantile)) +
geom_point() +
geom_hline(yintercept = 0, linetype = 2, color = "grey50") +
geom_smooth(method = "loess", se = FALSE, formula = y ~ x, span = 0.8) +
labs(
title = "Poisson quantile residuals versus the linear predictor",
x = expression(paste("Fitted linear predictor, ", hat(eta))),
y = "Randomized quantile residual"
)ggplot(diag_gala, aes(sample = quantile)) +
stat_qq() +
stat_qq_line(color = "red") +
labs(
title = "Q-Q plot of Poisson randomized quantile residuals",
x = "Theoretical normal quantiles",
y = "Sample quantiles"
)只有 30 个观测时,应避免“看起来一切正常”之类的确定性表述。平滑曲线弯曲提示均值模型可能设定不当;Q–Q 图中的突出点可能对应异常观测。应进一步考虑变换、遗漏结构和敏感性分析。quasi-Poisson 本身不能消除残差曲线中的弯曲模式。
p_gala <- length(coef(fit_gala))
n_gala <- nobs(fit_gala)
leverage_threshold_gala <- 2 * p_gala / n_gala
cook_threshold_gala <- 4 / n_gala
ggplot(diag_gala, aes(x = observation, y = leverage)) +
geom_point() +
geom_hline(
yintercept = leverage_threshold_gala,
linetype = 2,
color = "red"
) +
geom_text(
data = diag_gala[diag_gala$leverage > leverage_threshold_gala, ],
aes(label = island),
vjust = -0.6,
size = 3,
check_overlap = TRUE
) +
labs(
title = "Leverage in the reduced Poisson model",
x = "Observation",
y = "Hat value"
)ggplot(diag_gala, aes(x = observation, y = cook)) +
geom_point() +
geom_hline(
yintercept = cook_threshold_gala,
linetype = 2,
color = "red"
) +
geom_text(
data = diag_gala[diag_gala$cook > cook_threshold_gala, ],
aes(label = island),
vjust = -0.6,
size = 3,
check_overlap = TRUE
) +
labs(
title = "Cook's distance in the reduced Poisson model",
x = "Observation",
y = "Cook's distance"
)outliers_gala <- diag_gala[abs(diag_gala$std_deviance) > 2, ]
high_leverage_gala <-
diag_gala[diag_gala$leverage > leverage_threshold_gala, ]
influential_gala <- diag_gala[diag_gala$cook > cook_threshold_gala, ]
outliers_gala## island observation eta quantile std_deviance
## Baltra Baltra 1 3.688989 2.6569269 2.736055
## Caldwell Caldwell 3 3.000397 -4.6149095 -4.874370
## Coamano Coamano 5 2.921029 -4.7262991 -5.024753
## Daphne.Major Daphne.Major 6 3.332755 -1.8870282 -2.068881
## Darwin Darwin 8 3.433065 -4.3359069 -4.541039
## Eden Eden 9 3.013621 -3.1192529 -3.196833
## Enderby Enderby 10 2.963033 -5.0013324 -5.170373
## Espanola Espanola 11 3.798649 6.8336776 6.954982
## Fernandina Fernandina 12 4.121773 3.7663498 3.802154
## Gardner1 Gardner1 13 3.481700 3.9863905 4.121713
## Gardner2 Gardner2 14 3.052599 -4.3332580 -4.320673
## Genovesa Genovesa 15 3.982016 -1.9612829 -2.114357
## Isabela Isabela 16 5.822503 0.4908308 4.475394
## Onslow Onslow 18 2.969543 -5.0472671 -5.192054
## Pinta Pinta 19 4.449258 1.9657938 2.019495
## Pinzon Pinzon 20 4.138206 5.2119954 5.304334
## Las.Plazas Las.Plazas 21 3.192079 -2.6410223 -2.841569
## Rabida Rabida 22 3.973758 2.2351552 2.254739
## SanSalvador SanSalvador 24 5.719872 -4.0510861 -4.695386
## SantaCruz SantaCruz 25 6.205642 -2.3338938 -3.456136
## SantaMaria SantaMaria 27 5.476334 2.9170297 3.221615
## Seymour Seymour 28 3.441490 2.1147525 2.204806
## Wolf Wolf 30 3.610581 -2.8468008 -2.966373
## leverage cook
## Baltra 0.05190406 0.11685937
## Caldwell 0.04137989 0.16369790
## Coamano 0.04114806 0.16532551
## Daphne.Major 0.04094068 0.03984230
## Darwin 0.06244900 0.25221492
## Eden 0.04350743 0.08921699
## Enderby 0.04111487 0.17398255
## Espanola 0.05238870 0.89571481
## Fernandina 0.04881340 0.21470768
## Gardner1 0.04852747 0.26768466
## Gardner2 0.04067064 0.13645651
## Genovesa 0.15017830 0.17996910
## Isabela 0.98764758 403.97314691
## Onslow 0.04069351 0.17343098
## Pinta 0.08921355 0.10680962
## Pinzon 0.04505295 0.40447133
## Las.Plazas 0.04566081 0.07840333
## Rabida 0.04968198 0.07312494
## SanSalvador 0.25734582 1.76229993
## SantaCruz 0.53485660 3.31256786
## SantaMaria 0.19580671 0.67113018
## Seymour 0.04868676 0.07018275
## Wolf 0.06804535 0.13534946
high_leverage_gala## island observation eta quantile std_deviance
## Isabela Isabela 16 5.822503 0.4908308 4.475394
## SanCristobal SanCristobal 23 5.570675 1.0911520 1.903321
## SantaCruz SantaCruz 25 6.205642 -2.3338938 -3.456136
## leverage cook
## Isabela 0.9876476 403.973147
## SanCristobal 0.6889618 2.049871
## SantaCruz 0.5348566 3.312568
influential_gala## island observation eta quantile std_deviance
## Caldwell Caldwell 3 3.000397 -4.6149095 -4.874370
## Coamano Coamano 5 2.921029 -4.7262991 -5.024753
## Darwin Darwin 8 3.433065 -4.3359069 -4.541039
## Enderby Enderby 10 2.963033 -5.0013324 -5.170373
## Espanola Espanola 11 3.798649 6.8336776 6.954982
## Fernandina Fernandina 12 4.121773 3.7663498 3.802154
## Gardner1 Gardner1 13 3.481700 3.9863905 4.121713
## Gardner2 Gardner2 14 3.052599 -4.3332580 -4.320673
## Genovesa Genovesa 15 3.982016 -1.9612829 -2.114357
## Isabela Isabela 16 5.822503 0.4908308 4.475394
## Onslow Onslow 18 2.969543 -5.0472671 -5.192054
## Pinzon Pinzon 20 4.138206 5.2119954 5.304334
## SanCristobal SanCristobal 23 5.570675 1.0911520 1.903321
## SanSalvador SanSalvador 24 5.719872 -4.0510861 -4.695386
## SantaCruz SantaCruz 25 6.205642 -2.3338938 -3.456136
## SantaMaria SantaMaria 27 5.476334 2.9170297 3.221615
## Wolf Wolf 30 3.610581 -2.8468008 -2.966373
## leverage cook
## Caldwell 0.04137989 0.1636979
## Coamano 0.04114806 0.1653255
## Darwin 0.06244900 0.2522149
## Enderby 0.04111487 0.1739826
## Espanola 0.05238870 0.8957148
## Fernandina 0.04881340 0.2147077
## Gardner1 0.04852747 0.2676847
## Gardner2 0.04067064 0.1364565
## Genovesa 0.15017830 0.1799691
## Isabela 0.98764758 403.9731469
## Onslow 0.04069351 0.1734310
## Pinzon 0.04505295 0.4044713
## SanCristobal 0.68896178 2.0498706
## SanSalvador 0.25734582 1.7622999
## SantaCruz 0.53485660 3.3125679
## SantaMaria 0.19580671 0.6711302
## Wolf 0.06804535 0.1353495
vif_gala <- car::vif(fit_gala)
vif_gala## Endemics Area Nearest
## 1.418635 1.389114 1.110042
代码明确使用 cook=cooks.distance(fit_gala) 计算 Cook
距离,避免原讲义中 cooksD
未定义的问题。所有阈值都只是筛查工具。可以在敏感性分析中重新拟合排除某个被标记观测后的模型,报告结果变化,但不能为了得到想要的结论而删除数据。
当暴露量不同时,将期望计数写成
其中 是暴露量, 是每单位暴露量的事件率。使用 log 链接时,
其中
是 offset:其系数固定为
1,而不是由数据估计。响应变量仍然是计数
cases;不能先把响应改成比率,再声称原 Poisson
计数方差模型仍然适用。
fit_rate <- glm(
cases ~ city + age + offset(log(pop)),
data = cancer_data,
family = poisson(link = "log")
)
summary(fit_rate)##
## Call:
## glm(formula = cases ~ city + age + offset(log(pop)), family = poisson(link = "log"),
## data = cancer_data)
##
## Coefficients:
## Estimate Std. Error z value Pr(>|z|)
## (Intercept) -5.6321 0.2003 -28.125 < 2e-16 ***
## cityHorsens -0.3301 0.1815 -1.818 0.0690 .
## cityKolding -0.3715 0.1878 -1.978 0.0479 *
## cityVejle -0.2723 0.1879 -1.450 0.1472
## age55-59 1.1010 0.2483 4.434 9.23e-06 ***
## age60-64 1.5186 0.2316 6.556 5.53e-11 ***
## age65-69 1.7677 0.2294 7.704 1.31e-14 ***
## age70-74 1.8569 0.2353 7.891 3.00e-15 ***
## age75+ 1.4197 0.2503 5.672 1.41e-08 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## (Dispersion parameter for poisson family taken to be 1)
##
## Null deviance: 129.908 on 23 degrees of freedom
## Residual deviance: 23.447 on 15 degrees of freedom
## AIC: 137.84
##
## Number of Fisher Scoring iterations: 5
rr_rate <- exp(cbind(RR = coef(fit_rate), confint.default(fit_rate)))
rr_rate## RR 2.5 % 97.5 %
## (Intercept) 0.003581174 0.002418625 0.005302521
## cityHorsens 0.718880610 0.503687146 1.026012546
## cityKolding 0.689667168 0.477285856 0.996553318
## cityVejle 0.761612264 0.527026991 1.100613918
## age55-59 3.007213795 1.848515376 4.892215085
## age60-64 4.565884929 2.899710957 7.189442499
## age65-69 5.857402508 3.735990951 9.183417356
## age70-74 6.403619032 4.037552548 10.156236043
## age75+ 4.135686847 2.532309969 6.754270176
phi_rate <- pearson_dispersion(fit_rate)
phi_rate## [1] 1.504109
系数取指数后,在其他模型项不变时比较事件率。截距是参照城市和参照年龄组的期望对数率;除非暴露量恰为相应尺度上的 1,否则截距不是原始期望计数。
new_cancer <- data.frame(
city = factor("Kolding", levels = levels(cancer_data$city)),
age = factor("40-54", levels = levels(cancer_data$age)),
pop = 1000
)
pred_rate <- predict(
fit_rate,
newdata = new_cancer,
type = "link",
se.fit = TRUE
)
prediction_rate <- data.frame(
new_cancer,
expected_cases = exp(pred_rate$fit),
lower = exp(pred_rate$fit - 1.96 * pred_rate$se.fit),
upper = exp(pred_rate$fit + 1.96 * pred_rate$se.fit)
)
prediction_rate$rate_per_1000 <-
prediction_rate$expected_cases / prediction_rate$pop * 1000
prediction_rate## city age pop expected_cases lower upper rate_per_1000
## 1 Kolding 40-54 1000 2.469818 1.627957 3.747029 2.469818
offset_demo <- new_cancer[c(1, 1), ]
offset_demo$pop <- c(1000, 2000)
offset_demo$expected_cases <- predict(
fit_rate,
newdata = offset_demo,
type = "response"
)
offset_demo$rate_per_1000 <-
offset_demo$expected_cases / offset_demo$pop * 1000
offset_demo## city age pop expected_cases rate_per_1000
## 1 Kolding 40-54 1000 2.469818 2.469818
## 1.1 Kolding 40-54 2000 4.939637 2.469818
将链接尺度估计取指数后得到的区间是期望计数的置信区间,不是未来实际计数的预测区间;后者还需要考虑计数本身的随机变异。当
pop=1000 时,期望计数与每 1,000
人的事件率在数值上相同,但概念标签不同。人口翻倍时,期望计数翻倍,率保持不变。这个小演示是解释
offset 作用最直接的方式。
本模块不属于两小时核心路线的必讲内容,但完整的 GLM 课程应当覆盖这些理论。
glm()
估计的是什么对于参数化 GLM,通常使用极大似然法估计系数。对数似然为 ,得分方程令其关于 的导数为零。对于 logit 和 log 链接,这些方程是非线性的,通常没有闭式系数公式。
R 使用迭代加权最小二乘法(IRLS),在这里也称 Fisher
scoring。直观地说,每次迭代针对一个工作响应求解加权最小二乘问题,更新
,然后重复直到估计稳定。因此,Fisher scoring iterations
是计算过程信息,不是模型质量指标。
在标准参数化二项和 Poisson GLM 中,离散参数固定为 1。输出中的 z 统计量使用大样本正态近似。算法收敛并不表示模型设定正确。
对于拟合模型 ,deviance 将其对数似然与饱和参照模型比较。对固定数据集,较小的 residual deviance 表示样本内拟合更接近,但增加参数通常会降低 deviance。因此,residual deviance 不能单独作为选模规则。
常用对象包括:
logLik(fit):最大化后的对数似然。deviance(fit):残差 deviance。df.residual(fit):残差自由度。AIC(fit):对于估计
个参数的参数模型,为
。logLik(fit_default)## 'log Lik.' -785.7724 (df=4)
deviance(fit_default)## [1] 1571.545
df.residual(fit_default)## [1] 9996
AIC(fit_default)## [1] 1579.545
这些方法相关,但并不相同:
wald_ci_default <- confint.default(fit_default)
wald_ci_default## 2.5 % 97.5 %
## (Intercept) -1.183385e+01 -9.904242e+00
## balance 5.282000e-03 6.191010e-03
## studentYes -1.109822e+00 -1.837294e-01
## income -1.304338e-05 1.911028e-05
profile_ci_default <- confint(fit_default)## Waiting for profiling to be done...
profile_ci_default## 2.5 % 97.5 %
## (Intercept) -1.185902e+01 -9.928174e+00
## balance 5.294898e-03 6.204587e-03
## studentYes -1.109018e+00 -1.822147e-01
## income -1.304712e-05 1.912447e-05
fit_default_no_income <- update(fit_default, . ~ . - income)
anova(fit_default_no_income, fit_default, test = "LRT")## Analysis of Deviance Table
##
## Model 1: default01 ~ balance + student
## Model 2: default01 ~ balance + student + income
## Resid. Df Resid. Dev Df Deviance Pr(>Chi)
## 1 9997 1571.7
## 2 9996 1571.5 1 0.13677 0.7115
AIC(fit_default_no_income, fit_default)## df AIC
## fit_default_no_income 3 1577.682
## fit_default 4 1579.545
标准似然比比较要求模型嵌套,并且拟合使用相同响应和相同观测。AIC
比较拟合与复杂度,但不检验任何一个模型是否正确。income
的统计显著性也不等同于其实际重要性或预测重要性。
当预测变量能够几乎完全区分两个响应类别时,会出现完全分离或准完全分离。此时有限的极大似然估计可能不存在。警示信号包括:
fitted probabilities numerically 0 or 1 occurred
警告。任何单一信号都不是最终判决。应检查数据和模型,而不是仅仅隐藏警告。惩罚似然或精确方法可以作为扩展,但本文主案例不需要使用。
convergence_default <- data.frame(
converged = fit_default$converged,
iterations = fit_default$iter,
minimum_fitted_probability = min(fitted(fit_default)),
maximum_fitted_probability = max(fitted(fit_default))
)
convergence_default## converged iterations minimum_fitted_probability maximum_fitted_probability
## 1 TRUE 8 1.025695e-05 0.9776263
缺失值处理同样重要。默认情况下,glm()
会删除模型变量中含缺失值的行。将诊断结果合并回原数据时,如果有行被删除,应使用模型框架或明确的行标识;不能默认残差向量的位置始终与原数据一致。
对于使用处理对照的二水平因子,R
会为非参照水平创建指示变量。此时,当其他数值预测变量为 0
时,截距对应参照水平。balance=0
等取值可能不在实际关心的范围内,因此截距通常不是主要解释对象。
contrasts(default_data$student)## Yes
## No 0
## Yes 1
model_matrix_example <- model.matrix(
~ balance + student + income,
data = default_data
)
head(model_matrix_example)## (Intercept) balance studentYes income
## 1 1 729.5265 0 44361.625
## 2 1 817.1804 1 12106.135
## 3 1 1073.5492 0 31767.139
## 4 1 529.2506 0 35704.494
## 5 1 785.6559 0 38463.496
## 6 1 919.5885 1 7491.559
改变参照水平会改变参数化方式,但不会改变其他条件完全等价的模型所产生的拟合概率。报告结果时,应始终说明参照类别和事件类别。
balance*student 展开为
balance+student+balance:student。交互作用允许 logit
尺度上的 balance 斜率随 student
状态变化。由于逆链接是非线性的,链接尺度上的交互也会产生不平行的概率曲线。
fit_default_interaction <- glm(
default01 ~ balance * student + income,
data = default_data,
family = binomial(link = "logit")
)
summary(fit_default_interaction)##
## Call:
## glm(formula = default01 ~ balance * student + income, family = binomial(link = "logit"),
## data = default_data)
##
## Coefficients:
## Estimate Std. Error z value Pr(>|z|)
## (Intercept) -1.099e+01 5.667e-01 -19.399 <2e-16 ***
## balance 5.817e-03 2.938e-04 19.801 <2e-16 ***
## studentYes -2.856e-01 8.239e-01 -0.347 0.729
## income 3.016e-06 8.226e-06 0.367 0.714
## balance:studentYes -2.184e-04 4.781e-04 -0.457 0.648
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## (Dispersion parameter for binomial family taken to be 1)
##
## Null deviance: 2920.6 on 9999 degrees of freedom
## Residual deviance: 1571.3 on 9995 degrees of freedom
## AIC: 1581.3
##
## Number of Fisher Scoring iterations: 8
anova(fit_default, fit_default_interaction, test = "LRT")## Analysis of Deviance Table
##
## Model 1: default01 ~ balance + student + income
## Model 2: default01 ~ balance * student + income
## Resid. Df Resid. Dev Df Deviance Pr(>Chi)
## 1 9996 1571.5
## 2 9995 1571.3 1 0.20712 0.649
含交互模型中,不能把 balance 的主效应系数解释为普遍适用的 balance 效应。它是参照 student 组的斜率。应在有意义的取值范围内使用预测概率解释。
balance_grid <- seq(
min(default_data$balance),
max(default_data$balance),
length.out = 200
)
interaction_newdata <- expand.grid(
balance = balance_grid,
student = factor(
levels(default_data$student),
levels = levels(default_data$student)
),
income = median(default_data$income)
)
interaction_newdata$probability <- predict(
fit_default_interaction,
newdata = interaction_newdata,
type = "response"
)
ggplot(
interaction_newdata,
aes(x = balance, y = probability, color = student)
) +
geom_line(linewidth = 1) +
labs(
title = "Predicted probabilities from the interaction model",
subtitle = paste("Income fixed at its sample median:", median(default_data$income)),
x = "Credit card balance",
y = "Predicted probability of default",
color = "Student"
)将 income
固定在中位数,得到的是条件于某一明确收入水平的曲线,并不是对观测收入分布取平均后的结果。
对每个观测行,分别计算 student=Yes 和
student=No
时的模型预测概率,其他变量保持不变。对每一行的概率差取平均,得到平均调整后概率对比。
default_yes <- default_data
default_yes$student <- factor(
"Yes",
levels = levels(default_data$student)
)
default_no <- default_data
default_no$student <- factor(
"No",
levels = levels(default_data$student)
)
p_if_yes <- predict(fit_default, newdata = default_yes, type = "response")
p_if_no <- predict(fit_default, newdata = default_no, type = "response")
average_student_contrast <- mean(p_if_yes - p_if_no)
average_student_contrast## [1] -0.01326965
这是在样本协变量分布上平均的模型关联性摘要,不自动具有因果含义。其标准误需要额外方法,例如 delta 方法或适当的 bootstrap。
对于无交互 Logistic 模型中的连续预测变量,第 个观测处的导数为 。对该导数取平均,可得到概率尺度上的平均边际效应。
average_balance_slope <- coef(fit_default)[["balance"]] *
mean(fitted(fit_default) * (1 - fitted(fit_default)))
average_balance_slope_per_100 <- 100 * average_balance_slope
average_balance_slope_per_100## [1] 0.01232347
每 100 个单位的平均斜率是局部概率尺度摘要。它不等于从一个固定概率变化到另一个固定概率,也不是优势比。
模型诊断关注假设和函数形式是否合理;预测评估关注模型在未参与拟合的观测上表现如何。预测项目需要二者,任何一方都不能替代另一方。
下面代码进行可重复、近似按类别分层的划分。实际项目中,所有依赖数据的预处理、变量选择和阈值调整都只能使用训练数据。
stratified_training_rows <- function(y, proportion = 0.7) {
rows_by_class <- split(seq_along(y), y)
selected <- unlist(
lapply(rows_by_class, function(rows) {
sample(rows, size = floor(length(rows) * proportion))
}),
use.names = FALSE
)
sort(selected)
}
set.seed(303)
training_rows <- stratified_training_rows(default_data$default01)
training_data <- default_data[training_rows, ]
test_data <- default_data[-training_rows, ]
fit_default_train <- glm(
default01 ~ balance + student + income,
data = training_data,
family = binomial(link = "logit")
)
p_test <- predict(fit_default_train, newdata = test_data, type = "response")
observed_test <- test_data$default01单次划分可能不稳定。模型开发时通常更适合交叉验证或重复重抽样。最终保留的测试集不应被反复用于选择变量、链接或阈值。
以违约为阳性类别:
类别不平衡时,准确率可能具有误导性。始终预测“不违约”的分类器可能有很高准确率,但灵敏度为零。
predicted_test <- as.integer(p_test >= 0.5)
confusion_test <- table(
Observed = factor(observed_test, levels = c(0, 1)),
Predicted = factor(predicted_test, levels = c(0, 1))
)
confusion_test## Predicted
## Observed 0 1
## 0 2888 13
## 1 70 30
tn <- confusion_test["0", "0"]
fp <- confusion_test["0", "1"]
fn <- confusion_test["1", "0"]
tp <- confusion_test["1", "1"]
accuracy_test <- (tp + tn) / sum(confusion_test)
sensitivity_test <- tp / (tp + fn)
specificity_test <- tn / (tn + fp)
precision_test <- tp / (tp + fp)
brier_test <- mean((observed_test - p_test)^2)
p_test_clamped <- pmin(pmax(p_test, 1e-15), 1 - 1e-15)
log_loss_test <- -mean(
observed_test * log(p_test_clamped) +
(1 - observed_test) * log(1 - p_test_clamped)
)
prediction_metrics <- data.frame(
metric = c(
"Accuracy", "Sensitivity", "Specificity", "Precision",
"Brier score", "Log loss"
),
value = c(
accuracy_test, sensitivity_test, specificity_test, precision_test,
brier_test, log_loss_test
)
)
prediction_metrics## metric value
## 1 Accuracy 0.97234255
## 2 Sensitivity 0.30000000
## 3 Specificity 0.99551879
## 4 Precision 0.69767442
## 5 Brier score 0.02354585
## 6 Log loss 0.08903948
Brier 分数是概率误差的均方,越小越好。Log loss 对自信但错误的概率预测惩罚很重,越小越好。它们直接评估概率;准确率、灵敏度、特异度和精确率则依赖所选阈值。
ROC 曲线展示阈值变化时灵敏度与假阳性率的关系。ROC AUC 衡量排序区分度,不衡量校准。AUC 很高并不表示预测概率等于实际事件率。
事件稀少时,精确率—召回率曲线尤其有信息。其精确率基线是事件发生率,不同于 ROC 图中的对角随机线。
下面的实现只在每个相同预测分数区段的末尾计算阈值点,因此能够正确处理并列分数。
binary_prediction_curves <- function(y, p) {
stopifnot(
length(y) == length(p),
all(y %in% c(0, 1)),
all(is.finite(p)),
sum(y == 1) > 0,
sum(y == 0) > 0
)
ordering <- order(p, decreasing = TRUE)
p_sorted <- p[ordering]
y_sorted <- y[ordering]
tp_cumulative <- cumsum(y_sorted == 1)
fp_cumulative <- cumsum(y_sorted == 0)
tie_end <- !duplicated(p_sorted, fromLast = TRUE)
tp_at_threshold <- tp_cumulative[tie_end]
fp_at_threshold <- fp_cumulative[tie_end]
thresholds <- p_sorted[tie_end]
positives <- sum(y == 1)
negatives <- sum(y == 0)
roc <- data.frame(
fpr = c(0, fp_at_threshold / negatives),
tpr = c(0, tp_at_threshold / positives),
threshold = c(Inf, thresholds)
)
pr <- data.frame(
recall = c(0, tp_at_threshold / positives),
precision = c(1, tp_at_threshold / (tp_at_threshold + fp_at_threshold)),
threshold = c(Inf, thresholds)
)
list(roc = roc, pr = pr)
}
curves_test <- binary_prediction_curves(observed_test, p_test)
roc_test <- curves_test$roc
pr_test <- curves_test$pr下面的梯形法利用单调递增的假阳性率序列计算经验 ROC 曲线下面积。
auc_test <- sum(
diff(roc_test$fpr) *
(head(roc_test$tpr, -1) + tail(roc_test$tpr, -1)) / 2
)
auc_test## [1] 0.9333264
ggplot(roc_test, aes(x = fpr, y = tpr)) +
geom_abline(intercept = 0, slope = 1, linetype = 2, color = "grey50") +
geom_line(color = "steelblue", linewidth = 1) +
coord_equal(xlim = c(0, 1), ylim = c(0, 1)) +
labs(
title = "Test-set ROC curve",
subtitle = paste("Trapezoidal AUC =", round(auc_test, 4)),
x = "False positive rate (1 - specificity)",
y = "True positive rate (sensitivity)"
)ggplot(pr_test, aes(x = recall, y = precision)) +
geom_hline(
yintercept = mean(observed_test),
linetype = 2,
color = "grey50"
) +
geom_line(color = "steelblue", linewidth = 1) +
coord_cartesian(xlim = c(0, 1), ylim = c(0, 1)) +
labs(
title = "Test-set precision-recall curve",
subtitle = "Dashed line: test-set event prevalence",
x = "Recall (sensitivity)",
y = "Precision"
)阈值应反映决策成本,并在训练集或验证集上确定,而不是为了在最终测试集上取得最好表现而选择。校准、区分度和临床或金融效用是不同性质。
普通 Poisson 似然比检验假设 Poisson 方差模型成立。存在明显过度离散时,名义卡方参照可能产生过于激进的 p 值。下面的比较用于展示 R 语法和模型差异;确认过度离散后,不能天真地解释这些结果。
anova(fit_gala, fit_gala_full, test = "LRT")## Analysis of Deviance Table
##
## Model 1: Species ~ Endemics + Area + Nearest
## Model 2: Species ~ Endemics + Area + Elevation + Nearest + Scruz + Adjacent
## Resid. Df Resid. Dev Df Deviance Pr(>Chi)
## 1 26 330.84
## 2 23 313.36 3 17.482 0.0005625 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
AIC(fit_gala, fit_gala_full)## df AIC
## fit_gala 4 499.6684
## fit_gala_full 7 488.1868
这里的 AIC 比较同一数据上的两个参数化 Poisson 拟合,不包含 quasi-Poisson 离散参数修正。quasi-Poisson 没有普通完整似然,因此没有普通 AIC。
残差平滑曲线弯曲可能来自遗漏的非线性项、遗漏预测变量、交互作用或影响点。样条是一种诊断性替代方案,不是自动修复办法。
fit_gala_spline <- update(
fit_gala,
. ~ Endemics + splines::ns(Area, df = 3) + Nearest
)
anova(fit_gala, fit_gala_spline, test = "LRT")## Analysis of Deviance Table
##
## Model 1: Species ~ Endemics + Area + Nearest
## Model 2: Species ~ Endemics + splines::ns(Area, df = 3) + Nearest
## Resid. Df Resid. Dev Df Deviance Pr(>Chi)
## 1 26 330.84
## 2 24 222.98 2 107.86 < 2.2e-16 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
AIC(fit_gala, fit_gala_spline)## df AIC
## fit_gala 4 499.6684
## fit_gala_spline 6 395.8094
只有 30 个岛屿时,增加灵活性必须权衡方差和稳定性。不能因为某种变换产生理想的 p 值就选择它。应绘制拟合关系并检查科学合理性。
影响点应触发数据核查和敏感性分析。下面代码识别最大 Cook 距离对应的观测,重新拟合排除该行后的模型并比较系数。主分析中的观测不会被静默删除。
most_influential_island <- diag_gala$island[which.max(diag_gala$cook)]
fit_gala_leave_one_out <- update(
fit_gala,
data = gala_data[gala_data$island != most_influential_island, ]
)
coefficient_sensitivity <- data.frame(
term = names(coef(fit_gala)),
full_model = coef(fit_gala),
leave_one_out = coef(fit_gala_leave_one_out)
)
coefficient_sensitivity$change <-
coefficient_sensitivity$leave_one_out - coefficient_sensitivity$full_model
most_influential_island## [1] "Isabela"
coefficient_sensitivity## term full_model leave_one_out change
## (Intercept) (Intercept) 2.8678751411 2.7778550554 -0.0900200857
## Endemics Endemics 0.0355078212 0.0405436376 0.0050358164
## Area Area -0.0000454177 -0.0005819772 -0.0005365595
## Nearest Nearest 0.0092886047 0.0099687311 0.0006801264
系数变化很大表示结论高度依赖一个观测。应检查数值是否错误、模型是否缺少结构,以及该观测是否属于科学上不同的子群。
以下情况应考虑更多建模:
负二项、零膨胀或 hurdle、混合效应模型分别处理不同问题。它们不是“过度离散”的可互换同义词,每种模型都需要自己的诊断与解释。
原讲义跳过了最后率模型的诊断。这里使用同样的结构化流程:检查残差模式、随机分位数残差、异常观测、影响点和离散程度。offset 改变期望计数尺度,但不会消除诊断的必要性。
set.seed(303)
diag_rate <- data.frame(
observation = seq_len(nobs(fit_rate)),
group = paste(cancer_data$city, cancer_data$age, sep = " / "),
eta = predict(fit_rate, type = "link"),
quantile = statmod::qresid(fit_rate),
std_deviance = rstandard(fit_rate, type = "deviance"),
leverage = hatvalues(fit_rate),
cook = cooks.distance(fit_rate)
)ggplot(diag_rate, aes(x = eta, y = quantile)) +
geom_point() +
geom_hline(yintercept = 0, linetype = 2, color = "grey50") +
geom_smooth(method = "loess", se = FALSE, formula = y ~ x, span = 0.9) +
labs(
title = "Rate-model quantile residuals versus the linear predictor",
x = expression(paste("Fitted linear predictor, ", hat(eta))),
y = "Randomized quantile residual"
)ggplot(diag_rate, aes(sample = quantile)) +
stat_qq() +
stat_qq_line(color = "red") +
labs(
title = "Q-Q plot for the rate model",
x = "Theoretical normal quantiles",
y = "Sample quantiles"
)只有 24 个城市—年龄组,因此图形和数值标记都应谨慎解释。group 标签同时包含城市和年龄,便于追踪被标记的观测。
leverage_threshold_rate <- 2 * length(coef(fit_rate)) / nobs(fit_rate)
cook_threshold_rate <- 4 / nobs(fit_rate)
ggplot(diag_rate, aes(x = observation, y = cook)) +
geom_point() +
geom_hline(
yintercept = cook_threshold_rate,
linetype = 2,
color = "red"
) +
geom_text(
data = diag_rate[diag_rate$cook > cook_threshold_rate, ],
aes(label = group),
vjust = -0.6,
size = 3,
check_overlap = TRUE
) +
labs(
title = "Cook's distance for the rate model",
x = "Observation",
y = "Cook's distance"
)rate_flags <- diag_rate[
abs(diag_rate$std_deviance) > 2 |
diag_rate$leverage > leverage_threshold_rate |
diag_rate$cook > cook_threshold_rate,
]
rate_flags## observation group eta quantile std_deviance leverage
## 2 2 Horsens / 40-54 2.003074 1.994804 2.261199 0.3286998
## 3 3 Kolding / 40-54 2.049004 -1.346489 -1.848879 0.3509565
## 10 10 Horsens / 60-64 2.384117 1.169152 1.528771 0.3937242
## 22 22 Horsens / 75+ 2.119384 -2.420076 -3.326994 0.3723796
## 23 23 Kolding / 75+ 1.906766 1.972143 2.218757 0.3219538
## cook
## 2 0.3414624
## 3 0.1686580
## 10 0.1889755
## 22 0.5048607
## 23 0.3208806
不要把 residual deviance 除以其自由度当成机械的通过/不通过检验。应综合考察离散程度、残差模式、影响点和研究设计。
优势与概率。 基线概率为 0.10,优势比为
2。新概率是多少?
答案: 基线优势为
;翻倍后为
;新概率为
。概率没有翻倍。
尺度转换。 Logistic 的 balance
系数以每个货币单位估计。如何得到 100 个单位的优势比?
答案: 计算
,不是
,也不是概率变化。
预测类型。 Logistic 模型中,哪个
predict() 类型返回对数优势?
答案:
type="link";type="response"
返回概率。
符号变化。 为什么 studentYes 在仅含
student 的模型和调整模型中可能符号相反?
答案: 两者估计不同的边际关联和条件关联,而且不同
student 状态的 balance 分布不同。
Probit 单位。 预测概率从 0.20 增加到
0.26。绝对变化是多少?
答案: 0.06,即 6 个百分点。相对增加为
。
Poisson 解释。 log 链接 Poisson
模型中,
表示什么?
答案:
其他模型项不变时,
增加一个单位,期望计数乘以该值;存在暴露量 offset
时,对应期望率的乘法变化。
Quasi-Poisson。 系数、标准误和普通 AIC
哪些会改变?
答案: 同一均值模型的系数不变;标准误乘以
;普通
AIC 不可用。
Offset。
协变量不变而暴露量翻倍时,期望计数和期望率如何变化?
答案: 期望计数翻倍;期望率不变。
诊断。
对于以线性项进入模型的预测变量,
对该变量的图为直线,能否证明线性假设?
答案:
不能,这是模型公式决定的。应检查残差模式和灵活替代模型。
预测。 ROC AUC
很高的模型是否仍可能校准很差?
答案: 是。排序区分度和概率校准是不同性质。
fit_default,验证拟合概率不变。fit_gala,比较系数和预测计数。报告 GLM 之前,逐项检查:
sessionInfo()## R version 4.5.1 (2025-06-13 ucrt)
## Platform: x86_64-w64-mingw32/x64
## Running under: Windows 11 x64 (build 26200)
##
## Matrix products: default
## LAPACK version 3.12.1
##
## locale:
## [1] LC_COLLATE=Chinese (Simplified)_China.utf8
## [2] LC_CTYPE=Chinese (Simplified)_China.utf8
## [3] LC_MONETARY=Chinese (Simplified)_China.utf8
## [4] LC_NUMERIC=C
## [5] LC_TIME=Chinese (Simplified)_China.utf8
##
## time zone: Asia/Shanghai
## tzcode source: internal
##
## attached base packages:
## [1] stats graphics grDevices utils datasets methods base
##
## other attached packages:
## [1] ggplot2_3.5.2
##
## loaded via a namespace (and not attached):
## [1] sandwich_3.1-3 generics_0.1.4 ISLR_1.4 lattice_0.22-7
## [5] lme4_1.1-37 magrittr_2.0.3 evaluate_1.0.4 grid_4.5.1
## [9] RColorBrewer_1.1-3 Matrix_1.7-3 Formula_1.2-5 survival_3.8-3
## [13] mgcv_1.9-3 scales_1.4.0 abind_1.4-8 reformulas_0.4.1
## [17] faraway_1.0.9 Rdpack_2.6.4 cli_3.6.5 rlang_1.1.6
## [21] rbibutils_2.3 splines_4.5.1 withr_3.0.2 yaml_2.3.10
## [25] tools_4.5.1 nloptr_2.2.1 minqa_1.2.8 dplyr_1.1.4
## [29] boot_1.3-31 vctrs_0.6.5 R6_2.6.1 zoo_1.8-14
## [33] lifecycle_1.0.4 car_3.1-3 MASS_7.3-65 pkgconfig_2.0.3
## [37] pillar_1.11.0 gtable_0.3.6 glue_1.8.0 Rcpp_1.1.0
## [41] statmod_1.5.0 xfun_0.52 tibble_3.3.0 lmtest_0.9-40
## [45] tidyselect_1.2.1 knitr_1.50 farver_2.1.2 nlme_3.1-168
## [49] labeling_0.4.3 carData_3.0-5 compiler_4.5.1 ISwR_2.0-12
## [53] AER_1.2-17
让学生不看输出,完成以下四句话:
coef() 位于 ______
尺度,exp(coef()) 给出 ______。exp(coef()) 表示 ______
的乘法变化。offset(log(exposure))
的系数固定为 ______。参考答案:对数优势;优势比;6;期望均值或率,视具体项而定;计数;1。
最后不要给学生留下“选择 p 值最小的模型”这种印象。应强调:先明确响应与暴露量,再识别解释尺度,使用基于模型的诊断,并以有实际意义的单位报告预测及不确定性。
课程最后保留以下四组对应关系:
| 原讲义问题 | 为什么需要修正或补充 | 本文档的处理 |
|---|---|---|
将 mtcars 说成来自 dplyr |
它实际来自 datasets |
已更正,并降为可选语法示例 |
| 讲优势比时没有回答概率如何变化 | 优势与概率之间是非线性关系 | 加入基线概率换算公式与课堂检查 |
| 将连续变量系数称为弹性 | 这不是通常 log–log 模型中的弹性 | 改为对数优势变化和局部概率斜率 |
| 将 p 值当作预测重要性或删变量规则 | 统计显著性与预测目标不同 | 加入尺度转换、调整分析和建模目标提醒 |
| 强调二分类模型的残差正态性 | Bernoulli 数据不要求残差正态 | 分残差类型解释,并加入随机分位数残差 |
用
对 balance 的图证明线性 |
该直线由模型公式机械决定 | 改为残差平滑图和样条比较 |
| 将 Probit 的概率变化写成 6.1% | 0.061 的概率差是 6.1 个百分点 | 更正单位,并区分相对百分比变化 |
| 仅凭计数右偏就称为近似 Poisson | 边际右偏不能验证条件 Poisson 模型 | 加入条件均值—方差关系 |
| 用原始响应检查回归中的过度离散 | 回归中每个观测有不同的拟合均值 | 改为拟合模型的 Pearson 离散参数 |
| 将 quasi-Poisson 当作通用解决办法 | 它调整不确定性,不修正均值模型 | 加入局限及 AIC 不可用的原因 |
使用未定义的 cooksD |
代码不能独立运行 | 明确调用 cooks.distance() |
| 率模型的数据整理依赖外部向量 | 代码脆弱,也掩盖暴露量含义 | 在模型公式中使用 offset(log(pop)) |
| 混合预测、分类和诊断 | 估计、阈值选择与验证是不同任务 | 分开讲解概率、诊断、校准和验证 |
This page reproduces the Quarto-rendered teaching document generated by DeepSeek 4.1 Flash; all code, outputs and figures are the original ones.
本页由 DeepSeek 4.1 Flash 依据课程 Quarto 讲义(已渲染版)重新排版,代码、输出与图均保留原内容。