Downloading packages
required_packages <- c("rmarkdown", "tidyverse", "broom", "arm", "pROC",
"jtools", "rpart", "ISLR", "rattle","ggplot2","ggrepel","dplyr","wesanderson","interactions","readr","here")
# installed.packages() is a data frame with info about
# versions and other things we don't need.
installed_packages <- rownames(installed.packages())
# Which ones are required but not installed?
to_install <- setdiff(required_packages, installed_packages)
# Install them.
install.packages(to_install)
Part 1: Plotting Linear Model Results We will be using the mpg dataset in the ggplot2 package. Familiarise yourself with its variables by looking at its help.
Consider the following linear model fit, predicting highway fuel economy as a function of engine displacement per cylinder (essentially the volume of each cylinder) and the number of cylinders:
##加载包和数据集
library(ggplot2)
data(mpg)
##进行拟合线性回归,I()包裹以运算,factor()转换为分类变量
lmfit <- lm(hwy ~ I(displ/cyl) + factor(cyl), data = mpg)
##加载包,加载 broom 包,该包提供了方便的工具来处理统计模型的输出,加载 ggrepel,该包用于在图中添加不会重叠的文本标签
library(broom)
library(ggrepel)
##使用 broom 包的 augment 函数,将线性模型 lmfit 的预测值和残差附加到数据框 mpg 中,生成一个新的数据框 mpgaug
mpgaug <- augment(lmfit, mpg)
##mpgaug$.std.resid:标准化残差,abs():取残差的绝对值,rank():对残差绝对值按从大到小排序(通过 -abs() 实现降序,<= 3:选取排序中绝对值最大的前三个残差。
high_abs_resid <- rank(-abs(mpgaug$.std.resid)) <= 3
##x = .fitted:X 轴为模型的拟合值,y = .resid:Y 轴为残差,label:对于残差最大的三个点,使用其序号作为标签;其他点不显示标签(NA)
##ifelse():根据条件 high_abs_resid(是否为残差最大的三个点),返回序列值(例如 1, 2, 3)或 NA。
ggplot(mpgaug, aes(x = .fitted, y = .resid,
label = ifelse(high_abs_resid,
seq_along(high_abs_resid), NA))) +
##画散点图
geom_point() +
##添加平滑曲线,不显示置信区间
geom_smooth(se = FALSE) +
##使用 ggrepel 包自动调整文本标签,避免标签与点或其他标签重叠
geom_text_repel() +
##标注
labs("Residuals vs. Fitted Plot",
x = "Fitted values",
y = "Residual")
## `geom_smooth()` using method = 'loess' and formula = 'y ~ x'
## Warning: The following aesthetics were dropped during statistical transformation: label.
## ℹ This can happen when ggplot fails to infer the correct grouping structure in
## the data.
## ℹ Did you forget to specify a `group` aesthetic or to convert a numerical
## variable into a factor?
## Warning: Removed 231 rows containing missing values or values outside the scale range
## (`geom_text_repel()`).
##sample选定样本,.std.resid:标准化残差,表示残差已经按标准正态分布的标准化(均值 0,标准差 1)
ggplot(mpgaug, aes(sample = .std.resid)) +
##QQ图
geom_qq() +
##QQ图参考线
geom_qq_line() +
#标题
ggtitle("Normal Q-Q Plot")
##同上图,y更改为sqrt(abs(.std.resid)),标准正态化后残差绝对值的平方
ggplot(mpgaug, aes(x = .fitted, y = sqrt(abs(.std.resid)),
label = ifelse(high_abs_resid,
seq_along(high_abs_resid), NA))) +
geom_point() +
geom_smooth(se = FALSE) +
geom_text_repel() +
labs(title = "Scale-Location Plot",
x = "Fitted values",
y = expression(sqrt(abs("Std. Residual"))))
## `geom_smooth()` using method = 'loess' and formula = 'y ~ x'
## Warning: The following aesthetics were dropped during statistical transformation: label.
## ℹ This can happen when ggplot fails to infer the correct grouping structure in
## the data.
## ℹ Did you forget to specify a `group` aesthetic or to convert a numerical
## variable into a factor?
## Warning: Removed 231 rows containing missing values or values outside the scale range
## (`geom_text_repel()`).
##标记出绝对值最大的三个cook距离点
high_cook <- rank(-abs(mpgaug$.cooksd)) <= 3
##ggplot2,X 轴是杠杆值(Leverage),表示每个点对自变量变化的敏感性
##size = .cooksd:点的大小由 Cook's Distance 决定。
ggplot(mpgaug, aes(x = .hat, y = .std.resid, size = .cooksd,
label = ifelse(high_cook, seq_along(high_cook), NA))) +
geom_point() +
geom_text_repel() +
labs(title = "Cook's Distance",
x = "Leverage", y = "Pearson residual")
## Warning: Removed 232 rows containing missing values or values outside the scale range
## (`geom_text_repel()`).
(b)Use either broom tools or some other package to plot parameter estimates and confidence intervals for the model fit (i.e. a forest plot). The hand-generated plot may look something like this:
##加载管道符包
library(dbplyr)
##从回归lm中提取系数,conf.int = TRUE:时提取系数的置信区间(conf.low 和 conf.high)
tidy(lmfit, conf.int = TRUE) %>%
##y为变量名,X 轴为每个项的估计系数,xmin = conf.low,xmax = conf.high:X 轴置信区间的范围
ggplot(aes(y = term, x = estimate, xmin = conf.low, xmax = conf.high)) +
geom_point() +
##geom_errorbar(width = 0.1):添加误差条,表示每个系数的置信区间,labs(y = NULL):删除 Y 轴标签
geom_errorbar(width = .1) + labs(y = NULL) +
##scale_y_discrete(limits = rev)
scale_y_discrete(limits = rev)
The plots may look something like this:
##interval = "confidence":要求生成置信区间(confidence interval),即 .fitted(拟合值)、.lower(置信区间下限)和 .upper(置信区间上限)
augment(lmfit, mpg, interval = "confidence") %>%
ggplot(aes(x = displ/cyl, y = hwy,
##fill = factor(cyl) 和 col = factor(cyl):将汽缸数量(cyl)映射为颜色和填充(用于区分分类变量 cyl)
fill = factor(cyl), col = factor(cyl))) +
##为点添加随机抖动,避免点完全重叠
geom_point(position = "jitter") +
##绘制置信区间带,显示 .lower 和 .upper 的范围,alpha = 0.2:设置透明度,color = FALSE:边框颜色设为无
geom_ribbon(aes(ymin = .lower, ymax = .upper), alpha = 0.2, color = FALSE) +
##geom_line():绘制拟合线,显示模型预测的趋势
geom_line(aes(y = .fitted)) +
labs(x = "Displacement per cylinder",
y = "Highway fuel efficiency",
col = "Cylinders",
fill = "Cylinders")
The plot should look something like this:
##重新进行回归模型
lmfit2 <- lm(hwy ~ cty + displ + year, data = mpg)
library(jtools)
##绘制回归模型中某个自变量的影响图,图中会显示 cty 对 hwy 的边际影响,显示置信区间,显示偏残差
jtools::effect_plot(lmfit2, pred = cty,
interval = TRUE, partial.residuals = TRUE)
Yes, the line fits the relationship between cty and hwy. This isn’t
surprising that there is a close linear relationship between city
efficiency and highway efficiency, as they are both likely functions of
the same car attributes (engine properties, car weight, etc).
Although you can use a built-in function to create this plot, it would be better to create it by hand to better understand interaction terms! Try creating the lines yourself by calculating the intercept and slope terms for each line by hand. If you create the plot yourself, check it against a built-in function.
Here is an example of a plot made by hand:
library(dplyr)
##
## 载入程序包:'dplyr'
## The following objects are masked from 'package:dbplyr':
##
## ident, sql
## The following objects are masked from 'package:stats':
##
## filter, lag
## The following objects are masked from 'package:base':
##
## intersect, setdiff, setequal, union
mtcars <- mtcars %>%
##将 am 的值从 0 或 1 转为索引值 1 或 2,am = 0 对应 c("automatic", "manual")[1],即 "automatic"
##am = 1 对应 c("automatic", "manual")[2],即 "manual"
mutate(Transmission = c("automatic", "manual")[am + 1])
##变速箱类型与发动机排量的双重影响的线性回归
lmfit.mtcars <- lm(mpg ~ Transmission*disp, data = mtcars)
# 提取回归系数
coef.vec <- coef(lmfit.mtcars)
## intercept.am0:自动变速箱的回归线截距,intercept.am1:手动变速箱的回归线截距(自动变速箱截距 + 截距调整值)
##slope.am0:自动变速箱的回归线斜率(排量的系数)slope.am1:手动变速箱的回归线斜率(自动变速箱斜率 + 斜率调整值)
intercept.am0 <- coef.vec[1]
intercept.am1 <- intercept.am0 + coef.vec[2]
slope.am0 <- coef.vec[3]
slope.am1 <- slope.am0 + coef.vec[4]
# 选择配色方案,调用"Fantastic Mr. Fox" 电影的配色方案1和3
library(wesanderson)
plot.colours <- wes_palette("FantasticFox1")[c(1,3)]
#添加发动起排量与燃油效率散点图,按照手自动挡设置颜色
ggplot(mtcars, aes(x = disp, y = mpg, colour = Transmission)) +
geom_point() +
##添加回归线
geom_abline(intercept = intercept.am0, slope = slope.am0, colour = plot.colours[1]) +
geom_abline(intercept = intercept.am1, slope = slope.am1, colour = plot.colours[2]) +
##手动设置颜色映射,Transmission 的颜色使用 plot.colours
scale_colour_manual(values = plot.colours) +
##设置图形为简约主题,提升视觉效果
theme_minimal()
##加载interactions:一个专门用于交互效应可视化的 R 包
library(interactions)
##设置预测变量为disp(发动机排量),调节变量为(变速箱类型),在图中显示实际数据点,以便与拟合结果进行对比
interact_plot(lmfit.mtcars, pred = disp, modx = Transmission, plot.points = TRUE)
Part 2: Logistic regression (a) Fit a logistic regression model of
whether a student holds a scholarship (Scholarship holder) on Admission
grade, Age at enrolment, and Marital status. Create a binned diagnostic
residual plot. Make sure to include a horizontal line at 0 as a
reference line.
The plot should look something like this:
##加载包
library(readr)
library(here)
## here() starts at C:/Users/Winst/Desktop/DATA5002/lab/lab3
#确认文件目录
getwd()
## [1] "C:/Users/Winst/Desktop/DATA5002/lab/lab3"
#加载数据集,并根据“;”进行数据划分,并导出为frame格式
students <- read_delim(here::here("data", "student_success.csv"), delim = ";")
## Rows: 4424 Columns: 37
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ";"
## chr (1): Target
## dbl (36): Marital status, Application mode, Application order, Course, Dayti...
##
## ℹ Use `spec()` to retrieve the full column specification for this data.
## ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
##以因变量是否为奖学金持有者,自变量为入学年龄,婚姻状况做广义线性回归,因为因变量为0,1变量,因此选择二分法
logis.fit <- glm(
`Scholarship holder` ~ `Age at enrollment` + `Marital status`,
data = students,
family = "binomial"
)
#加载arm 是 R 包,提供高级建模诊断和绘图工具
library(arm)
## 载入需要的程序包:MASS
##
## 载入程序包:'MASS'
## The following object is masked from 'package:dplyr':
##
## select
## 载入需要的程序包:Matrix
## 载入需要的程序包:lme4
##
## arm (Version 1.14-4, built: 2024-4-1)
## Working directory is C:/Users/Winst/Desktop/DATA5002/lab/lab3
##
## 载入程序包:'arm'
## The following object is masked from 'package:jtools':
##
## standardize
#绘制分箱残差图,检查模型拟合效果,填入模型,残差计算方式为响应
binnedplot(fitted(logis.fit), residuals(logis.fit, type = "response"),
#绘制xlab,x为平均拟合概率
xlab = "Averaged fitted probabilities",
#绘制ylab,y为平均残差
ylab = "Averaged residuals",
#点的样式(19 表示实心圆点),点的颜色为红色,点的大小为 1.5 倍默认值
pch = 19, col.pts = "red", cex.pts = 1.5,
#图的标题为 "Binned residuals vs fitted plot for linear fit"
main = "Binned residuals vs fitted plot for linear fit")
#绘制水平线,位置为0,线为虚线,颜色为绿色
abline(h = 0, lty = 2, col = "green")
(b) Create a ROC curve using your predicted values. Make sure to add a
reference line for the performance of a random classifier.
The plot should look something like this:
# 加载Proc曲线包
library(pROC)
## Type 'citation("pROC")' for a citation.
##
## 载入程序包:'pROC'
## The following objects are masked from 'package:stats':
##
## cov, smooth, var
# 定义roc.logis为曲线,分类标签为是否得到奖学金,预测概率
roc.logis <- roc(students$`Scholarship holder`, predict(logis.fit))
## Setting levels: control = 0, case = 1
## Setting direction: controls < cases
#绘制曲线图,颜色,曲线线条宽度,确保 X 轴表示假阳性率(FPR),Y 轴表示真阳性率(TPR)
ggroc(roc.logis, colour = "steelblue", size = 2, legacy.axes = TRUE) +
#标题
ggtitle("ROC Curve for logistic fit") +
#添加一条虚线从 (0, 0) 到 (1, 1),这条对角线表示随机猜测的模型性能(即没有区分能力的模型)
geom_segment(aes(x = 0, xend = 1, y = 0, yend = 1), linetype = "dashed")
## Warning in geom_segment(aes(x = 0, xend = 1, y = 0, yend = 1), linetype = "dashed"): All aesthetics have length 1, but the data has 139 rows.
## ℹ Please consider using `annotate()` or provide this layer with data containing
## a single row.
Part 3: Visualising Uncertainty In this part, we will practise different ways of visualising uncertainty. We will be using the mpg dataset in the ggplot2 package. Familiarise yourself with its variables by looking at its help. (a) For each class of vehicle (class), plot confidence intervals for the mean highway fuel efficiency (hwy) (in miles per gallon) over the models. The plot should look something like this:
mpg.means <- mpg %>%
##按 class(车辆类别)分组
group_by(class) %>%
##对每个类别的 hwy 值执行单样本 t 检验,假设均值为 0,将 t 检验的结果格式化为数据框(来自 broom 包),将每组的 t 检验结果合并到一个新的数据框 mpg.means 中
summarise(tidy(t.test(hwy)))
##绘制散点图
ggplot(mpg.means, aes(x = estimate, y = class)) +
geom_point() +
##添加置信区间,与设置误差条的横向宽度
geom_errorbar(aes(xmin = conf.low, xmax = conf.high), width = .1) +
#添加标签
labs(x = "Fuel Efficiency (miles per gallon)", y = "Vehicle Class")
mpg %>%
group_by(class) %>%
summarise(tidy(t.test(hwy))) %>%
##加入重新排序,根据估计值对class进行排序
mutate(class = reorder(class, estimate)) %>%
ggplot(aes(x = estimate, y = class)) +
geom_point() +
geom_errorbar(aes(xmin = conf.low, xmax = conf.high), width = .1) +
labs(x = "Fuel Efficiency (miles per gallon)", y = "Vehicle Class")
Part 4: Classification trees For this part, we will be using dataset OJ
from the ISRL package. This dataset contains information about customer
decision to purchase a one of two brands of orange juice (Citrus Hill or
Minute Maid), as well as various information about the pricing and the
promotion of the two brands, the stores where they were purchased and
when, and customer loyalty. Please use R help to familiarise yourself
with it.
A marketing manager may be interested in predicting the customer decision as a function of the prince of the juice and that charged by their nearest competitor, as well as impact of discounts and promotions. Thus, we will focus on those predictors, as opposed to those related to store and week of purchase.
(a)Fit a classification tree for customer purchase decision as a function of the price, price difference, discount, and promotion data (i.e., excluding week of purchase, customer loyalty, and store information). Print the tree results.
##加载 ISLR 数据集包,加载决策树模型包,用于构建分类和回归树
library(ISLR)
library(rpart)
#加载 OJ 数据集,包含有关橙汁购买行为的变量
data(OJ)
##rpart():构建决策树模型,加入所有自变量
OJPrice <- rpart(
Purchase ~ PriceCH + PriceMM + DiscCH + DiscMM +
SpecialCH + SpecialMM + SalePriceMM + SalePriceCH +
PriceDiff + PctDiscMM + PctDiscCH + ListPriceDiff,
data = OJ
)
##展示结果
OJPrice
## n= 1070
##
## node), split, n, loss, yval, (yprob)
## * denotes terminal node
##
## 1) root 1070 417 CH (0.6102804 0.3897196)
## 2) PriceDiff>=0.015 756 239 CH (0.6838624 0.3161376) *
## 3) PriceDiff< 0.015 314 136 MM (0.4331210 0.5668790)
## 6) PriceDiff>=-0.39 254 123 MM (0.4842520 0.5157480)
## 12) PctDiscMM>=0.109423 175 79 CH (0.5485714 0.4514286)
## 24) SpecialMM< 0.5 106 40 CH (0.6226415 0.3773585) *
## 25) SpecialMM>=0.5 69 30 MM (0.4347826 0.5652174)
## 50) PriceCH< 1.755 26 9 CH (0.6538462 0.3461538) *
## 51) PriceCH>=1.755 43 13 MM (0.3023256 0.6976744) *
## 13) PctDiscMM< 0.109423 79 27 MM (0.3417722 0.6582278) *
## 7) PriceDiff< -0.39 60 13 MM (0.2166667 0.7833333) *
##加载可视化决策树模型包
library(rattle)
## 载入需要的程序包:tibble
## 载入需要的程序包:bitops
##
## 载入程序包:'bitops'
## The following object is masked from 'package:Matrix':
##
## %&%
## Rattle: A free graphical interface for data science with R.
## XXXX 5.5.1 Copyright (c) 2006-2021 Togaware Pty Ltd.
## 键入'rattle()'去轻摇、晃动、翻滚你的数据。
##可视化决策树模型,不添加子标题
fancyRpartPlot(OJPrice, sub = "")