library(rpart) # fit trees
library(rpart.plot) # draw trees
library(randomForest) # fit forests
## randomForest 4.7-1.2
## Type rfNews() to see new features/changes/bug fixes.
library(pROC) # ROC and AUC
## Type 'citation("pROC")' for a citation.
##
## Attaching package: 'pROC'
## The following objects are masked from 'package:stats':
##
## cov, smooth, var
library(caret) # split, tune, confusion matrix
## Loading required package: ggplot2
##
## Attaching package: 'ggplot2'
## The following object is masked from 'package:randomForest':
##
## margin
## Loading required package: lattice
els_file <- file.path("/Users/xutianyu/Downloads/els_02_12_byf3pststu_v1_0.rdata")
load(els_file)
els <- els_02_12_byf3pststu_v1_0
names(els) <- toupper(names(els))
dim(els) # students, columns
## [1] 16197 4012
keepvars <- c(
"STU_ID", "F2EVERDO",
"BYTXMSTD", "BYTXRSTD",
"BYS42", "BYP52E", "BYS24F",
"F2PS0601", "F1RGPP2",
"BYS33A", "F1S27","BYP51",
"F3TZSTEM1CRED", "F3TZSTEM1TOT","F3TZSTEM2GPA",
"F3STEMOCCCUR")
ROC <- els[keepvars]
ROC <- naniar::replace_with_na_if(
ROC,
.predicate = is.numeric, # select numeric columns
condition = ~ .x < 0 # negative values become NA
)
summary(ROC)
## STU_ID F2EVERDO BYTXMSTD BYTXRSTD
## Min. :101101 Min. :0.000 Min. :19.38 Min. :22.57
## 1st Qu.:190106 1st Qu.:0.000 1st Qu.:44.07 1st Qu.:43.64
## Median :281116 Median :0.000 Median :50.83 Median :50.91
## Mean :279543 Mean :0.113 Mean :50.71 Mean :50.53
## 3rd Qu.:369205 3rd Qu.:0.000 3rd Qu.:57.82 3rd Qu.:57.56
## Max. :461234 Max. :1.000 Max. :86.68 Max. :78.76
## NA's :305 NA's :305
## BYS42 BYP52E BYS24F F2PS0601
## Min. : 0.000 Min. :1.000 Min. :1.000 Min. :0.000
## 1st Qu.: 0.000 1st Qu.:1.000 1st Qu.:1.000 1st Qu.:1.000
## Median : 2.000 Median :1.000 Median :1.000 Median :1.000
## Mean : 4.773 Mean :1.199 Mean :1.105 Mean :1.062
## 3rd Qu.:10.000 3rd Qu.:1.000 3rd Qu.:1.000 3rd Qu.:2.000
## Max. :21.000 Max. :4.000 Max. :5.000 Max. :4.000
## NA's :1751 NA's :3911 NA's :1721 NA's :5686
## F1RGPP2 BYS33A F1S27 BYP51
## Min. :0.000 Min. :0.0000 Min. :1.000 Min. :0.0000
## 1st Qu.:3.000 1st Qu.:0.0000 1st Qu.:1.000 1st Qu.:0.0000
## Median :4.000 Median :0.0000 Median :3.000 Median :0.0000
## Mean :3.912 Mean :0.1824 Mean :3.182 Mean :0.0725
## 3rd Qu.:5.000 3rd Qu.:0.0000 3rd Qu.:5.000 3rd Qu.:0.0000
## Max. :6.000 Max. :1.0000 Max. :8.000 Max. :1.0000
## NA's :1401 NA's :1829 NA's :2124 NA's :3740
## F3TZSTEM1CRED F3TZSTEM1TOT F3TZSTEM2GPA F3STEMOCCCUR
## Min. :0.0000 Min. : 0.000 Min. :0.000 Length:16197
## 1st Qu.:0.0000 1st Qu.: 3.000 1st Qu.:2.000 Class :character
## Median :0.0000 Median : 6.000 Median :2.750 Mode :character
## Mean :0.1825 Mean : 9.257 Mean :2.586
## 3rd Qu.:0.0000 3rd Qu.:11.000 3rd Qu.:3.250
## Max. :2.0000 Max. :56.000 Max. :4.000
## NA's :9261 NA's :4657 NA's :5442
#Math t score
ROC$BYTXMSTD_01 = ifelse(ROC$BYTXMSTD < 44.065, 1, 0)
#Reading t score
ROC$BYTXRSTD_01 = ifelse(ROC$BYTXRSTD < 43.64, 1, 0)
#compare AUC for math and reading scores
roc1 = roc(ROC$F2EVERDO, ROC$BYTXMSTD_01, legacy.axes=TRUE, asp=FALSE,
plot=TRUE, grid=FALSE, lty=1, xaxs="i", yaxs="i", main = "ROC curves for predicting dropout: Comparison")
## Setting levels: control = 0, case = 1
## Setting direction: controls < cases
roc2 = roc(ROC$F2EVERDO, ROC$BYTXRSTD_01,
plot=TRUE, add=TRUE, percent=roc1$percent, lty=2)
## Setting levels: control = 0, case = 1
## Setting direction: controls < cases
legend("bottomright", legend=c("Math t score (2002)","Reading t score (2002)"), lty=c(1,2), lwd=2)
roc.test(roc1, roc2, method="delong") #select math t score with bigger AUC
##
## DeLong's test for two correlated ROC curves
##
## data: roc1 and roc2
## Z = 1.7462, p-value = 0.08078
## alternative hypothesis: true difference in AUC is not equal to 0
## 95 percent confidence interval:
## -0.00133231 0.02309384
## sample estimates:
## AUC of roc1 AUC of roc2
## 0.6472583 0.6363775
For this step, I relabeled some variables based on the descriptions in Appendix A, to match the workflow in Bowers & Zhou (2019) html.
#Dichotomize the Balfanz et al. flags
# BYP52E: school contacted parent about poor attendance
# Original codes: 1 = None; 2 = Once or twice; 3 = Three or four times; 4 = More than four times
# New: 1 = School contacted parent about poor attendance 1-4 times (codes 2-4), 0 = None (code 1)
ROC$BYP52E_01 <- ifelse(ROC$BYP52E %in% 2:4, 1,
ifelse(ROC$BYP52E == 1, 0, NA))
# BYS24F: how many times suspended/put on probation
# Original codes: 1 = Never; 2 = 1-2 times; 3 = 3-6 times; 4 = 7-9 times; 5 = 10 or more times
# New: 1 = Suspended/put on probation 1-5 times (codes 2-5), 0 = Never (code 1)
ROC$BYS24F_01 <- ifelse(ROC$BYS24F %in% 2:5, 1,
ifelse(ROC$BYS24F == 1, 0, NA))
# BYTXMSTD: 1 = Math test standardized score below 1st quantile (cutoff 44.065), 0 = otherwise
ROC$BYTXMSTD_01 <- ifelse(ROC$BYTXMSTD < 44.065, 1, 0)
# BYP51: already 0/1, 1 = Ever had behavior problem at school (no recode needed)
# F2PS0601: postsecondary enrollment, codes 0-4 (1 = 4-year institution)
# New: 1 = Enrolled in a 4-yr institution (code 1), 0 = codes 0, 2, 3, 4; negative codes stay NA
ROC$F2PS0601_01 <- ifelse(ROC$F2PS0601 == 1, 1,
ifelse(ROC$F2PS0601 %in% c(0, 2, 3, 4), 0, NA))
# Value labels for reference
attr(ROC$BYP52E_01, "label") <- "1=School contacted parent about poor attendance 1-4 times"
attr(ROC$BYS24F_01, "label") <- "1=Suspended/put on probation 1-5 times"
attr(ROC$BYTXMSTD_01, "label") <- "1=Math test standardized score below 1st quantile"
# Check the recodes against the original codes
table(ROC$BYP52E, ROC$BYP52E_01, useNA = "ifany")
##
## 0 1 <NA>
## 1 10694 0 0
## 2 0 1037 0
## 3 0 262 0
## 4 0 293 0
## <NA> 0 0 3911
table(ROC$BYS24F, ROC$BYS24F_01, useNA = "ifany")
##
## 0 1 <NA>
## 1 13308 0 0
## 2 0 961 0
## 3 0 119 0
## 4 0 29 0
## 5 0 59 0
## <NA> 0 0 1721
table(ROC$BYTXMSTD_01, useNA = "ifany")
##
## 0 1 <NA>
## 11919 3973 305
individual_flags <- c("BYP52E_01", "BYTXMSTD_01", "BYS24F_01", "BYP51")
flag_ones <- rowSums(ROC[individual_flags] == 1, na.rm = TRUE) # flags observed as 1
flag_nas <- rowSums(is.na(ROC[individual_flags])) # flags missing
# flag_00: 1 = One or more flags; 0 = no observed flag (all students kept)
ROC$flag_00 <- as.integer(flag_ones >= 1)
# flag_01 - flag_04: 1 = student has at least k flags;
# 0 = student cannot reach k flags even if the missing ones were 1;
# NA = not determinable because of missing flags
make_flag <- function(k) ifelse(flag_ones >= k, 1,
ifelse(flag_ones + flag_nas < k, 0, NA))
ROC$flag_01 <- make_flag(1) # Any one flag
ROC$flag_02 <- make_flag(2) # Any two flags
ROC$flag_03 <- make_flag(3) # Any three flags
ROC$flag_04 <- make_flag(4) # All four flags
table(flag_ones, flag_nas)
## flag_nas
## flag_ones 0 1 2 3 4
## 0 7500 560 1586 594 238
## 1 2784 260 967 184 0
## 2 916 89 181 0 0
## 3 269 14 0 0 0
## 4 55 0 0 0 0
# High school dropout with dichotomous predictors
mean(ROC$F2EVERDO); sd(ROC$F2EVERDO); length(ROC$F2EVERDO) # Dropout
## [1] 0.1129839
## [1] 0.3165829
## [1] 16197
BYP52E=na.omit(ROC$BYP52E_01); mean(BYP52E); sd(BYP52E); length(BYP52E); # Absent
## [1] 0.1295784
## [1] 0.3358527
## [1] 12286
BYS24F=na.omit(ROC$BYS24F_01); mean(BYS24F); sd(BYS24F); length(BYS24F); # Suspension
## [1] 0.08068527
## [1] 0.2723606
## [1] 14476
BYP51=na.omit(ROC$BYP51); mean(BYP51); sd(BYP51); length(BYP51) # Misbehavior
## [1] 0.07248936
## [1] 0.2593069
## [1] 12457
flag_00=na.omit(ROC$flag_00); mean(flag_00); sd(flag_00); length(flag_00) # One or more flags
## [1] 0.3530901
## [1] 0.4779452
## [1] 16197
flag_01=na.omit(ROC$flag_01); mean(flag_01); sd(flag_01); length(flag_01) # Any one flag
## [1] 0.4326348
## [1] 0.4954599
## [1] 13219
flag_02=na.omit(ROC$flag_02); mean(flag_02); sd(flag_02); length(flag_02) # Any two flags
## [1] 0.1232212
## [1] 0.3287042
## [1] 12368
flag_03=na.omit(ROC$flag_03); mean(flag_03); sd(flag_03); length(flag_03) # Any three flags
## [1] 0.02423982
## [1] 0.1537984
## [1] 13944
flag_04=na.omit(ROC$flag_04); mean(flag_04); sd(flag_04); length(flag_04) # Any four flags
## [1] 0.003530167
## [1] 0.05931215
## [1] 15580
BYS42=na.omit(ROC$BYS42); mean(BYS42); sd(BYS42); length(BYS42); min(BYS42); max(BYS42) # Extrac. activities (2002)
## [1] 4.773294
## [1] 5.699724
## [1] 14446
## [1] 0
## [1] 21
BYTXMSTD_01=na.omit(ROC$BYTXMSTD_01); mean(BYTXMSTD_01); sd(BYTXMSTD_01); length(BYTXMSTD_01); # 1st quantile Math t score (2002)
## [1] 0.25
## [1] 0.4330263
## [1] 15892
differences from Appendix A.
The single flags match Appendix A exactly in N, mean and SD: Absent (12,286 / 0.130 / 0.336), Suspension (14,476 / 0.081 / 0.272), Misbehavior (12,457 / 0.072 / 0.259) and 1st quantile Math t score (15,892 / 0.250 / 0.433). This confirms the recodes: BYP52E codes 2–4 = 1 (“1–4 times”), BYS24F codes 2–5 = 1 (“1–5 times”), and math t score < 44.065 = 1. All four flags also matches exactly (15,580 / 0.004 / 0.059). The other composite flags are close but not identical
The paper says only that the composite flags were built “with Boolean operators such as (and) and (or). It does not say how students with some missing flags were handled. Here, a student counts as having”at least k flags” when k or more of their observed flags are 1. They are coded 0 when they cannot reach k even if their missing flags were all 1, and NA otherwise. The remaining gaps in N and mean most likely come from a different missing-data rule that the paper does not report, not from the recodes, since every single flag matches exactly. Two other possibilities were tested and ruled out: coding only categories 2–3 of BYP52E/BYS24F as 1 (this makes the single flags stop matching), and using the reading score instead of math (Appendix A’s label for “One or more flags” mentions reading, but that fits no better).
# High school dropout with continous predictors
BYTXRSTD=na.omit(ROC$BYTXRSTD); mean(BYTXRSTD); sd(BYTXRSTD); length(BYTXRSTD) # Reading t score
## [1] 50.52618
## [1] 9.88539
## [1] 15892
BYTXMSTD=na.omit(ROC$BYTXMSTD); mean(BYTXMSTD); sd(BYTXMSTD); length(BYTXMSTD) # Math t score (2002)
## [1] 50.71016
## [1] 9.912398
## [1] 15892
F2PS0601=na.omit(ROC$F2PS0601_01); mean(F2PS0601); sd(F2PS0601); length(F2PS0601); # College enrollment
## [1] 0.5456189
## [1] 0.4979383
## [1] 10511
F1RGPP2=na.omit(ROC$F1RGPP2); mean(F1RGPP2); sd(F1RGPP2); length(F1RGPP2);min(F1RGPP2); max(F1RGPP2) # GPA
## [1] 3.911868
## [1] 1.542702
## [1] 14796
## [1] 0
## [1] 6
F1S27=na.omit(ROC$F1S27); mean(F1S27); sd(F1S27); length(F1S27) # Extrac. activities (2004)
## [1] 3.181909
## [1] 1.8975
## [1] 14073
BYS33A=na.omit(ROC$BYS33A); mean(BYS33A); sd(BYS33A); length(BYS33A) # AP
## [1] 0.1823497
## [1] 0.3861459
## [1] 14368
# Postsecondary STEM degree
F3TZSTEM1CRED=na.omit(ROC$F3TZSTEM1CRED); mean(F3TZSTEM1CRED); sd(F3TZSTEM1CRED); length(F3TZSTEM1CRED); # Postsecondary STEM degree
## [1] 0.182526
## [1] 0.4247094
## [1] 6936
F3TZSTEM1TOT=na.omit(ROC$F3TZSTEM1TOT); mean(F3TZSTEM1TOT); sd(F3TZSTEM1TOT); length(F3TZSTEM1TOT); min(F3TZSTEM1TOT); max(F3TZSTEM1TOT) # Number of STEM Courses
## [1] 9.257192
## [1] 10.39643
## [1] 11540
## [1] 0
## [1] 56
F3TZSTEM2GPA=na.omit(ROC$F3TZSTEM2GPA); mean(F3TZSTEM2GPA); sd(F3TZSTEM2GPA); length(F3TZSTEM2GPA); min(F3TZSTEM2GPA); max(F3TZSTEM2GPA) # STEM course GPA
## [1] 2.585565
## [1] 0.9375899
## [1] 10755
## [1] 0
## [1] 4
F1S27=na.omit(ROC$F1S27); mean(F1S27); sd(F1S27); min(F1S27); max(F1S27) #Extracurricular activities (2004)
## [1] 3.181909
## [1] 1.8975
## [1] 1
## [1] 8
# Hard/soft STEM career: see the chunk after STEMH/STEMS are created (Hard STEM section)
# Square ROC plots
# kept for every chunk in the document
knitr::opts_chunk$set(fig.width = 6, fig.height = 6)
knitr::opts_knit$set(global.par = TRUE)
square_plot <- function() par(pty = "s", mar = c(5, 4.5, 4, 1), las = 1, cex.main = 0.9)
square_plot()
# Arrow label for a ROC curve
# x, y = where the label text sits (x on the 1-specificity scale, 0-1)
# target_x = the 1-specificity value on the curve the arrow points to
label_curve <- function(roc_obj, label, x, y, target_x, cex = 0.75, pos = NULL) {
k <- if (isTRUE(roc_obj$percent)) 100 else 1
fpr <- 1 - roc_obj$specificities / k
sen <- roc_obj$sensitivities / k
o <- order(fpr, sen)
target_y <- approx(fpr[o], sen[o], xout = target_x, ties = max)$y
arrows(k * (1 - x), k * y, k * (1 - target_x), k * target_y,
length = 0.07, angle = 20, lwd = 1)
if (is.null(pos)) pos <- if (x < target_x) 2 else 4
text(k * (1 - x), k * y, label, cex = cex, font = 2, pos = pos,
offset = 0.2, xpd = NA)
}
label_roc <- function(roc_obj, label, x, y, target_x, ...) label_curve(roc_obj, label, x, y, target_x, ...)
# DeLong test for every pair of ROC curves in a named list
auc_pairs <- function(rocs) {
pairs <- combn(names(rocs), 2, simplify = FALSE)
do.call(rbind, lapply(pairs, function(pr) {
# warning about curves with different directions is explained under Table 1
t <- suppressWarnings(pROC::roc.test(rocs[[pr[1]]], rocs[[pr[2]]], method = "delong"))
data.frame(`Predictor 1` = pr[1], `Predictor 2` = pr[2],
Z = round(unname(t$statistic), 3),
`p-value` = ifelse(t$p.value < 0.001, "<0.001", sprintf("%.3f", t$p.value)),
check.names = FALSE)
}))
}
auc_pairs_table <- function(groups, caption) {
tab <- do.call(rbind, lapply(names(groups), function(g) {
rbind(data.frame(`Predictor 1` = paste0("*", g, "*"), `Predictor 2` = "", Z = NA,
`p-value` = "", check.names = FALSE),
auc_pairs(groups[[g]]))
}))
opts <- options(knitr.kable.NA = ""); on.exit(options(opts))
knitr::kable(tab, caption = caption, row.names = FALSE, align = c("l", "l", "r", "r"))
}
square_plot()
roc1 = roc(ROC$F2EVERDO, ROC$BYP52E_01, legacy.axes=TRUE, asp=FALSE, main = "ROC curves for predicting dropout,\nwith Balfanz et al.'s flags as predictors",
plot=TRUE, grid=FALSE, lty=5, xaxs="i", yaxs="i", col = 'gray')
## Setting levels: control = 0, case = 1
## Setting direction: controls < cases
roc2 = roc(ROC$F2EVERDO, ROC$BYTXMSTD_01,
plot=TRUE, add=TRUE, percent=roc1$percent, lty=2, col = 'gray')
## Setting levels: control = 0, case = 1
## Setting direction: controls < cases
roc3 = roc(ROC$F2EVERDO, ROC$BYS24F_01,
plot=TRUE, add=TRUE, percent=roc1$percent, lty=3, col = 'gray')
## Setting levels: control = 0, case = 1
## Setting direction: controls < cases
roc4 = roc(ROC$F2EVERDO, ROC$BYP51,
plot=TRUE, add=TRUE, percent=roc1$percent, lty=4, col = 'gray')
## Setting levels: control = 0, case = 1
## Setting direction: controls < cases
roc5 = roc(ROC$F2EVERDO, ROC$flag_00,
plot=TRUE, add=TRUE, percent=roc1$percent, lty=6)
## Setting levels: control = 0, case = 1
## Setting direction: controls < cases
roc6 = roc(ROC$F2EVERDO, ROC$flag_01,
plot=TRUE, add=TRUE, percent=roc1$percent, lty=1)
## Setting levels: control = 0, case = 1
## Setting direction: controls < cases
roc7 = roc(ROC$F2EVERDO, ROC$flag_02,
plot=TRUE, add=TRUE, percent=roc1$percent, lty=18)
## Setting levels: control = 0, case = 1
## Setting direction: controls < cases
roc8 = roc(ROC$F2EVERDO, ROC$flag_03,
plot=TRUE, add=TRUE, percent=roc1$percent, lty=8)
## Setting levels: control = 0, case = 1
## Setting direction: controls < cases
roc9 = roc(ROC$F2EVERDO, ROC$flag_04,
plot=TRUE, add=TRUE, percent=roc1$percent, lty=9)
## Setting levels: control = 0, case = 1
## Setting direction: controls < cases
# Arrow labels (x, y = label position; target_x = 1-specificity on the curve)
label_curve(roc6, "Any one flag", x = 0.30, y = 0.93, target_x = 0.38)
label_curve(roc5, "One or more flags", x = 0.26, y = 0.82, target_x = 0.31)
label_curve(roc7, "Any two flags", x = 0.20, y = 0.71, target_x = 0.25)
label_curve(roc1, "Absent", x = 0.14, y = 0.60, target_x = 0.20)
label_curve(roc2, "1st quantile\nMath t score (2002)", x = 0.70, y = 0.52, target_x = 0.60)
label_curve(roc4, "Misbehavior", x = 0.72, y = 0.40, target_x = 0.55)
label_curve(roc3, "Suspension", x = 0.72, y = 0.30, target_x = 0.50)
label_curve(roc8, "Any three flags", x = 0.66, y = 0.19, target_x = 0.45)
label_curve(roc9, "All four flags", x = 0.60, y = 0.09, target_x = 0.40)
auc_table <- data.frame(
Predictor = c(
"Absent",
"Math t score (2002)",
"Suspension",
"Misbehavior",
"One or more flags",
"Any one flag",
"Any two flags",
"Any three flags",
"Any four flags"
),
AUC = c(
as.numeric(pROC::auc(roc1)),
as.numeric(pROC::auc(roc2)),
as.numeric(pROC::auc(roc3)),
as.numeric(pROC::auc(roc4)),
as.numeric(pROC::auc(roc5)),
as.numeric(pROC::auc(roc6)),
as.numeric(pROC::auc(roc7)),
as.numeric(pROC::auc(roc8)),
as.numeric(pROC::auc(roc9))
)
)
auc_table <- auc_table[order(auc_table$AUC, decreasing = TRUE), ]
knitr::kable(
auc_table,
format = "html",
digits = 3,
col.names = c("Predictor", "AUC"),
align = c("l", "r")
)
| Predictor | AUC | |
|---|---|---|
| 6 | Any one flag | 0.734 |
| 5 | One or more flags | 0.698 |
| 7 | Any two flags | 0.683 |
| 2 | Math t score (2002) | 0.647 |
| 1 | Absent | 0.643 |
| 4 | Misbehavior | 0.593 |
| 3 | Suspension | 0.584 |
| 8 | Any three flags | 0.550 |
| 9 | Any four flags | 0.509 |
Note on differences from Bowers & Zhou (2019), Figure 2A.
The AUCs for the four single flags (Absent 0.643, 1st quantile Math t score 0.647, Misbehavior 0.593, Suspension 0.584) and for All four flags (0.509) match the paper exactly. The other composite flags are within 0.005 of the published values (Any one flag 0.734 vs. 0.729, One or more flags 0.698 vs. 0.700, Any two flags 0.683 vs. 0.685, Any three flags 0.550 vs. 0.551), and the ranking of all nine predictors is the same. These small gaps come from the slightly different sample sizes of the composite flags (see the note under the descriptive statistics). pROC uses listwise deletion, so each AUC is calculated only on students with a non-missing flag, and a few hundred students more or fewer moves the AUC slightly. The DeLong tests below confirm that the flags are built the same way as in the paper that the p-values match Appendix B, including p = 1.000 for One or more flags vs. Any one flag. That result shows the two flags are identical for every student who has both, so “Any one flag” means “at least one flag” and is missing when it cannot be determined.
# Check against Appendix B (paper p-values in comments)
roc.test(roc5, roc6, method = "delong")$p.value
## [1] 1
roc.test(roc1, roc2, method = "delong")$p.value
## [1] 0.3303759
roc.test(roc3, roc4, method = "delong")$p.value
## [1] 0.719295
roc.test(roc2, roc7, method = "delong")$p.value
## [1] 0.08872709
square_plot()
roc1 = roc(ROC$F2EVERDO, ROC$BYTXRSTD, legacy.axes=TRUE, asp=FALSE, main = "ROC curves for predicting dropout,\nwith continuous predictors",
plot=TRUE, grid=FALSE, lty=1, lwd=2, xaxs="i", yaxs="i")
## Setting levels: control = 0, case = 1
## Setting direction: controls > cases
roc2 = roc(ROC$F2EVERDO, ROC$BYTXMSTD,
plot=TRUE, add=TRUE, percent=roc1$percent, lty=2, lwd=2)
## Setting levels: control = 0, case = 1
## Setting direction: controls > cases
roc3 = roc(ROC$F2EVERDO, ROC$BYS42,
plot=TRUE, add=TRUE, percent=roc1$percent, lty=3, lwd=2)
## Setting levels: control = 0, case = 1
## Setting direction: controls > cases
roc4 = roc(ROC$F2EVERDO, ROC$BYP52E,
plot=TRUE, add=TRUE, percent=roc1$percent, lty=4, lwd=2)
## Setting levels: control = 0, case = 1
## Setting direction: controls < cases
roc5 = roc(ROC$F2EVERDO, ROC$BYS24F,
plot=TRUE, add=TRUE, percent=roc1$percent, lty=5, lwd=2)
## Setting levels: control = 0, case = 1
## Setting direction: controls < cases
# The three continuous curves are within ~0.05 of each other everywhere, so each arrow
# points where its curve is most separated from its neighbours
label_roc(roc2, "Math t score (2002)", x = 0.20, y = 0.88, target_x = 0.37, pos = 3)
label_roc(roc1, "Reading t score (2002)", x = 0.62, y = 0.50, target_x = 0.32)
label_roc(roc3, "Extracurricular activities (2002)", x = 0.40, y = 0.15, target_x = 0.20)
label_roc(roc4, "Absent", x = 0.78, y = 0.62, target_x = 0.60)
label_roc(roc5, "Suspension", x = 0.78, y = 0.40, target_x = 0.60)
rocs_dropout <- list("Reading t score (2002)" = roc1,
"Math t score (2002)" = roc2,
"Extracurricular activities (2002)" = roc3,
"Absent" = roc4,
"Suspension" = roc5)
knitr::kable(auc_pairs(rocs_dropout), row.names = FALSE, align = c("l", "l", "r", "r"),
caption = "Table 1: Significance of AUC Difference for Predictors of Continuous Dropout")
| Predictor 1 | Predictor 2 | Z | p-value |
|---|---|---|---|
| Reading t score (2002) | Math t score (2002) | -3.220 | 0.001 |
| Reading t score (2002) | Extracurricular activities (2002) | 3.641 | <0.001 |
| Reading t score (2002) | Absent | 6.456 | <0.001 |
| Reading t score (2002) | Suspension | 14.571 | <0.001 |
| Math t score (2002) | Extracurricular activities (2002) | 5.744 | <0.001 |
| Math t score (2002) | Absent | 8.006 | <0.001 |
| Math t score (2002) | Suspension | 16.735 | <0.001 |
| Extracurricular activities (2002) | Absent | 2.790 | 0.005 |
| Extracurricular activities (2002) | Suspension | 10.380 | <0.001 |
| Absent | Suspension | 5.846 | <0.001 |
Higher test scores and more extracurricular hours mean lower dropout risk, so pROC sets their direction to “>” and reports their AUCs as 0.706, 0.722 and 0.672. Absent and Suspension have direction “<”. The paper’s Table 1 appears to have run the DeLong tests with every predictor forced to direction “<”. That compares Reading, Math and Extracurricular using their flipped AUCs (1 − AUC: 0.294, 0.278, 0.328) instead of the reported ones. Re-running the tests that way reproduces all ten of the paper’s Z values exactly (3.220, −3.641, −33.716, −32.105, −5.744, −34.194, −34.840, −28.758, −28.183, 5.846). The table above uses the AUCs shown in Figure 2B, so it gives the same |Z| for the pairs whose directions agree (Reading–Math 3.220, Reading–Extracurricular 3.641, Math–Extracurricular 5.744, Absent–Suspension 5.846; signs flip because the higher-AUC predictor comes second). It gives much smaller Z values for pairs that mix the two directions, such as Reading vs. Absent. All ten comparisons are still significant (p ≤ 0.005).
In an ROC plot, the diagonal line is a 50-50 guess (AUC = 0.5). The closer a curve gets to the top-left corner, the more accurate the predictor (AUC near 1). In Figure 2A, the Balfanz et al. (2007) flags are all fairly weak predictors of dropout. “Any one flag” is the most accurate (AUC = 0.734), followed by “one or more flags” (0.698). The single flags are close to the 50-50 line: 1st quantile math 0.647, absent 0.643, misbehavior 0.593, suspension 0.584. “All four flags” (0.509) is basically a random guess, because very few students have all four flags, so it misses almost every dropout. This matches the readings: combining flags with “or” catches more students who drop out (higher sensitivity), and many dropout flags in the literature are not much better than a coin flip (Bowers et al., 2013).
In Figure 2B, the continuous predictors do a little better. The 10th-grade math t score is the most accurate (AUC = 0.722), then reading (0.706), extracurricular hours (0.672), absences (0.647) and suspensions (0.584). Table 1 shows that every pair of these predictors is significantly different (all p ≤ 0.005), so math scores really are more accurate than the other indicators. Still, none of them reaches 0.75, which the NCRTI guideline cited in the paper calls “unconvincing evidence”. Each predictor alone would still misidentify many students.
square_plot()
roc1 = roc(ROC$F2PS0601_01, ROC$F1RGPP2, legacy.axes=TRUE, asp=FALSE, main = "ROC Curves for Predicting College Enrollment",
plot=TRUE, grid=FALSE, lty=1, xaxs="i", yaxs="i")
## Setting levels: control = 0, case = 1
## Setting direction: controls < cases
roc2 = roc(ROC$F2PS0601_01, ROC$BYS33A,
plot=TRUE, add=TRUE, percent=roc1$percent, lty=2)
## Setting levels: control = 0, case = 1
## Setting direction: controls < cases
roc3 = roc(ROC$F2PS0601_01, ROC$F1S27,
plot=TRUE, add=TRUE, percent=roc1$percent, lty=3)
## Setting levels: control = 0, case = 1
## Setting direction: controls < cases
label_curve(roc1, "GPA", x = 0.15, y = 0.90, target_x = 0.30)
label_curve(roc3, "Extracurricular activities (2004)", x = 0.42, y = 0.97, target_x = 0.55)
label_curve(roc2, "AP", x = 0.55, y = 0.28, target_x = 0.40)
# keep the college-enrollment curves for Table 2
rocs_college <- list("GPA" = roc1, "AP" = roc2, "Extracurricular activities (2004)" = roc3)
post_stem <- c(
"F3TZSTEM1CRED",
"F3TZSTEM1TOT",
"F3TZSTEM2GPA",
"BYTXMSTD"
)
data.frame(
variable = post_stem,
present_in_ROC = post_stem %in% names(ROC)
)
## variable present_in_ROC
## 1 F3TZSTEM1CRED TRUE
## 2 F3TZSTEM1TOT TRUE
## 3 F3TZSTEM2GPA TRUE
## 4 BYTXMSTD TRUE
square_plot()
# F3TZSTEM1CRED has codes 0, 1, 2; like the paper, compare 0 (no STEM credential) vs 1 (STEM credential)
roc1 = roc(ROC$F3TZSTEM1CRED, ROC$F3TZSTEM1TOT, levels = c(0, 1), legacy.axes=TRUE, asp=FALSE, main = "ROC Curves for Predicting Postsecondary STEM Degree",
plot=TRUE, grid=FALSE, lty=1, xaxs="i", yaxs="i")
## Setting direction: controls < cases
roc2 = roc(ROC$F3TZSTEM1CRED, ROC$F3TZSTEM2GPA, levels = c(0, 1),
plot=TRUE, add=TRUE, percent=roc1$percent, lty=2)
## Setting direction: controls < cases
roc3 = roc(ROC$F3TZSTEM1CRED, ROC$BYTXMSTD, levels = c(0, 1),
plot=TRUE, add=TRUE, percent=roc1$percent, lty=3)
## Setting direction: controls < cases
label_curve(roc1, "Number of STEM courses", x = 0.30, y = 0.80, target_x = 0.05)
label_curve(roc3, "Math t score (2002)", x = 0.65, y = 0.45, target_x = 0.40)
label_curve(roc2, "STEM course GPA", x = 0.72, y = 0.30, target_x = 0.55)
# Rebuild the curves here so this chunk works no matter which chunks were run before it
# (roc1-roc3 are reused by every figure, so they can point to the wrong outcome)
rocs_college <- list(
"GPA" = roc(ROC$F2PS0601_01, ROC$F1RGPP2, quiet = TRUE),
"AP" = roc(ROC$F2PS0601_01, ROC$BYS33A, quiet = TRUE),
"Extracurricular activities (2004)" = roc(ROC$F2PS0601_01, ROC$F1S27, quiet = TRUE))
rocs_stem_degree <- list(
"Number of STEM Courses" = roc(ROC$F3TZSTEM1CRED, ROC$F3TZSTEM1TOT, levels = c(0, 1), quiet = TRUE),
"STEM course GPA" = roc(ROC$F3TZSTEM1CRED, ROC$F3TZSTEM2GPA, levels = c(0, 1), quiet = TRUE),
"Math t score (2002)" = roc(ROC$F3TZSTEM1CRED, ROC$BYTXMSTD, levels = c(0, 1), quiet = TRUE))
auc_pairs_table(
list("College Enrollment Predictors" = rocs_college,
"Postsecondary STEM Degree Predictors" = rocs_stem_degree),
caption = "Table 2: Significance of AUC Difference for College Enrollment Predictors and STEM Career Predictors")
| Predictor 1 | Predictor 2 | Z | p-value |
|---|---|---|---|
| College Enrollment Predictors | |||
| GPA | AP | 32.679 | <0.001 |
| GPA | Extracurricular activities (2004) | 17.070 | <0.001 |
| AP | Extracurricular activities (2004) | -10.939 | <0.001 |
| Postsecondary STEM Degree Predictors | |||
| Number of STEM Courses | STEM course GPA | 39.649 | <0.001 |
| Number of STEM Courses | Math t score (2002) | 31.625 | <0.001 |
| STEM course GPA | Math t score (2002) | -8.712 | <0.001 |
For four-year college enrollment, high school GPA is the most accurate predictor (AUC = 0.767). Extracurricular activities come next (0.642) and taking an AP course is last (0.565). Table 2 shows all three are significantly different from each other (p < 0.001). In a regression, all three would simply be “significant predictors”, but the ROC AUC shows that GPA is much more accurate. This fits the reading’s point that grades capture students’ overall engaged participation in school, while AP is common among students who go to college anyway, so it does not separate them well.
For earning a postsecondary STEM degree, the number of STEM courses taken in college is an excellent predictor (AUC = 0.957), with the curve almost touching the top-left corner. Math t score (0.663) and STEM course GPA (0.566) are much weaker. All pairs differ significantly (p < 0.001). In simple words, how many STEM courses a student takes says much more about finishing a STEM degree than how well they do in them. This makes sense, because a STEM degree requires many STEM courses.
table(ROC$F3STEMOCCCUR, useNA = "ifany")
##
## -3 -4 -8 -9 00 1A 1B 1E 2A 2B 4A 4B 9Z
## 306 2488 459 148 10903 562 179 68 46 39 523 390 86
# Categories in dataset
valid_codes <- c(
"00", "1A", "1B", "1E",
"2A", "2B", "4A", "4B", "9Z"
)
# Occupation code as text (character variable, so negative codes were not set to NA above)
occupation <- as.character(ROC$F3STEMOCCCUR)
# Hard STEM: sub-domain 1
ROC$STEMH <- ifelse(
is.na(occupation) | !occupation %in% valid_codes,
NA_integer_,
as.integer(occupation %in% c("1A", "1B", "1E"))
)
# Soft STEM: sub-domains 2 and 4
ROC$STEMS <- ifelse(
is.na(occupation) | !occupation %in% valid_codes,
NA_integer_,
as.integer(occupation %in% c("2A", "2B", "4A", "4B"))
)
# Descriptive statistics for the STEM career outcomes (Appendix A: 12,796 / 0.063 / 0.243 and 12,796 / 0.078 / 0.268)
STEMH=na.omit(ROC$STEMH); mean(STEMH); sd(STEMH); length(STEMH); # Hard STEM career
## [1] 0.06322288
## [1] 0.2433729
## [1] 12796
STEMS=na.omit(ROC$STEMS); mean(STEMS); sd(STEMS); length(STEMS); # Soft STEM career
## [1] 0.07799312
## [1] 0.2681712
## [1] 12796
square_plot()
roc1 = roc(ROC$STEMH, ROC$F3TZSTEM1TOT, legacy.axes=TRUE, asp=FALSE, main = "ROC Curves for Predicting Hard STEM Career",
plot=TRUE, grid=FALSE, lty=1, xaxs="i", yaxs="i")
## Setting levels: control = 0, case = 1
## Setting direction: controls < cases
roc2 = roc(ROC$STEMH, ROC$F3TZSTEM2GPA,
plot=TRUE, add=TRUE, percent=roc1$percent, lty=2)
## Setting levels: control = 0, case = 1
## Setting direction: controls < cases
roc3 = roc(ROC$STEMH, ROC$BYTXMSTD,
plot=TRUE, add=TRUE, percent=roc1$percent, lty=3)
## Setting levels: control = 0, case = 1
## Setting direction: controls < cases
label_curve(roc1, "Number of STEM courses", x = 0.42, y = 0.95, target_x = 0.30)
label_curve(roc3, "Math t score (2002)", x = 0.45, y = 0.25, target_x = 0.20)
label_curve(roc2, "STEM course GPA", x = 0.75, y = 0.45, target_x = 0.55)
# keep the hard-STEM curves for Table 3
rocs_hard <- list("Number of STEM Courses" = roc1,
"STEM course GPA" = roc2,
"Math t score (2002)" = roc3)
auc_table <- data.frame(
Predictor = c(
"Number of STEM Courses",
"STEM course GPA",
"Math t score (2002)"
),
AUC = c(
as.numeric(pROC::auc(roc1)),
as.numeric(pROC::auc(roc2)),
as.numeric(pROC::auc(roc3))
))
auc_table <- auc_table[order(auc_table$AUC, decreasing = TRUE), ]
knitr::kable(
auc_table,
format = "html",
digits = 3,
col.names = c("Predictor", "AUC"),
align = c("l", "r")
)
| Predictor | AUC | |
|---|---|---|
| 1 | Number of STEM Courses | 0.799 |
| 3 | Math t score (2002) | 0.712 |
| 2 | STEM course GPA | 0.593 |
square_plot()
roc1 = roc(ROC$STEMS, ROC$F3TZSTEM1TOT, legacy.axes=TRUE, asp=FALSE, main = "ROC Curves for Predicting Soft STEM Career",
plot=TRUE, grid=FALSE, lty=1, xaxs="i", yaxs="i")
## Setting levels: control = 0, case = 1
## Setting direction: controls < cases
roc2 = roc(ROC$STEMS, ROC$F3TZSTEM2GPA,
plot=TRUE, add=TRUE, percent=roc1$percent, lty=2)
## Setting levels: control = 0, case = 1
## Setting direction: controls < cases
roc3 = roc(ROC$STEMS, ROC$BYTXMSTD,
plot=TRUE, add=TRUE, percent=roc1$percent, lty=3)
## Setting levels: control = 0, case = 1
## Setting direction: controls < cases
label_curve(roc1, "Number of STEM courses", x = 0.30, y = 0.92, target_x = 0.40)
label_curve(roc2, "STEM course GPA", x = 0.42, y = 0.25, target_x = 0.25)
label_curve(roc3, "Math t score (2002)", x = 0.72, y = 0.45, target_x = 0.50)
rocs_soft <- list("Number of STEM Courses" = roc1,
"STEM course GPA" = roc2,
"Math t score (2002)" = roc3)
auc_pairs_table(
list("Soft STEM Career Predictors" = rocs_soft,
"Hard STEM Career Predictors" = rocs_hard),
caption = "Table 3: Significance of AUC Difference for Soft and Hard STEM Career Predictors")
| Predictor 1 | Predictor 2 | Z | p-value |
|---|---|---|---|
| Soft STEM Career Predictors | |||
| Number of STEM Courses | STEM course GPA | 0.846 | 0.397 |
| Number of STEM Courses | Math t score (2002) | 10.523 | <0.001 |
| STEM course GPA | Math t score (2002) | 11.111 | <0.001 |
| Hard STEM Career Predictors | |||
| Number of STEM Courses | STEM course GPA | 15.055 | <0.001 |
| Number of STEM Courses | Math t score (2002) | 8.943 | <0.001 |
| STEM course GPA | Math t score (2002) | -7.401 | <0.001 |
All six Z and p values match the paper, but the paper’s table has the “Soft” and “Hard” headings swapped. Its “Hard STEM” rows (Z = 0.846, p = 0.397 for Number of STEM Courses vs. STEM course GPA) are the soft STEM results here. The paper’s own text (p. 11) says there is no significant difference between these two predictors for soft STEM careers, which agrees with this table.
auc_table <- data.frame(
Predictor = c(
"Number of STEM Courses",
"STEM course GPA",
"Math t score (2002)"
),
AUC = c(
as.numeric(pROC::auc(roc1)),
as.numeric(pROC::auc(roc2)),
as.numeric(pROC::auc(roc3))
)
)
auc_table <- auc_table[order(auc_table$AUC, decreasing = TRUE), ]
knitr::kable(
auc_table,
format = "html",
digits = 3,
col.names = c("Predictor", "AUC"),
align = c("l", "r")
)
| Predictor | AUC |
|---|---|
| Number of STEM Courses | 0.693 |
| STEM course GPA | 0.673 |
| Math t score (2002) | 0.611 |
For a hard STEM career (science, engineering, math, IT), the number of STEM courses is again the most accurate predictor (AUC = 0.799). Math t score is in the middle (0.712) and STEM course GPA is weakest (0.593). All three differ significantly (p < 0.001). For a soft STEM career (social science and health), the predictors are less accurate overall. Number of STEM courses (0.693) and STEM course GPA (0.673) are not significantly different (Z = 0.846, p = 0.397), and both beat the math t score (0.611, p < 0.001). So the same predictor can work differently for different outcomes: math scores matter more for hard STEM careers than for soft ones. As the authors note, no predictor here reaches the 0.85 level, so these are useful but not definitive early warning indicators. Testing each indicator’s accuracy (AUC plus significance tests) before using it is the main lesson of the paper.
Replication of Chapter 7, “Supervised Machine Learning – Part I” (decision trees, regression trees and random forests), from Bulut & Desjardins (2019), Exploring, Visualizing, and Modeling Big Data with R: https://www.okanbulut.com/bigdata/supervised-machine-learning---part-i.html
library("data.table")
library("dplyr")
##
## Attaching package: 'dplyr'
## The following objects are masked from 'package:data.table':
##
## between, first, last
## The following object is masked from 'package:randomForest':
##
## combine
## The following objects are masked from 'package:stats':
##
## filter, lag
## The following objects are masked from 'package:base':
##
## intersect, setdiff, setequal, union
library("ggplot2")
library("caret")
library("rpart")
library("rpart.plot")
library("randomForest")
library("modelr")
# The ROC section above made every plot square; tree plots look better wide
par(pty = "m")
# Whole PISA 2015 student file (519,334 students x 921 variables; takes about a minute)
pisa <- fread("/Users/xutianyu/Downloads/pisa2015.csv", na.strings = "")
dim(pisa)
## [1] 519334 921
# The CSV has 10 plausible values per subject. As in the earlier chapters of the book,
# each student's math, reading and science score is the mean of the 10 plausible values.
pisa[, `:=`(
math = rowMeans(.SD[, paste0("PV", 1:10, "MATH"), with = FALSE], na.rm = TRUE),
reading = rowMeans(.SD[, paste0("PV", 1:10, "READ"), with = FALSE], na.rm = TRUE),
science = rowMeans(.SD[, paste0("PV", 1:10, "SCIE"), with = FALSE], na.rm = TRUE)
)]
Section 7.1 has no code. It explains how decision trees work. A decision tree predicts an outcome by asking a series of simple yes/no questions about the predictors, such as “is math ≥ 478?”. Each question splits the students into two groups, and the splitting continues until the final groups (the “leaves”) are as similar as possible. Starting from the top “root” node, the tree chooses at each step the predictor and cut-off that separate the students best.
In simple words, trees are easy to understand and explain, because the result is a set of “if-then” rules. But one tree can be unstable and can overfit. That is why the next sections choose cp carefully (7.2, 7.2.1) and then combine many trees into a random forest (7.4).
# Outcome: High = science score at or above the PISA 2015 average (493), Low = below
pisa <- pisa[, science_perf := as.factor(ifelse(science >= 493, "High", "Low"))]
# Canada and the United States, 9 predictors
pisa_small <- subset(pisa, CNT %in% c("Canada", "United States"),
select = c(science_perf, WEALTH, HEDRES, ENVAWARE, ICTRES,
EPIST, HOMEPOS, ESCS, reading, math))
# The book was written with R < 3.6, which used the "Rounding" sampler. Using it here
# gives exactly the book's training/test split (R >= 3.6 would give a different split).
suppressWarnings(RNGkind(sample.kind = "Rounding"))
set.seed(442019)
pisa_nm <- na.omit(pisa_small)
# 70% training, 30% test, stratified by the outcome
index <- createDataPartition(pisa_nm$science_perf, p = 0.7, list = FALSE)
train_dat <- pisa_nm[index, ]
test_dat <- pisa_nm[-index, ]
nrow(train_dat) # book: 16561
## [1] 16561
nrow(test_dat) # book: 7097
## [1] 7097
# Fully grown tree (cp = 0)
dt_fit1 <- rpart(formula = science_perf ~ .,
data = train_dat,
method = "class",
control = rpart.control(minsplit = 20, cp = 0, xval = 0),
parms = list(split = "gini"))
rpart.plot(dt_fit1)
## Warning: labs do not fit even at cex 0.15, there may be some overplotting
# Smaller tree (cp = 0.005)
dt_fit2 <- rpart(formula = science_perf ~ .,
data = train_dat,
method = "class",
control = rpart.control(minsplit = 20, cp = 0.005, xval = 0),
parms = list(split = "gini"))
rpart.plot(dt_fit2)
# Same tree with information gain (entropy) instead of gini.
# The book overwrites dt_fit2 here, but its printed results below (printcp, varImp,
# rules, confusion matrix) come from the gini tree, so this one gets its own name
# and dt_fit2 stays the gini tree.
dt_fit2_info <- rpart(formula = science_perf ~ .,
data = train_dat,
method = "class",
control = rpart.control(minsplit = 20, cp = 0.005, xval = 0),
parms = list(split = "information"))
rpart.plot(dt_fit2_info, extra = 8, box.palette = "RdBu", shadow.col = "gray")
# Gini tree, plotted the same way
rpart.plot(dt_fit2, extra = 8, box.palette = "RdBu", shadow.col = "gray")
# Pruning the full tree back to cp = 0.005
dt_fit1_prune <- prune(dt_fit1, cp = 0.005)
rpart.plot(dt_fit1_prune, extra = 8, box.palette = "RdBu", shadow.col = "gray")
printcp(dt_fit2)
##
## Classification tree:
## rpart(formula = science_perf ~ ., data = train_dat, method = "class",
## parms = list(split = "gini"), control = rpart.control(minsplit = 20,
## cp = 0.005, xval = 0))
##
## Variables actually used in tree construction:
## [1] math reading
##
## Root node error: 6461/16561 = 0.39013
##
## n= 16561
##
## CP nsplit rel error
## 1 0.7461693 0 1.00000
## 2 0.0153227 1 0.25383
## 3 0.0147036 3 0.22319
## 4 0.0080483 4 0.20848
## 5 0.0050000 6 0.19239
summary(dt_fit2)
## Call:
## rpart(formula = science_perf ~ ., data = train_dat, method = "class",
## parms = list(split = "gini"), control = rpart.control(minsplit = 20,
## cp = 0.005, xval = 0))
## n= 16561
##
## CP nsplit rel error
## 1 0.74616932 0 1.0000000
## 2 0.01532271 1 0.2538307
## 3 0.01470361 3 0.2231853
## 4 0.00804829 4 0.2084817
## 5 0.00500000 6 0.1923851
##
## Variable importance
## math reading ENVAWARE ESCS EPIST HOMEPOS
## 46 37 5 4 4 4
##
## Node number 1: 16561 observations, complexity param=0.7461693
## predicted class=High expected loss=0.3901334 P(node) =1
## class counts: 10100 6461
## probabilities: 0.610 0.390
## left son=2 (10226 obs) right son=3 (6335 obs)
## Primary splits:
## math < 477.5115 to the right, improve=4934.1020, (0 missing)
## reading < 497.3618 to the right, improve=4789.7100, (0 missing)
## EPIST < 0.198 to the right, improve= 717.7465, (0 missing)
## ENVAWARE < -0.70615 to the right, improve= 497.6106, (0 missing)
## ESCS < 0.68805 to the right, improve= 423.6393, (0 missing)
## Surrogate splits:
## reading < 491.146 to the right, agree=0.856, adj=0.624, (0 split)
## ENVAWARE < -0.70615 to the right, agree=0.660, adj=0.110, (0 split)
## ESCS < -0.473 to the right, agree=0.655, adj=0.098, (0 split)
## EPIST < -0.584 to the right, agree=0.652, adj=0.089, (0 split)
## HOMEPOS < -0.52045 to the right, agree=0.648, adj=0.080, (0 split)
##
## Node number 2: 10226 observations, complexity param=0.01532271
## predicted class=High expected loss=0.08634852 P(node) =0.6174748
## class counts: 9343 883
## probabilities: 0.914 0.086
## left son=4 (8797 obs) right son=5 (1429 obs)
## Primary splits:
## reading < 499.4133 to the right, improve=468.47150, (0 missing)
## math < 507.9312 to the right, improve=267.69060, (0 missing)
## EPIST < 0.1958 to the right, improve= 30.64835, (0 missing)
## ENVAWARE < -0.7282 to the right, improve= 27.13673, (0 missing)
## HOMEPOS < -0.00285 to the right, improve= 12.47935, (0 missing)
## Surrogate splits:
## math < 481.7951 to the right, agree=0.862, adj=0.013, (0 split)
## ICTRES < -2.9564 to the right, agree=0.860, adj=0.001, (0 split)
##
## Node number 3: 6335 observations, complexity param=0.01470361
## predicted class=Low expected loss=0.1194949 P(node) =0.3825252
## class counts: 757 5578
## probabilities: 0.119 0.881
## left son=6 (823 obs) right son=7 (5512 obs)
## Primary splits:
## reading < 506.7617 to the right, improve=363.28980, (0 missing)
## math < 449.5018 to the right, improve=202.08040, (0 missing)
## ENVAWARE < -0.23335 to the right, improve= 24.76223, (0 missing)
## EPIST < 0.2134 to the right, improve= 20.60559, (0 missing)
## HOMEPOS < -0.65485 to the right, improve= 5.43476, (0 missing)
##
## Node number 4: 8797 observations
## predicted class=High expected loss=0.02534955 P(node) =0.5311877
## class counts: 8574 223
## probabilities: 0.975 0.025
##
## Node number 5: 1429 observations, complexity param=0.01532271
## predicted class=High expected loss=0.4618614 P(node) =0.08628706
## class counts: 769 660
## probabilities: 0.538 0.462
## left son=10 (945 obs) right son=11 (484 obs)
## Primary splits:
## reading < 467.9986 to the right, improve=86.210090, (0 missing)
## math < 523.4835 to the right, improve=68.072220, (0 missing)
## ENVAWARE < 0.0851 to the right, improve=15.654290, (0 missing)
## EPIST < 0.1958 to the right, improve= 9.251227, (0 missing)
## WEALTH < 0.7185 to the right, improve= 7.572725, (0 missing)
## Surrogate splits:
## EPIST < -2.1704 to the right, agree=0.664, adj=0.008, (0 split)
## ESCS < -2.06225 to the right, agree=0.663, adj=0.004, (0 split)
## HEDRES < -2.98705 to the right, agree=0.662, adj=0.002, (0 split)
## ICTRES < -2.0475 to the right, agree=0.662, adj=0.002, (0 split)
## HOMEPOS < -1.85625 to the right, agree=0.662, adj=0.002, (0 split)
##
## Node number 6: 823 observations, complexity param=0.00804829
## predicted class=High expected loss=0.4422843 P(node) =0.04969507
## class counts: 459 364
## probabilities: 0.558 0.442
## left son=12 (239 obs) right son=13 (584 obs)
## Primary splits:
## reading < 538.6211 to the right, improve=36.595050, (0 missing)
## math < 458.3372 to the right, improve=35.012280, (0 missing)
## ENVAWARE < 0.8873 to the right, improve= 9.457961, (0 missing)
## EPIST < 0.6612 to the right, improve= 8.267985, (0 missing)
## HEDRES < -0.0704 to the left, improve= 5.287639, (0 missing)
## Surrogate splits:
## HOMEPOS < 2.5398 to the right, agree=0.712, adj=0.008, (0 split)
## WEALTH < 3.7552 to the right, agree=0.711, adj=0.004, (0 split)
## ESCS < 1.68255 to the right, agree=0.711, adj=0.004, (0 split)
##
## Node number 7: 5512 observations
## predicted class=Low expected loss=0.05406386 P(node) =0.3328301
## class counts: 298 5214
## probabilities: 0.054 0.946
##
## Node number 10: 945 observations
## predicted class=High expected loss=0.3375661 P(node) =0.05706177
## class counts: 626 319
## probabilities: 0.662 0.338
##
## Node number 11: 484 observations
## predicted class=Low expected loss=0.2954545 P(node) =0.02922529
## class counts: 143 341
## probabilities: 0.295 0.705
##
## Node number 12: 239 observations
## predicted class=High expected loss=0.209205 P(node) =0.0144315
## class counts: 189 50
## probabilities: 0.791 0.209
##
## Node number 13: 584 observations, complexity param=0.00804829
## predicted class=Low expected loss=0.4623288 P(node) =0.03526357
## class counts: 270 314
## probabilities: 0.462 0.538
## left son=26 (290 obs) right son=27 (294 obs)
## Primary splits:
## math < 458.3372 to the right, improve=22.943920, (0 missing)
## reading < 522.4489 to the right, improve= 8.272326, (0 missing)
## ENVAWARE < -0.1317 to the right, improve= 7.457194, (0 missing)
## EPIST < 0.7558 to the right, improve= 4.979011, (0 missing)
## ESCS < 0.3023 to the left, improve= 4.179308, (0 missing)
## Surrogate splits:
## HEDRES < -0.95765 to the left, agree=0.550, adj=0.093, (0 split)
## ESCS < -0.12205 to the left, agree=0.545, adj=0.083, (0 split)
## reading < 519.4401 to the right, agree=0.545, adj=0.083, (0 split)
## EPIST < -0.21475 to the right, agree=0.534, adj=0.062, (0 split)
## HOMEPOS < -0.55435 to the left, agree=0.533, adj=0.059, (0 split)
##
## Node number 26: 290 observations
## predicted class=High expected loss=0.3965517 P(node) =0.01751102
## class counts: 175 115
## probabilities: 0.603 0.397
##
## Node number 27: 294 observations
## predicted class=Low expected loss=0.3231293 P(node) =0.01775255
## class counts: 95 199
## probabilities: 0.323 0.677
varImp(dt_fit2)
## Overall
## ENVAWARE 582.079065
## EPIST 791.498637
## ESCS 427.818610
## HEDRES 5.287639
## HOMEPOS 17.914110
## math 5529.901785
## reading 5752.549285
## WEALTH 7.572725
## ICTRES 0.000000
rpart.rules(dt_fit2, cover = TRUE)
## science_perf cover
## 0.03 when math >= 478 & reading >= 499 53%
## 0.21 when math < 478 & reading >= 539 1%
## 0.34 when math >= 478 & reading is 468 to 499 6%
## 0.40 when math is 458 to 478 & reading is 507 to 539 2%
## 0.68 when math < 458 & reading is 507 to 539 2%
## 0.70 when math >= 478 & reading < 468 3%
## 0.95 when math < 478 & reading < 507 33%
# Predicted probabilities for the test data
dt_pred <- predict(dt_fit2, test_dat) %>%
as.data.frame()
head(dt_pred)
## High Low
## 1 0.97465045 0.02534955
## 2 0.05406386 0.94593614
## 3 0.05406386 0.94593614
## 4 0.66243386 0.33756614
## 5 0.97465045 0.02534955
## 6 0.05406386 0.94593614
# Classify as High when P(High) >= 0.5, then compare with the real outcome
dt_pred <- mutate(dt_pred,
science_perf = as.factor(ifelse(High >= 0.5, "High", "Low"))
) %>%
select(science_perf)
confusionMatrix(dt_pred$science_perf, test_dat$science_perf)
## Confusion Matrix and Statistics
##
## Reference
## Prediction High Low
## High 4076 316
## Low 252 2453
##
## Accuracy : 0.92
## 95% CI : (0.9134, 0.9262)
## No Information Rate : 0.6098
## P-Value [Acc > NIR] : < 2.2e-16
##
## Kappa : 0.8311
##
## Mcnemar's Test P-Value : 0.008207
##
## Sensitivity : 0.9418
## Specificity : 0.8859
## Pos Pred Value : 0.9281
## Neg Pred Value : 0.9068
## Prevalence : 0.6098
## Detection Rate : 0.5743
## Detection Prevalence : 0.6189
## Balanced Accuracy : 0.9138
##
## 'Positive' Class : High
##
# Without reading and math: trees with only the 7 background variables
dt_fit3a <- rpart(formula = science_perf ~ WEALTH + HEDRES + ENVAWARE +
ICTRES + EPIST + HOMEPOS + ESCS,
data = train_dat,
method = "class",
control = rpart.control(minsplit = 20, cp = 0.001, xval = 0),
parms = list(split = "gini"))
rpart.plot(dt_fit3a, extra = 8, box.palette = "RdBu", shadow.col = "gray")
dt_fit3b <- rpart(formula = science_perf ~ WEALTH + HEDRES + ENVAWARE +
ICTRES + EPIST + HOMEPOS + ESCS,
data = train_dat,
method = "class",
control = rpart.control(minsplit = 20, cp = 0.005, xval = 0),
parms = list(split = "gini"))
rpart.plot(dt_fit3b, extra = 8, box.palette = "RdBu", shadow.col = "gray")
# Accuracy, sensitivity and specificity of the 7-predictor tree for a given cp
decision_check <- function(cp) {
require("rpart")
require("dplyr")
dt <- rpart(formula = science_perf ~ WEALTH + HEDRES + ENVAWARE +
ICTRES + EPIST + HOMEPOS + ESCS,
data = train_dat,
method = "class",
control = rpart.control(minsplit = 20, cp = cp, xval = 0),
parms = list(split = "gini"))
dt_pred <- predict(dt, test_dat) %>%
as.data.frame() %>%
mutate(science_perf = as.factor(ifelse(High >= 0.5, "High", "Low"))) %>%
select(science_perf)
cm <- confusionMatrix(dt_pred$science_perf, test_dat$science_perf)
results <- data.frame(cp = cp,
Accuracy = round(cm$overall[1], 3),
Sensitivity = round(cm$byClass[1], 3),
Specificity = round(cm$byClass[2], 3))
return(results)
}
result <- NULL
for(i in seq(from = 0.001, to = 0.08, by = 0.005)) {
result <- rbind(result, decision_check(cp = i))
}
result <- result[order(result$Accuracy, result$Sensitivity, result$Specificity), ]
result
## cp Accuracy Sensitivity Specificity
## Accuracy9 0.046 0.675 0.947 0.250
## Accuracy10 0.051 0.675 0.947 0.250
## Accuracy11 0.056 0.675 0.947 0.250
## Accuracy12 0.061 0.675 0.947 0.250
## Accuracy13 0.066 0.675 0.947 0.250
## Accuracy14 0.071 0.675 0.947 0.250
## Accuracy15 0.076 0.675 0.947 0.250
## Accuracy3 0.016 0.686 0.757 0.574
## Accuracy4 0.021 0.686 0.757 0.574
## Accuracy5 0.026 0.686 0.757 0.574
## Accuracy6 0.031 0.686 0.757 0.574
## Accuracy7 0.036 0.686 0.757 0.574
## Accuracy8 0.041 0.686 0.757 0.574
## Accuracy1 0.006 0.694 0.850 0.449
## Accuracy2 0.011 0.694 0.850 0.449
## Accuracy 0.001 0.705 0.835 0.502
result_long <- melt(as.data.table(result),
id.vars = c("cp"),
measure = c("Accuracy", "Sensitivity", "Specificity"),
variable.name = "Index",
value.name = "Value")
ggplot(data = result_long,
mapping = aes(x = cp, y = Value)) +
geom_point(aes(color = Index), size = 3) +
labs(x = "Complexity Parameter", y = "Value") +
theme_bw()
The decision tree splits students into smaller and smaller groups
using simple “if-then” rules. The goal is for each final group (leaf) to
be mostly “High” or mostly “Low” in science. With cp = 0
the tree (dt_fit1) grows very large and is hard to read,
and it probably overfits the training data. Raising the complexity
parameter to cp = 0.005 (or pruning the big tree) gives a
small tree with only 6 splits, and it uses only math and reading. The
rules are easy to read: for example, students with math ≥ 478 and
reading ≥ 499 (53% of the sample) have only a 3% chance of being “Low”
in science. Students with math < 478 and reading < 507 (33%) have
a 95% chance of being “Low”. Gini and information (entropy) splits give
very similar trees. On the test data this small tree is 92% accurate
(sensitivity 0.94, specificity 0.89), so it works well on students it
has not seen.
This is mostly because science, math and reading scores are strongly related. When math and reading are removed, the tree has to use background variables (ESCS, EPIST, ENVAWARE, HOMEPOS, etc.), and accuracy drops to about 0.68–0.71. The cp comparison also shows the trade-off between sensitivity and specificity. Simpler trees (larger cp) label almost everyone “High” (sensitivity 0.95, specificity only 0.25). More complex trees (smaller cp) are more balanced. So cp controls how complex the tree is, and choosing it is a balance between fitting the data and keeping the tree simple.
# 10-fold cross-validation (xval = 10) to choose cp
dt_fit4 <- rpart(formula = science_perf ~ WEALTH + HEDRES + ENVAWARE +
ICTRES + EPIST + HOMEPOS + ESCS,
data = train_dat,
method = "class",
control = rpart.control(minsplit = 20, cp = 0, xval = 10),
parms = list(split = "gini"))
printcp(dt_fit4)
##
## Classification tree:
## rpart(formula = science_perf ~ WEALTH + HEDRES + ENVAWARE + ICTRES +
## EPIST + HOMEPOS + ESCS, data = train_dat, method = "class",
## parms = list(split = "gini"), control = rpart.control(minsplit = 20,
## cp = 0, xval = 10))
##
## Variables actually used in tree construction:
## [1] ENVAWARE EPIST ESCS HEDRES HOMEPOS ICTRES WEALTH
##
## Root node error: 6461/16561 = 0.39013
##
## n= 16561
##
## CP nsplit rel error xerror xstd
## 1 7.7233e-02 0 1.00000 1.00000 0.0097156
## 2 4.3646e-02 2 0.84553 0.84677 0.0093682
## 3 1.1918e-02 3 0.80189 0.80406 0.0092417
## 4 5.6493e-03 5 0.77805 0.78703 0.0091875
## 5 2.6312e-03 7 0.76675 0.78270 0.0091733
## 6 2.3216e-03 9 0.76149 0.78378 0.0091769
## 7 1.9347e-03 11 0.75685 0.78270 0.0091733
## 8 1.8573e-03 13 0.75298 0.78115 0.0091683
## 9 1.7025e-03 16 0.74741 0.78130 0.0091688
## 10 1.5477e-03 18 0.74400 0.78068 0.0091667
## 11 1.5220e-03 24 0.73425 0.77743 0.0091560
## 12 1.3930e-03 30 0.72512 0.77852 0.0091596
## 13 1.2382e-03 34 0.71955 0.77356 0.0091430
## 14 1.0834e-03 35 0.71831 0.77465 0.0091467
## 15 1.0525e-03 47 0.70392 0.77387 0.0091441
## 16 8.5126e-04 52 0.69865 0.77279 0.0091404
## 17 8.2547e-04 54 0.69695 0.77790 0.0091575
## 18 7.7387e-04 57 0.69447 0.77697 0.0091544
## 19 7.2228e-04 69 0.68488 0.77914 0.0091616
## 20 6.7069e-04 72 0.68271 0.77697 0.0091544
## 21 6.1910e-04 84 0.67466 0.78099 0.0091677
## 22 5.8041e-04 101 0.66398 0.78610 0.0091845
## 23 5.6751e-04 106 0.66104 0.78718 0.0091880
## 24 5.4171e-04 123 0.65036 0.79121 0.0092010
## 25 5.1592e-04 148 0.63612 0.79121 0.0092010
## 26 4.9012e-04 153 0.63287 0.79910 0.0092262
## 27 4.6432e-04 159 0.62993 0.79957 0.0092277
## 28 4.3337e-04 198 0.61059 0.80313 0.0092388
## 29 4.1273e-04 211 0.60331 0.80622 0.0092485
## 30 4.0241e-04 231 0.59403 0.80932 0.0092581
## 31 3.8694e-04 254 0.58180 0.81025 0.0092609
## 32 3.6114e-04 275 0.57282 0.81241 0.0092676
## 33 3.3166e-04 298 0.56369 0.81288 0.0092690
## 34 3.0955e-04 310 0.55905 0.82185 0.0092961
## 35 2.7086e-04 362 0.54280 0.82449 0.0093039
## 36 2.5796e-04 382 0.53645 0.83052 0.0093217
## 37 2.4764e-04 404 0.52995 0.83965 0.0093481
## 38 2.3216e-04 416 0.52685 0.84197 0.0093547
## 39 2.2111e-04 459 0.51509 0.84569 0.0093652
## 40 2.1668e-04 470 0.51230 0.84569 0.0093652
## 41 2.0637e-04 498 0.50224 0.84987 0.0093768
## 42 1.9347e-04 510 0.49977 0.85219 0.0093833
## 43 1.8573e-04 524 0.49667 0.85265 0.0093846
## 44 1.7197e-04 532 0.49482 0.85265 0.0093846
## 45 1.5477e-04 541 0.49327 0.87339 0.0094403
## 46 1.2898e-04 635 0.47717 0.87463 0.0094435
## 47 1.1608e-04 641 0.47640 0.87835 0.0094531
## 48 1.0318e-04 649 0.47547 0.88268 0.0094642
## 49 9.2865e-05 670 0.47330 0.88392 0.0094673
## 50 7.7387e-05 675 0.47284 0.89351 0.0094914
## 51 6.8789e-05 717 0.46959 0.89351 0.0094914
## 52 5.8041e-05 726 0.46897 0.89707 0.0095001
## 53 5.1592e-05 741 0.46804 0.90141 0.0095106
## 54 3.8694e-05 774 0.46634 0.90234 0.0095129
## 55 2.2111e-05 786 0.46587 0.90543 0.0095203
## 56 0.0000e+00 800 0.46525 0.90698 0.0095240
plotcp(dt_fit4)
# Tree with the cp chosen from the cross-validation results
dt_fit5 <- rpart(formula = science_perf ~ WEALTH + HEDRES + ENVAWARE +
ICTRES + EPIST + HOMEPOS + ESCS,
data = train_dat,
method = "class",
control = rpart.control(minsplit = 20, cp = 0.0039, xval = 0),
parms = list(split = "gini"))
printcp(dt_fit5)
##
## Classification tree:
## rpart(formula = science_perf ~ WEALTH + HEDRES + ENVAWARE + ICTRES +
## EPIST + HOMEPOS + ESCS, data = train_dat, method = "class",
## parms = list(split = "gini"), control = rpart.control(minsplit = 20,
## cp = 0.0039, xval = 0))
##
## Variables actually used in tree construction:
## [1] ENVAWARE EPIST ESCS HOMEPOS
##
## Root node error: 6461/16561 = 0.39013
##
## n= 16561
##
## CP nsplit rel error
## 1 0.0772326 0 1.00000
## 2 0.0436465 2 0.84553
## 3 0.0119177 3 0.80189
## 4 0.0056493 5 0.77805
## 5 0.0039000 7 0.76675
rpart.plot(dt_fit5, extra = 8, box.palette = "RdBu", shadow.col = "gray")
# Regression tree: predicting the math score (continuous outcome, method = "anova")
rt_fit1 <- rpart(formula = math ~ WEALTH + HEDRES + ENVAWARE +
ICTRES + EPIST + HOMEPOS + ESCS,
data = train_dat,
method = "anova",
control = rpart.control(minsplit = 20, cp = 0.001, xval = 10),
parms = list(split = "gini"))
printcp(rt_fit1)
##
## Regression tree:
## rpart(formula = math ~ WEALTH + HEDRES + ENVAWARE + ICTRES +
## EPIST + HOMEPOS + ESCS, data = train_dat, method = "anova",
## parms = list(split = "gini"), control = rpart.control(minsplit = 20,
## cp = 0.001, xval = 10))
##
## Variables actually used in tree construction:
## [1] ENVAWARE EPIST ESCS HEDRES WEALTH
##
## Root node error: 104625310/16561 = 6317.6
##
## n= 16561
##
## CP nsplit rel error xerror xstd
## 1 0.1121549 0 1.00000 1.00014 0.0100818
## 2 0.0382061 1 0.88785 0.88819 0.0091919
## 3 0.0353050 2 0.84964 0.85964 0.0089652
## 4 0.0166934 3 0.81433 0.81758 0.0085677
## 5 0.0078301 4 0.79764 0.80105 0.0084293
## 6 0.0070306 5 0.78981 0.79455 0.0083594
## 7 0.0063780 6 0.78278 0.78877 0.0083343
## 8 0.0040553 7 0.77640 0.78437 0.0083043
## 9 0.0033408 8 0.77235 0.78091 0.0082947
## 10 0.0030034 9 0.76901 0.77942 0.0082741
## 11 0.0028744 10 0.76600 0.77759 0.0082582
## 12 0.0024670 11 0.76313 0.77469 0.0082327
## 13 0.0021466 12 0.76066 0.77141 0.0082005
## 14 0.0021460 13 0.75851 0.77185 0.0082082
## 15 0.0019919 14 0.75637 0.77166 0.0082192
## 16 0.0018103 15 0.75438 0.76997 0.0082037
## 17 0.0017435 17 0.75076 0.76856 0.0081993
## 18 0.0017275 18 0.74901 0.76836 0.0081954
## 19 0.0016846 19 0.74728 0.76787 0.0081916
## 20 0.0016463 20 0.74560 0.76770 0.0081872
## 21 0.0015453 21 0.74395 0.76759 0.0081813
## 22 0.0013210 22 0.74241 0.76538 0.0081718
## 23 0.0012386 23 0.74109 0.76290 0.0081676
## 24 0.0012244 25 0.73861 0.76170 0.0081598
## 25 0.0011261 27 0.73616 0.75927 0.0081399
## 26 0.0011075 28 0.73504 0.75895 0.0081377
## 27 0.0011003 29 0.73393 0.75948 0.0081432
## 28 0.0010564 30 0.73283 0.75924 0.0081413
## 29 0.0010195 31 0.73177 0.75704 0.0081125
## 30 0.0010000 32 0.73075 0.75675 0.0081169
rt_fit2 <- rpart(formula = math ~ WEALTH + HEDRES + ENVAWARE +
ICTRES + EPIST + HOMEPOS + ESCS,
data = train_dat,
method = "anova",
control = rpart.control(minsplit = 20, cp = 0.007, xval = 0),
parms = list(split = "gini"))
printcp(rt_fit2)
##
## Regression tree:
## rpart(formula = math ~ WEALTH + HEDRES + ENVAWARE + ICTRES +
## EPIST + HOMEPOS + ESCS, data = train_dat, method = "anova",
## parms = list(split = "gini"), control = rpart.control(minsplit = 20,
## cp = 0.007, xval = 0))
##
## Variables actually used in tree construction:
## [1] ENVAWARE EPIST ESCS
##
## Root node error: 104625310/16561 = 6317.6
##
## n= 16561
##
## CP nsplit rel error
## 1 0.1121549 0 1.00000
## 2 0.0382061 1 0.88785
## 3 0.0353050 2 0.84964
## 4 0.0166934 3 0.81433
## 5 0.0078301 4 0.79764
## 6 0.0070306 5 0.78981
## 7 0.0070000 6 0.78278
rpart.plot(rt_fit2, extra = 100, box.palette = "RdBu", shadow.col = "gray")
# Mean absolute error and root mean square error, training vs test data
mae(model = rt_fit2, data = train_dat)
## [1] 56.48637
rmse(model = rt_fit2, data = train_dat)
## [1] 70.3226
mae(model = rt_fit2, data = test_dat)
## [1] 56.65823
rmse(model = rt_fit2, data = test_dat)
## [1] 70.41532
Instead of guessing cp, 10-fold cross-validation
(xval = 10) splits the training data into 10 parts. It fits
the tree on 9 parts and checks its error on the 10th. The
printcp()/plotcp() output shows that the
cross-validated error (xerror) drops quickly at first and then levels
off at about 0.77. So making the tree bigger after a few splits does not
really improve prediction. Following the book, we pick a small cp where
the error has already leveled off (cp = 0.0039). This gives
dt_fit5, a simple tree with 7 splits that uses ESCS, EPIST,
ENVAWARE and HOMEPOS.
The regression tree uses the same idea for a continuous outcome (the
math score). The tree with cp = 0.007 uses ENVAWARE, EPIST
and ESCS, and it reduces the error by only about 21% compared with just
predicting the average (relative error 0.79). The MAE (about 56.5
points) and RMSE (about 70.4 points) are almost the same for the
training and test data. So the tree is not overfitting, but the
background variables can only explain a small part of the differences in
math scores.
rf_fit1 <- randomForest(formula = science_perf ~ .,
data = train_dat,
importance = TRUE, ntree = 1000)
print(rf_fit1)
##
## Call:
## randomForest(formula = science_perf ~ ., data = train_dat, importance = TRUE, ntree = 1000)
## Type of random forest: classification
## Number of trees: 1000
## No. of variables tried at each split: 3
##
## OOB estimate of error rate: 7.63%
## Confusion matrix:
## High Low class.error
## High 9459 641 0.06346535
## Low 622 5839 0.09626993
# OOB error by number of trees
plot(rf_fit1)
rf_fit2 <- randomForest(formula = science_perf ~ .,
data = train_dat,
importance = TRUE, ntree = 50)
print(rf_fit2)
##
## Call:
## randomForest(formula = science_perf ~ ., data = train_dat, importance = TRUE, ntree = 50)
## Type of random forest: classification
## Number of trees: 50
## No. of variables tried at each split: 3
##
## OOB estimate of error rate: 7.74%
## Confusion matrix:
## High Low class.error
## High 9465 635 0.06287129
## Low 646 5815 0.09998452
# Classification accuracy in the training data
sum(diag(rf_fit2$confusion)) / nrow(train_dat)
## [1] 0.9226496
importance(rf_fit2) %>%
as.data.frame() %>%
mutate(Predictors = row.names(.)) %>%
arrange(desc(MeanDecreaseGini))
## High Low MeanDecreaseAccuracy MeanDecreaseGini Predictors
## math 29.380889 38.3753846 51.046554 3205.8314 math
## reading 41.655837 33.9384659 60.981665 2993.5330 reading
## EPIST 4.177108 2.0361204 4.226346 339.3820 EPIST
## ESCS 7.874423 4.6877784 8.287506 310.9099 ESCS
## ENVAWARE 4.482585 5.3737399 7.492806 297.8013 ENVAWARE
## HOMEPOS 6.567278 8.0591792 9.403504 233.1485 HOMEPOS
## WEALTH 5.523155 6.7772569 8.697635 199.3318 WEALTH
## ICTRES 6.361521 4.8010217 8.327453 169.1460 ICTRES
## HEDRES 6.081750 0.7528446 4.650831 130.7501 HEDRES
varImpPlot(rf_fit2,
main = "Importance of Variables for Science Performance")
# Predictions for the test data
# (the book uses as.data.frame() and the column `.`; data.frame() gives the same result
# without depending on how the pipe names the column)
rf_pred <- data.frame(science_perf = predict(rf_fit2, test_dat))
confusionMatrix(rf_pred$science_perf, test_dat$science_perf)
## Confusion Matrix and Statistics
##
## Reference
## Prediction High Low
## High 4055 279
## Low 273 2490
##
## Accuracy : 0.9222
## 95% CI : (0.9157, 0.9283)
## No Information Rate : 0.6098
## P-Value [Acc > NIR] : <2e-16
##
## Kappa : 0.8365
##
## Mcnemar's Test P-Value : 0.8315
##
## Sensitivity : 0.9369
## Specificity : 0.8992
## Pos Pred Value : 0.9356
## Neg Pred Value : 0.9012
## Prevalence : 0.6098
## Detection Rate : 0.5714
## Detection Prevalence : 0.6107
## Balanced Accuracy : 0.9181
##
## 'Positive' Class : High
##
The data split, all decision trees, the cp comparison, the
cross-validated trees and the regression tree (MAE 56.49/56.66, RMSE
70.32/70.42) reproduce the book’s numbers exactly. The random forests
are very close but not identical: OOB error 7.63% for
rf_fit1 (book 7.58%) and 7.74% for rf_fit2
(book 7.95%), and test accuracy 0.922 (book 0.923). The book’s code does
not call set.seed() right before
randomForest(), so the random trees depend on everything
that ran before (for example the random folds in the cross-validated
trees) and on the package version. Small differences like these are
expected. The conclusions are the same: math and reading are by far the
most important predictors, and the forest classifies about 92% of test
students correctly, slightly better than the single tree.
rf_class <- data.frame(actual = test_dat$science_perf,
predicted = rf_pred$science_perf) %>%
mutate(Status = ifelse(actual == predicted, TRUE, FALSE))
ggplot(data = rf_class,
mapping = aes(x = predicted, fill = Status)) +
geom_bar(position = "dodge") +
labs(x = "Predicted Science Performance",
y = "Actual Science Performance") +
theme_bw()
ggplot(data = rf_class,
mapping = aes(x = predicted, y = actual,
color = Status, shape = Status)) +
geom_jitter(size = 2, alpha = 0.6) +
labs(x = "Predicted Science Performance",
y = "Actual Science Performance") +
theme_bw()
# Cross-validation of the random forest (the book shows this code but not its output).
# rfUtilities is not installed here, so this chunk is not run.
install.packages("rfUtilities")
library("rfUtilities")
rf_fit2_cv <- rf.crossValidation(x = rf_fit2, xdata = train_dat,
p = 0.10, # Proportion of data to test (the rest is training)
n = 10, # Number of cross validation samples
ntree = 50)
# Producer's accuracy: cross-validation vs. model
par(mfrow = c(1, 2))
plot(rf_fit2_cv, type = "cv", main = "CV producers accuracy")
plot(rf_fit2_cv, type = "model", main = "Model producers accuracy")
par(mfrow = c(1, 1))
# OOB error: cross-validation vs. model
par(mfrow = c(1, 2))
plot(rf_fit2_cv, type = "cv", stat = "oob", main = "CV oob error")
plot(rf_fit2_cv, type = "model", stat = "oob", main = "Model oob error")
par(mfrow = c(1, 1))
A random forest builds many trees, each on a bootstrap sample of the
students, and each split only considers a random subset of predictors
(here 3 of the 9). It then lets the trees “vote”. This makes the
predictions more stable than a single tree. The out-of-bag (OOB) error,
which is checked on the students each tree did not see, is about 7.6%
with 1,000 trees. The error plot shows it stops improving after about 50
trees, so rf_fit2 with 50 trees does just as well (OOB
error about 7.7%, training accuracy about 92%).
Variable importance agrees with the single tree: math and reading are by far the most important predictors, and the background variables (EPIST, ESCS, ENVAWARE, HOMEPOS, WEALTH, ICTRES, HEDRES) matter much less. On the test data the forest is about 92.2% accurate (sensitivity 0.94, specificity 0.90), slightly better and more balanced than the single decision tree. The bar and jitter plots show the same thing visually: most students are classified correctly, and the mistakes happen in both directions (some “High” students predicted “Low” and some “Low” students predicted “High”). The trade-off is that a forest is harder to interpret than one tree, because there is no single set of rules to read. In practice, it gives better prediction but less explanation.