Every Exam 3 analysis question can be broken into four parts. Read the question once for each part before you type any code.
Insurance_Claims.csv holds 2,500 simulated insurance
claims (fictional). The outcome is fraud (1 = the claim
was confirmed fraudulent, 0 = legitimate); 395 claims (15.8%) are
fraudulent. There are 14 predictors: 9 numeric and 5 categorical. See
the data dictionary for definitions.
claims <- read.csv("Insurance_Claims.csv", stringsAsFactors = TRUE)
claims$claim_id <- NULL # an ID, not a predictor
str(claims)
'data.frame': 2500 obs. of 15 variables:
$ claim_amount_k : num 2.6 6.5 4.1 2.3 3.9 46.2 2 20.3 14.4 5.9 ...
$ claim_type : Factor w/ 4 levels "Auto","Home",..: 4 2 1 1 2 1 2 3 1 2 ...
$ days_to_report : int 16 34 7 4 9 15 38 3 4 30 ...
$ police_report : Factor w/ 2 levels "No","Yes": 2 1 2 2 1 2 1 1 2 2 ...
$ witness_present : Factor w/ 2 levels "No","Yes": 2 1 2 2 1 1 1 2 2 1 ...
$ documents_submitted: int 5 5 2 4 12 7 11 7 7 6 ...
$ channel : Factor w/ 3 levels "Agent","Online",..: 1 3 1 2 2 1 3 1 2 3 ...
$ policy_tenure_years: num 2.6 7.5 1 8 0.7 2.1 3.8 4.7 12.4 7.2 ...
$ prior_claims : int 0 1 1 1 1 0 1 0 1 0 ...
$ customer_age : int 53 53 27 48 52 44 53 32 40 81 ...
$ credit_score : int 823 659 564 691 807 583 692 560 744 699 ...
$ coverage_limit_k : num 190 211 245 231 253 ...
$ annual_premium_k : num 1.45 1.57 1.86 1.79 1.79 1.88 0.79 1.12 2.83 1.98 ...
$ region : Factor w/ 4 levels "Midwest","Northeast",..: 3 2 1 4 4 4 1 2 4 3 ...
$ fraud : int 0 0 0 0 0 0 0 0 0 0 ...
mean(claims$fraud) # share of claims that are fraudulent
[1] 0.158
Step 1: Which R function?
You want to run a stepwise selection using AIC that starts from the
intercept-only model (null) and can add any predictor
(full). Which R call does that?
A.
summary(glm(fraud ~ ., family = binomial, data = claims))
B. drop1(full, test = "LRT")
C.
step(null, scope = formula(full), direction = "both")
D. step(null, direction = "both")
Instructor: Answer C. step() runs the search: it starts from null, scope = formula(full) lets any of the 14 candidates enter, and direction = “both” lets terms enter and leave. A fits all 14 predictors at once (AIC 1871.52, an option in Step 2); nothing is selected. B tests dropping each term from the full model one at a time; it does not search. D has no scope, so no predictor can enter and the result stays fraud ~ 1 (AIC 2183.69). Aside: starting from full with direction = “both” reaches the same 11 predictors in this data, but the task is to start from the intercept-only model.
Step 2: Run the code and interpret the results
With fraud as the outcome variable, start from the intercept-only model and run stepwise selection by AIC on all 14 candidate predictors. Which predictors are in the final model, and what is its AIC?
A. All 14 candidates; AIC = 1871.52.
B. All 14 candidates; AIC = 1871.52, because AIC always falls when a
predictor is added.
C. 11 predictors (all but coverage_limit_k,
annual_premium_k and region); AIC =
1867.79.
D. 10 predictors (customer_age is also left out); AIC =
1870.54.
E. 11 predictors (all but coverage_limit_k,
annual_premium_k and region); AIC = 1867.79,
so those three have no relationship with fraud.
How to read it
| The question says | So you … |
|---|---|
| “start from the intercept-only model” | Fit fraud ~ 1 first; it is where the search
begins. |
| “stepwise selection by AIC” | step() with direction = "both": terms can
enter and leave. |
| “all 14 candidate predictors” | The upper scope is the full model, fraud ~ . |
| “final model … AIC” | Read the last row of the search path, or
AIC(final). |
null <- glm(fraud ~ 1, family = binomial, data = claims)
full <- glm(fraud ~ ., family = binomial, data = claims)
final <- step(null, scope = formula(full),
direction = "both", trace = 0)
final$anova # the search path
Step Df Deviance Resid. Df Resid. Dev AIC
1 NA NA 2499 2181.692 2183.692
2 + claim_amount_k -1 85.091404 2498 2096.601 2100.601
3 + police_report -1 78.219031 2497 2018.382 2024.382
4 + days_to_report -1 32.324816 2496 1986.057 1994.057
5 + documents_submitted -1 25.395704 2495 1960.662 1970.662
6 + claim_type -3 29.031767 2492 1931.630 1947.630
7 + credit_score -1 23.472397 2491 1908.157 1926.157
8 + policy_tenure_years -1 21.752913 2490 1886.404 1906.404
9 + prior_claims -1 18.192298 2489 1868.212 1890.212
10 + channel -2 15.715911 2487 1852.496 1878.496
11 + witness_present -1 9.958725 2486 1842.537 1870.537
12 + customer_age -1 4.742725 2485 1837.795 1867.795
AIC(final)
[1] 1867.795
What the code does
glm(fraud ~ 1, ...) fits the intercept-only model
null: the starting point of the search.glm(fraud ~ ., ...) fits the full model with all 14
candidates; here it only sets the upper limit (scope) of
the search.step(null, scope = formula(full), direction = "both")
adds or removes one term at a time, always taking the move that lowers
AIC most, and stops when no move lowers AIC.final$anova prints the search path;
AIC(final) prints the AIC of the model where the search
stopped.What the output shows
The search path starts at AIC = 2183.69 (intercept only).
claim_amount_k enters first because it lowers AIC the most
(to 2100.60), then police_report (2024.38), and so on.
Every step is an addition (+); nothing is removed. The last step adds
customer_age (1870.54 → 1867.79). The search stops at
AIC = 1867.79 with 11 predictors because adding
coverage_limit_k, annual_premium_k or
region would raise AIC. Being left out means a predictor
adds too little once the others are in; it does not prove that
it is unrelated to fraud.
Result. The search adds 11 predictors and removes
none; it stops at AIC = 1867.79 because adding
coverage_limit_k, annual_premium_k or
region would not lower AIC.
Answer C. A predictor left out adds too little once the others are in; that is not the same as having no relationship with fraud (option E). 1871.52 is the full model’s AIC; 1870.54 is one step before the search ends.
Step 1: Which R function?
You want a likelihood-ratio test that compares the final model
(final) with the full model (full). Which R
call gives it?
A. anova(final, full, test = "LRT")
B. drop1(full, test = "LRT")
C. anova(null, final, test = "LRT")
D. AIC(final, full)
Instructor: Answer A. anova() with two nested models gives one likelihood-ratio test; final vs. full tests the three predictors stepwise left out together (LR χ²(5) = 6.27, p = .280). Put the smaller model first. B tests dropping each term from the full model one at a time, not the three together. C compares final with the intercept-only model, so it tests the final model’s own predictors. D lists the two AICs; it is not a test.
Step 2: Run the code and interpret the results
Use a likelihood-ratio test to compare the final model from stepwise selection with the full model that contains all 14 candidate predictors. Which response states the result?
A. LR χ²(5) = 6.27, p = .280: the three left-out predictors do not
significantly improve the fit, so keep the final model.
B. LR χ²(5) = 6.27, p = .280: the full model fits significantly better,
so keep all 14 predictors.
C. χ²(2485) = 1837.79: the final model does not fit the data, so the
full model is needed.
D. LR χ²(5) = 6.27, p = .280: the three left-out predictors therefore
have no relationship with fraud.
E. LR χ²(3) = 6.27, p = .099: the three left-out predictors do not
significantly improve the fit, so keep the final model.
How to read it
| The question says | So you … |
|---|---|
| “compare the final model … with the full model” | Two nested models: final sits inside
full. |
| “likelihood-ratio test” | anova(final, full, test = "LRT"), smaller model
first. |
| Degrees of freedom | Count parameters, not predictors: 3 predictors were left out, but
region has 3 dummies, so df = 5. |
| “states the result” | Pick the option with the right χ², df and the right conclusion. |
anova(final, full, test = "LRT")
Analysis of Deviance Table
Model 1: fraud ~ claim_amount_k + police_report + days_to_report + documents_submitted +
claim_type + credit_score + policy_tenure_years + prior_claims +
channel + witness_present + customer_age
Model 2: fraud ~ claim_amount_k + claim_type + days_to_report + police_report +
witness_present + documents_submitted + channel + policy_tenure_years +
prior_claims + customer_age + credit_score + coverage_limit_k +
annual_premium_k + region
Resid. Df Resid. Dev Df Deviance Pr(>Chi)
1 2485 1837.8
2 2480 1831.5 5 6.2749 0.2804
What the code does
anova(final, full, test = "LRT") compares two nested
models: final (11 predictors) sits inside full
(all 14).Deviance column is the
likelihood-ratio χ²; Df is the number of extra parameters
in the larger model.What the output shows
The residual deviance falls from 1837.79 (final, 2485 df) to 1831.52
(full, 2480 df): a drop of 6.27 on 5 df, p = .280. The
df is 5, not 3, because region has 4 levels and uses 3
parameters. Since p > .05, adding the three left-out predictors back
does not significantly improve the fit, so the simpler final model is
preferred. This supports the stepwise result from Q1.
Result. LR χ²(5) = 6.27, p = .280. Adding
coverage_limit_k, annual_premium_k and
region back does not significantly improve the fit, so the
simpler final model is preferred.
Answer A. A non-significant test says the extra predictors add too little once the others are in; it does not mean they are unrelated to fraud (option D). The df is 5, not 3, because
regionuses 3 parameters.
Step 1: Which R function?
You want to test whether claim_type, as a whole,
improves final after accounting for the other predictors.
Which R call gives that test?
A. summary(final), reading the Wald test in each
claim_type row
B.
anova(update(final, . ~ . - claim_type), final, test = "LRT")
C. anova(final, test = "Chisq"), reading the
claim_type row
D.
anova(glm(fraud ~ claim_type, family = binomial, data = claims), test = "Chisq")
Instructor: Answer B. Compare the final model with the same model minus claim_type; anova() of the two gives one likelihood-ratio test of all 3 dummies with every other predictor still in (LR χ²(3) = 29.09). A gives one Wald test per dummy (Theft vs. Auto, and so on), not the factor as a whole. C is a sequential test: claim_type is tested only after the terms entered before it, so the result depends on term order (here 29.03; it would be 40.05 if claim_type came first). D fits claim_type alone, so nothing is adjusted for (LR χ²(3) = 40.05).
Step 2: Run the code and interpret the results
In the final model, test whether claim_type, considered as a whole, significantly improves the fit after accounting for the other predictors. Which response gives the correct test and conclusion?
A. LR χ²(3) = 40.05, p < .001, from a model with
claim_type alone: this adjusts for the other
predictors.
B. LR χ²(3) = 29.09, p < .001: every claim type differs significantly
from Auto claims.
C. Wald χ²(1) = 27.53, p < .001 for Theft: claim type is related to
fraud after accounting for the other predictors.
D. LR χ²(3) = 29.09, p < .001: claim type is related to fraud after
accounting for the other predictors.
E. Wald χ²(1) = 27.53, p < .001 for Theft: the level with the
smallest p-value settles the test for the factor.
How to read it
| The question says | So you … |
|---|---|
| “considered as a whole” | Remove all of the factor’s dummies at once (3 df), not one level. |
| “after accounting for the other predictors” | Drop it from the final model, with everything else still in. |
| “likelihood-ratio” | anova(smaller, larger, test = "LRT") compares the two
nested models. |
no_type <- update(final, . ~ . - claim_type) # final model without claim_type
anova(no_type, final, test = "LRT")
Analysis of Deviance Table
Model 1: fraud ~ claim_amount_k + police_report + days_to_report + documents_submitted +
credit_score + policy_tenure_years + prior_claims + channel +
witness_present + customer_age
Model 2: fraud ~ claim_amount_k + police_report + days_to_report + documents_submitted +
claim_type + credit_score + policy_tenure_years + prior_claims +
channel + witness_present + customer_age
Resid. Df Resid. Dev Df Deviance Pr(>Chi)
1 2488 1866.9
2 2485 1837.8 3 29.088 2.146e-06 ***
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
What the code does
update(final, . ~ . - claim_type) refits the final
model without claim_type, keeping every other
predictor.anova(no_type, final, test = "LRT") compares the models
without and with claim_type: one test of all three of its
dummies together.What the output shows
Removing claim_type raises the deviance by 29.09
on 3 df (p < .001). So claim type is significantly related
to fraud after accounting for the other predictors. The 3 df
are the three dummies (Home, Injury, Theft vs. the reference, Auto). The
single Wald test for Theft in summary(final) answers a
narrower question (Theft vs. Auto only), and a model with
claim_type alone (LR χ²(3) = 40.05) adjusts for
nothing.
Result. LR χ²(3) = 29.09, p < .001: removing all
three claim_type dummies from the final model significantly
worsens the fit.
Answer D. One level’s Wald test is not the test of the whole factor, and a model with claim_type alone does not adjust for anything.
Step 1: Which R function?
Model m has police_report,
channel and their interaction. You want a
likelihood-ratio test for each term. Which R code gives it?
A. summary(m), reading the Wald test in each row
B. anova(null, m, test = "Chisq")
C. exp(coef(m)), reading each odds ratio
D. anova(m, test = "Chisq")
Instructor: Answer D. anova() with one model gives one likelihood-ratio test per term, added in order: police_report, then channel, then the interaction after both main effects (LR χ²(2) = 7.83, p = .020). A gives one Wald test per coefficient, so the 2-df interaction is split across two rows. B is one overall test of the whole model (LR χ²(5) = 102.16). C gives odds ratios, not tests.
Step 2: Run the code and interpret the results
Fit a model with police_report, channel and their interaction. Use likelihood-ratio tests to decide whether each term is significant. Which response is correct?
A. All three terms are significant; the interaction (LR χ²(2) = 7.83,
p = .020) means a police report has the same effect on fraud in every
channel.
B. All three terms are significant; the interaction (LR χ²(2) = 7.83, p
= .020) means the effect of a police report on fraud depends on the
channel.
C. All three terms are significant; the interaction (LR χ²(1) = 7.83, p
= .005) means the effect of a police report on fraud depends on the
channel.
D. The interaction is not significant, because the Wald test for
police_reportYes:channelPhone gives p = .071; a police
report has the same effect in every channel.
E. The terms are significant together (LR χ²(5) = 102.16, p < .001),
so each term is also significant on its own.
How to read it
| The question says | So you … |
|---|---|
| “police_report, channel and their interaction” | police_report * channel fits both main effects plus
police_report:channel. |
| “whether each term is significant” | anova(m, test = "Chisq"): one likelihood-ratio test per
term; the interaction is tested last, after both main effects. |
| Degrees of freedom | channel has 3 levels, so 2 df; the interaction has 1 ×
2 = 2 df. |
m <- glm(fraud ~ police_report * channel, family = binomial, data = claims)
anova(m, test = "Chisq") # one row per term; interaction last
Analysis of Deviance Table
Model: binomial, link: logit
Response: fraud
Terms added sequentially (first to last)
Df Deviance Resid. Df Resid. Dev Pr(>Chi)
NULL 2499 2181.7
police_report 1 81.886 2498 2099.8 < 2.2e-16 ***
channel 2 12.438 2496 2087.4 0.001991 **
police_report:channel 2 7.831 2494 2079.5 0.019934 *
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
What the code does
police_report * channel fits both main effects and
their interaction (police_report:channel).anova(m, test = "Chisq") gives one likelihood-ratio
test per term, added in order: police_report, then
channel, then the interaction after both main effects.What the output shows
Read the interaction row first: LR χ²(2) = 7.83, p =
.020. It is significant, so the effect of a police report on
fraud depends on the channel. Fraud rates show how: with no police
report vs. a report, Agent claims are 22.8% vs. 6.2%, Online 25.1%
vs. 13.7% and Phone 18.6% vs. 8.5%. A report lowers fraud in every
channel, but proportionally least for online claims. The interaction has
2 df = (2 − 1) × (3 − 1). Both main effects are also significant
(police_report LR χ²(1) = 81.89, p < .001;
channel LR χ²(2) = 12.44, p = .002), but with a significant
interaction neither describes a single, constant effect.
Result. police_report LR χ²(1) = 81.89,
p < .001; channel LR χ²(2) = 12.44, p = .002;
interaction LR χ²(2) = 7.83, p = .020.
Answer B. A significant interaction means the effect of a police report depends on the channel (option A says the opposite). The interaction has 2 df, not 1, and one dummy’s Wald p-value does not test the whole interaction.
Step 1: Which R function?
You want to predict fraud when the predicted probability is 0.25 or higher, then get the sensitivity, specificity and accuracy. Which R code does that?
A. predict(final), then confusionMatrix()
of p >= 0.25 with positive = "1"
B.
auc(roc(claims$fraud, predict(final, type = "response")))
C. predict(final, type = "response"), then
confusionMatrix() of p >= 0.25 with
positive = "1"
D. predict(final, type = "response"), then
confusionMatrix() of p >= 0.25 with
positive = "0"
Instructor: Answer C. predict(type = “response”) gives probabilities; a 0/1 prediction at p >= 0.25 goes into confusionMatrix() with positive = “1” so fraud is the event (sensitivity .463, specificity .866, accuracy .802). A is the trap: without type = “response”, predict() returns log-odds, so p >= 0.25 is the wrong cutoff (it catches only 44 frauds). B gives the AUC, not sensitivity or specificity. D makes legitimate (0) the event, so the sensitivity and specificity swap (.866 and .463).
Step 2: Run the code and interpret the results
Using the final model, predict that a claim is fraudulent when its predicted probability is 0.25 or higher. What are the sensitivity, specificity and overall accuracy of these predictions?
A. Sensitivity .393, specificity .866, accuracy .802: the rule
correctly identifies 39.3% of fraudulent and 86.6% of legitimate
claims.
B. Sensitivity .866, specificity .463, accuracy .802: the rule correctly
identifies 86.6% of fraudulent and 46.3% of legitimate claims.
C. Sensitivity .152, specificity .985, accuracy .854: the rule correctly
identifies 15.2% of fraudulent and 98.5% of legitimate claims.
D. Sensitivity .463, specificity .866, accuracy .802: the rule correctly
identifies 80.2% of the fraudulent claims.
E. Sensitivity .463, specificity .866, accuracy .802: the rule correctly
identifies 46.3% of fraudulent and 86.6% of legitimate claims.
How to read it
| The question says | So you … |
|---|---|
| “predicted probability” | predict(final, type = "response"); without
type = "response" you get log-odds. |
| “0.25 or higher” | Predict 1 when p >= 0.25 (not 0.5, not
>). |
| “sensitivity … specificity … accuracy” | confusionMatrix(..., positive = "1") reports all three,
with fraud (1) as the event. |
library(caret)
Loading required package: ggplot2
Loading required package: lattice
p <- predict(final, type = "response") # predicted probabilities
pred <- factor(as.integer(p >= 0.25), levels = c(0, 1))
confusionMatrix(pred, factor(claims$fraud), positive = "1")
Confusion Matrix and Statistics
Reference
Prediction 0 1
0 1822 212
1 283 183
Accuracy : 0.802
95% CI : (0.7858, 0.8175)
No Information Rate : 0.842
P-Value [Acc > NIR] : 1.000000
Kappa : 0.3065
Mcnemar's Test P-Value : 0.001654
Sensitivity : 0.4633
Specificity : 0.8656
Pos Pred Value : 0.3927
Neg Pred Value : 0.8958
Prevalence : 0.1580
Detection Rate : 0.0732
Detection Prevalence : 0.1864
Balanced Accuracy : 0.6644
'Positive' Class : 1
What the code does
predict(final, type = "response") returns each claim’s
predicted probability of fraud (without type = "response"
you get log-odds).as.integer(p >= 0.25) turns each probability into a
prediction: 1 (fraud) at 0.25 or higher, 0 otherwise;
factor(..., levels = c(0, 1)) keeps both classes even if
one is empty.confusionMatrix(pred, factor(claims$fraud), positive = "1")
cross-tabulates predictions (rows) against the actual outcome (columns,
“Reference”) and makes fraud (1) the event.What the output shows
The table has TP = 183 (frauds flagged), FN = 212 (frauds missed), FP
= 283 (legitimate claims flagged) and TN = 1822. Sensitivity =
.463: the rule flags 46.3% of the 395 fraudulent claims.
Specificity = .866: it clears 86.6% of the legitimate
claims. Accuracy = .802, which is below the No
Information Rate of .842 (never flag fraud). That is the price of a low
cutoff: it catches far more fraud than the 0.5 cutoff (sensitivity .152)
but flags more legitimate claims. Pos Pred Value (.393) is
precision: of the flagged claims, 39.3% are fraudulent.
Result. TP = 183, FN = 212, FP = 283, TN = 1822. Sensitivity = 183/395 = .463; specificity = 1822/2105 = .866; accuracy = (183 + 1822)/2,500 = .802.
Answer E. .393 is precision, TP/(TP + FP); swapping the two rates is a common slip; .854 is the accuracy at 0.5, not 0.25.
At a cutoff of 0.5, confusionMatrix() prints the table
below. What is the sensitivity?
Reference
Prediction 0 1
0 2074 335
1 31 60
A. 60 / 395 = .152
B. 60 / 91 = .659
C. (60 + 2,074) / 2,500 = .854
D. 2,074 / 2,105 = .985
Instructor: Answer A. Sensitivity = caught frauds / all actual frauds = 60 / 395 = .152. B is precision, C is accuracy, D is specificity. Accuracy is 85.4% only because most claims are legitimate: never flagging fraud is already 84.2% accurate. This sets up Q6 (Youden’s J).
Step 1: Which R function?
You want the cutoff with the largest Youden’s J and the AUC for the final model. Which R code gives both?
A. roc(), then auc() and
coords(..., "best", best.method = "youden")
B. table() at a cutoff of 0.5, then compute sensitivity +
specificity − 1
C. anova(null, final, test = "LRT")
D. roc(), then auc() and
coords(..., x = 0.5)
Instructor: Answer A. roc() (pROC) builds the curve from the actual outcome and fitted probabilities; auc() gives 0.768; coords(“best”, best.method = “youden”) searches every cutoff and returns 0.156. B computes J at one cutoff only. C is the overall likelihood-ratio test. D reports sensitivity and specificity at 0.5 only; it does not search.
Step 2: Run the code and interpret the results
Using the final model’s predicted probabilities, find the cutoff with the largest Youden’s J and compute the area under the ROC curve (AUC). Which response is correct?
A. Cutoff 0.156 (sensitivity .691, specificity .700); AUC = .232: the
model ranks fraudulent claims below legitimate ones more often than
not.
B. Cutoff 0.156 (sensitivity .691, specificity .700); AUC = .698, the
accuracy at this cutoff.
C. Cutoff 0.156 (sensitivity .691, specificity .700); AUC = .768: a
random fraud claim outscores a random legitimate one 76.8% of the
time.
D. Cutoff 0.156 (sensitivity .691, specificity .700); AUC = .768: the
model classifies 76.8% of all claims correctly at its best cutoff.
E. Cutoff 0.500 (sensitivity .152, specificity .985), the best cutoff
because its overall accuracy is the highest of all; AUC = .768.
How to read it
| The question says | So you … |
|---|---|
| “largest Youden’s J” | J = sensitivity + specificity − 1:
coords(…, "best", best.method = "youden"). |
| “area under the ROC curve” | auc() of the ROC curve built from the predicted
probabilities. |
| “Which response is correct?” | Check every part: cutoff, both rates, the AUC and its meaning. |
library(pROC)
Type 'citation("pROC")' for a citation.
Attaching package: 'pROC'
The following objects are masked from 'package:stats':
cov, smooth, var
roc_final <- roc(claims$fraud, p)
Setting levels: control = 0, case = 1
Setting direction: controls < cases
auc(roc_final)
Area under the curve: 0.7676
coords(roc_final, "best", best.method = "youden",
ret = c("threshold", "sensitivity", "specificity"))
threshold sensitivity specificity
1 0.1559885 0.6911392 0.6997625
What the code does
roc(claims$fraud, p) builds the ROC curve from the
actual outcome and the predicted probabilities p (from
Q5).auc(roc_final) gives the area under that curve.coords(..., "best", best.method = "youden") searches
every cutoff and returns the one with the largest sensitivity +
specificity − 1.What the output shows
AUC = .768: if we pick one fraudulent and one legitimate claim at random, the model gives the fraudulent claim the higher probability 76.8% of the time (0.5 = guessing, 1 = perfect). The Youden cutoff is 0.156, close to the fraud rate (15.8%), not 0.5. At that cutoff sensitivity = .691 and specificity = .700, so J = .391: it balances the two errors. The 0.5 cutoff has higher accuracy (.854) only because most claims are legitimate; it catches just 15.2% of the frauds.
Result. Youden cutoff = 0.156 (sensitivity .691, specificity .700); AUC = .768.
Answer C. The AUC is about ranking, not the share classified correctly; 0.5 has the highest accuracy only because most claims are legitimate; .232 is 1 − AUC, from reversing the outcome.
Step 1: Which R function?
Model m_lin contains centered age, age_c.
You want to test whether adding its square improves the fit. Which R
code does that?
A. anova(null, m_sq, test = "LRT"), comparing with the
intercept-only model
B. drop1(m_sq, test = "LRT"), reading the
age_c row
C. update(m_lin, . ~ . + age_c^2), then
anova()
D. update(m_lin, . ~ . + I(age_c^2)), then
anova(m_lin, m_sq)
Instructor: Answer D. Inside a formula, a square must be wrapped in I(); then anova(m_lin, m_sq, test = “LRT”) compares the models with and without it (LR χ²(1) = 15.81). A is an overall test of every predictor. B tests the linear term while keeping its square, which breaks the hierarchy (the I(age_c^2) row would be fine). C is the trap: without I(), age_c^2 means age_c crossed with itself, which is just age_c, so nothing is added.
Step 2: Run the code and interpret the results
Subtract the mean from customer_age. In the final model, replace customer_age with the centered variable and its square, and compare the models with and without the squared term using a likelihood-ratio test. Does the squared term belong in the model?
A. LR χ²(1) = 15.81, p < .001: keep the squared term and the
linear term, since the squared term significantly improves the
fit.
B. LR χ²(1) = 4.74, p = .029: keep only the linear term, since age
entered the stepwise model as a straight line.
C. LR χ²(1) = 15.81, p < .001: keep the squared term but drop the
linear term it replaces.
D. LR χ²(2) = 20.55, p < .001: keep the squared term and the linear
term, since the squared term significantly improves the fit.
E. LR χ²(2) = 20.55, p < .001: customer age matters overall, so its
squared term must be kept as well.
How to read it
| The question says | So you … |
|---|---|
| “subtract the mean” | Center first:
age_c = customer_age − mean(customer_age). |
| “the centered variable and its square” | age_c + I(age_c^2); I() is needed inside a
formula. |
| “with and without the squared term” | Two nested models that differ only by I(age_c^2):
compare with anova(). |
claims$age_c <- claims$customer_age - mean(claims$customer_age)
m_lin <- update(final, . ~ . - customer_age + age_c, data = claims)
m_sq <- update(m_lin, . ~ . + I(age_c^2))
anova(m_lin, m_sq, test = "LRT")
Analysis of Deviance Table
Model 1: fraud ~ claim_amount_k + police_report + days_to_report + documents_submitted +
claim_type + credit_score + policy_tenure_years + prior_claims +
channel + witness_present + age_c
Model 2: fraud ~ claim_amount_k + police_report + days_to_report + documents_submitted +
claim_type + credit_score + policy_tenure_years + prior_claims +
channel + witness_present + age_c + I(age_c^2)
Resid. Df Resid. Dev Df Deviance Pr(>Chi)
1 2485 1837.8
2 2484 1822.0 1 15.811 7.001e-05 ***
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
What the code does
claims$customer_age - mean(claims$customer_age) centers
age: age_c = 0 at the mean age, which keeps age and age²
from overlapping.update(final, . ~ . - customer_age + age_c) swaps age
for centered age; the fit is the same, only the coding changes.update(m_lin, . ~ . + I(age_c^2)) adds the squared
term; I() makes R square the variable (without it,
^ has a different meaning in a formula).anova(m_lin, m_sq, test = "LRT") tests whether the
squared term improves the fit.What the output shows
Adding the squared term lowers the deviance by 15.81 on 1 df (p < .001), so the relationship between age and fraud is curved and the squared term should be kept, together with its linear term. The squared coefficient is negative (-0.00107), so the curve is an upside-down U: the log-odds of fraud are highest at about age 41 (the mean age is 46.3) and lower for younger and older customers. The LR χ²(2) = 20.55 result tests both age terms at once; it does not test the curvature.
Result. LR χ²(1) = 15.81, p < .001. The squared coefficient is negative: the odds of fraud peak at about age 41 and fall on either side.
Answer A. A squared term stays together with its linear term; 20.55 on 2 df tests both age terms at once, not the curvature.
Step 1: Which R function?
You have fitted m_main (main effects only) and
m_int (main effects plus all two-way interactions). Which R
code tests whether the interactions improve the fit?
A. drop1(m_int, test = "LRT"), one row per
interaction
B. anova(m_main, m_int, test = "LRT")
C. anova(null, m_int, test = "LRT")
D. AIC(m_main, m_int)
Instructor: Answer B. anova() of the two nested models gives one likelihood-ratio test of the three interactions together (LR χ²(3) = 13.86, p = .003). A tests each interaction on its own, not the three together. C compares m_int with the intercept-only model, so it tests every term (LR χ²(6) = 184.19). D lists the two AICs; it is not a test.
Step 2: Run the code and interpret the results
Fit a model with the main effects of claim_amount_k, police_report and witness_present, and a second model that adds all two-way interactions among them. Compare the two models with a likelihood-ratio test (α = .05). Does adding the interactions significantly improve the fit?
A. Yes (LR χ²(3) = 13.86, p = .003): each of the three interactions
is therefore significant on its own.
B. Yes (LR χ²(6) = 13.86, p = .031): adding the interactions
significantly improves the fit, so keep the interaction model.
C. No: the AUC barely changes when the interactions are added (.694 to
.696), so keep the main-effects model.
D. Yes (LR χ²(3) = 13.86, p = .003): adding the interactions
significantly improves the fit, so keep the interaction model.
E. No (LR χ²(3) = 13.86, p = .003): the main-effects model fits
significantly better, so drop the interactions.
How to read it
| The question says | So you … |
|---|---|
| “a model with the main effects” | m_main: the three predictors, no interactions. |
| “adds all two-way interactions” | Shortcut: (a + b + c)^2 gives the main effects and all
three pairs. |
| “compare the two models … likelihood-ratio test” | anova(m_main, m_int, test = "LRT"), smaller model
first. |
| Degrees of freedom | One per added interaction: df = 3. |
m_main <- glm(fraud ~ claim_amount_k + police_report + witness_present,
family = binomial, data = claims)
m_int <- glm(fraud ~ (claim_amount_k + police_report + witness_present)^2,
family = binomial, data = claims)
anova(m_main, m_int, test = "LRT")
Analysis of Deviance Table
Model 1: fraud ~ claim_amount_k + police_report + witness_present
Model 2: fraud ~ (claim_amount_k + police_report + witness_present)^2
Resid. Df Resid. Dev Df Deviance Pr(>Chi)
1 2496 2011.4
2 2493 1997.5 3 13.865 0.003095 **
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
What the code does
m_main has the three main effects only.(claim_amount_k + police_report + witness_present)^2
expands to the three main effects plus all three two-way
interactions.anova(m_main, m_int, test = "LRT") tests the three
interactions together: one test, 3 df.What the output shows
Adding the interactions lowers the deviance by 13.86 on 3
df (p = .003), so as a group they significantly improve the fit
and the interaction model is preferred. This is a test of the three
together; it does not show that each interaction matters. Testing them
one at a time (drop1(m_int, test = "LRT")) shows that only
claim_amount_k × police_report is significant
on its own (LR χ²(1) = 13.54, p < .001): larger claims are more
suspicious when there is no police report. The AUC barely changes (.694
to .696), but the AUC measures ranking, not fit.
Result. LR χ²(3) = 13.86, p = .003. Adding the three interactions significantly improves the fit.
Answer D. The test is for the three interactions as a group; it does not make each one significant (only
claim_amount_k×police_reportis). The df is 3, one per added interaction. The AUC asks about ranking claims, not about fit.
Step 1: Which R function?
You want to know whether each slope in the final model
(final) differs significantly from zero. Which R code shows
that?
A. summary(final), reading the Wald z test in each
row
B. anova(null, final, test = "LRT")
C. exp(coef(final)), reading each odds ratio
D. Anova(final, type = "III", test.statistic = "LR"), one
row per predictor
Instructor: Answer A. summary() gives one Wald z test per slope (14 rows plus the intercept); read the Pr(>|z|) column. B is one overall test of all slopes together. C gives odds ratios, not tests. D tests each predictor as a whole, so a factor’s 3 slopes share one row; it cannot show that claim_typeHome on its own is not significant.
Step 2: Run the code and interpret the results
In the final model, use α = .05 to decide whether every slope is significantly different from zero. Which response is correct?
A. Yes: all 11 predictors in the final model are significant as a
whole (each p < .05), so every one of its slopes is significant
too.
B. No: claim_typeHome, channelPhone and
customer_age (p = .030) are not significant, because each
of their p-values is above .01.
C. Yes: the overall test (LR χ²(14) = 343.90, p < .001) shows that
every slope in the final model is significant on its own.
D. No: claim_typeHome (p = .099) and
channelPhone (p = .947) are not significant, so
claim_type and channel should both be
removed from the final model entirely.
E. No: claim_typeHome (p = .099) and
channelPhone (p = .947) are not significant, so Home and
Phone claims do not differ significantly from their reference
levels.
How to read it
| The question says | So you … |
|---|---|
| “every slope” | Every coefficient except the intercept: 14 here, because
claim_type adds 3 and channel adds 2. |
| “significantly different from zero” | The Pr(>|z|) column of summary(final):
one Wald test per slope. |
| “α = .05” | Compare each p-value with .05, not .01. |
| Factor slopes | Each dummy compares one level with the reference: Auto for
claim_type, Agent for channel. |
summary(final) # Pr(>|z|) column: one Wald test per slope
Call:
glm(formula = fraud ~ claim_amount_k + police_report + days_to_report +
documents_submitted + claim_type + credit_score + policy_tenure_years +
prior_claims + channel + witness_present + customer_age,
family = binomial, data = claims)
Coefficients:
Estimate Std. Error z value Pr(>|z|)
(Intercept) 2.192043 0.750493 2.921 0.003491 **
claim_amount_k 0.031061 0.003534 8.789 < 2e-16 ***
police_reportYes -1.094611 0.130935 -8.360 < 2e-16 ***
days_to_report 0.033311 0.005252 6.342 2.27e-10 ***
documents_submitted -0.142395 0.029114 -4.891 1.00e-06 ***
claim_typeHome 0.269138 0.163358 1.648 0.099447 .
claim_typeInjury 0.511914 0.176287 2.904 0.003686 **
claim_typeTheft 0.876712 0.167099 5.247 1.55e-07 ***
credit_score -0.005216 0.001024 -5.094 3.50e-07 ***
policy_tenure_years -0.050660 0.011705 -4.328 1.50e-05 ***
prior_claims 0.282388 0.064494 4.379 1.19e-05 ***
channelOnline 0.506006 0.135981 3.721 0.000198 ***
channelPhone 0.010752 0.161837 0.066 0.947028
witness_presentYes -0.424655 0.138845 -3.058 0.002225 **
customer_age -0.009320 0.004295 -2.170 0.030006 *
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
(Dispersion parameter for binomial family taken to be 1)
Null deviance: 2181.7 on 2499 degrees of freedom
Residual deviance: 1837.8 on 2485 degrees of freedom
AIC: 1867.8
Number of Fisher Scoring iterations: 5
What the code does
summary(final) prints one row per coefficient: the
estimate (log-odds), its standard error, the Wald z statistic and
Pr(>|z|).claim_type,
Agent for channel).What the output shows
Of the 14 slopes, 12 have p < .05. The two that do not are
claim_typeHome (p = .099): Home claims are
not significantly different from Auto claims, and
channelPhone (p = .947): Phone claims are
not significantly different from Agent claims, holding the other
predictors constant. So not every slope is significant. That does not
mean claim_type or channel should be dropped:
each is significant as a whole (Q3 for claim_type), and the
other dummies are significant.
Result. 12 of 14 slopes have p < .05.
claim_typeHome (p = .099) and channelPhone (p
= .947) do not.
Answer E. A non-significant dummy means that level does not differ from its reference level; claim_type and channel are still significant as a whole (Q3), so they stay. The overall test says the slopes help together, not that each one is significant.
Step 1: Which R function?
Model final uses Auto as the reference level of
claim_type. You want the odds ratio for Theft claims
compared with Home claims. Which R code gives it?
A. exp(coef(final)), reading the
claim_typeTheft row
B. coef(final), reading the claim_typeTheft
row
C. relevel() with ref = "Theft", refit, then
exp(coef())
D. relevel() with ref = "Home", refit, then
exp(coef())
Instructor: Answer D. R uses the first level alphabetically (Auto) as the reference, so set Home first and refit; exp(coef()) then gives Theft vs. Home = 1.84. A compares Theft with Auto (2.40). B is a log odds ratio, not an odds ratio. C makes Theft the reference, so its estimates compare other types with Theft (Home vs. Theft = 0.54).
Step 2: Run the code and interpret the results
In the final model, set Home as the reference level of claim_type. What is the odds ratio for Theft claims compared with Home claims, and what does it mean?
A. 0.54: since this is below 1, Theft claims have lower odds of fraud
than Home claims, holding the other predictors constant.
B. 1.84: holding the other predictors constant, the odds of fraud for
Theft claims are 1.84 times the odds for Home claims.
C. 2.40: holding the other predictors constant, the odds of fraud for
Theft claims are 2.40 times the odds for Home claims.
D. 1.84: holding the other predictors constant, Theft claims are 1.84
times as likely to be fraudulent as Home claims.
E. 0.54: holding the other predictors constant, the odds of fraud for
Theft claims are 0.54 times the odds for Home claims.
How to read it
| The question says | So you … |
|---|---|
| “set Home as the reference level” | relevel() the factor, then refit. R’s default reference
is Auto (alphabetical). |
| “odds ratio for Theft … compared with Home” | exp() of the claim_typeTheft coefficient
in the refitted model. |
| “what does it mean” | Odds, not probability, holding the other predictors constant. |
claims$claim_type <- relevel(claims$claim_type, ref = "Home")
final_home <- update(final, data = claims)
exp(coef(final_home))["claim_typeTheft"]
claim_typeTheft
1.835971
What the code does
relevel(claims$claim_type, ref = "Home") makes Home the
reference level (R’s default is the first level alphabetically,
Auto).update(final, data = claims) refits the final model
with the new reference level; nothing else changes.exp(coef(final_home))["claim_typeTheft"] turns the
Theft coefficient (a log odds ratio) into an odds ratio for Theft
vs. Home.What the output shows
OR = 1.84: holding the other predictors constant, the odds of fraud for Theft claims are 1.84 times the odds for Home claims, i.e., about 84% higher. This is a ratio of odds, not of probabilities, so it does not mean Theft claims are 1.84 times as likely to be fraudulent. With the default reference (Auto), the same row would compare Theft with Auto (2.40).
Result. Odds ratio = 1.84. Without
relevel(), the same coefficient compares Theft with Auto
and gives 2.40.
Answer B. 0.54 is the reciprocal (Home vs. Theft); 2.40 uses Auto as the reference; “times as likely” describes probabilities, not odds.
Step 1: Which R function?
You want to check the full model (full) for
multicollinearity among its predictors. Which R code does that?
A.
cor(claims$coverage_limit_k, claims$annual_premium_k)
B. vif(full)
C. summary(full), reading the standard errors
D. Anova(full, type = "III", test.statistic = "LR")
Instructor: Answer B. car::vif() gives one (G)VIF per predictor, so every predictor is checked at once, factors included. A checks only one pair you already suspect (r = 0.97); use it after vif() flags a pair. C shows inflated standard errors but no VIF. D tests each predictor; it does not measure overlap.
Step 2: Run the code and interpret the results
Fit the full model with all 14 candidate predictors and check for multicollinearity with variance inflation factors (VIFs). Which response is correct?
A. coverage_limit_k (17.48) and
annual_premium_k (17.47) have VIFs above 10: they overlap
heavily, so keep only one of them.
B. coverage_limit_k and annual_premium_k have
the largest VIFs (about 17.5), so they are the two strongest predictors
of fraud.
C. coverage_limit_k (17.48) and
annual_premium_k (17.47) have VIFs above 10, so neither of
them is related to fraud.
D. There is no problem: every value in the last column, GVIF^(1/(2*Df)),
is below 10 (the largest is 4.18).
E. claim_type (1.16 on 3 df) and region (1.03
on 3 df) are the problem, because a factor uses more than one df.
How to read it
| The question says | So you … |
|---|---|
| “check for multicollinearity with VIFs” | vif(full) from the car package. |
| Reading the output | Compare the GVIF column with 10, or square the last column (4.18² ≈ 17.5). |
| “which predictors overlap” | cor() of the two flagged predictors: r = 0.97. |
library(car)
Loading required package: carData
vif(full) # compare GVIF with 10 (or square the last column)
GVIF Df GVIF^(1/(2*Df))
claim_amount_k 1.051725 1 1.025536
claim_type 1.155623 3 1.024400
days_to_report 1.023281 1 1.011573
police_report 1.112504 1 1.054753
witness_present 1.017628 1 1.008775
documents_submitted 1.013361 1 1.006659
channel 1.025251 2 1.006254
policy_tenure_years 1.008428 1 1.004205
prior_claims 1.008717 1 1.004349
customer_age 1.011698 1 1.005832
credit_score 1.028290 1 1.014047
coverage_limit_k 17.477446 1 4.180604
annual_premium_k 17.466549 1 4.179300
region 1.029394 3 1.004840
cor(claims$coverage_limit_k, claims$annual_premium_k)
[1] 0.9706788
What the code does
vif(full) (car package) gives a generalized VIF (GVIF)
for each predictor, one row per predictor even for factors.cor() of the two flagged predictors shows how closely
they move together.What the output shows
coverage_limit_k (GVIF = 17.48) and
annual_premium_k (17.47) are far above 10,
while every other GVIF is at most 1.16. The two correlate at r = 0.97:
they carry almost the same information, so each one’s coefficient and
standard error are unstable when both are in the model. The remedy is to
keep one of them (or combine them) and rerun vif(). A high
VIF says nothing about whether a predictor is related to fraud; it
measures overlap among the predictors.
Result. GVIF = 17.48 for
coverage_limit_k and 17.47 for
annual_premium_k; every other GVIF is below 1.16. The two
correlate at r = 0.97.
Answer A. A high VIF means a predictor overlaps with the others, not that it is unrelated to fraud (option C) or strongly related to it. The last column is on a standard-error scale: 4.18 squared is about 17.5.
Step 1: Which R function?
The fraud team wants the lowest-AIC model that can be built from ten
claim and policyholder measures, stored with fraud in
claims_bs. Which R call compares every possible model?
A.
step(null, scope = formula(full), direction = "both")
B. step(full, direction = "backward")
C. bestglm(claims_bs, family = binomial, IC = "AIC")
D. bestglm(claims_bs, family = binomial, IC = "BIC")
Instructor: Answer C. bestglm() fits all 1,023 subsets and ranks them by the criterion in IC. A and B search over all 14 candidates in full, not the ten in claims_bs, and add or remove one term at a time, so they are not a best subset search. D ranks by BIC, which penalizes size more and picks 7 predictors (AIC = 1924.65).
Step 2: Run the code and interpret the results
The fraud team wants the lowest-AIC model that can be built from ten claim and policyholder measures. Use best subset selection by AIC over these candidates: claim_amount_k, days_to_report, police_report, witness_present, documents_submitted, prior_claims, customer_age, coverage_limit_k, annual_premium_k and credit_score. Which response is correct?
A. 8 predictors (all but coverage_limit_k and
annual_premium_k), AIC = 1922.00: so these are the
predictors that truly cause fraud.
B. All 10 candidates, AIC = 1922.27: the lowest AIC of all 1,023
possible models, because adding a predictor never raises AIC.
C. 8 predictors (all but coverage_limit_k and
annual_premium_k), AIC = 1922.00: the lowest AIC of all
1,023 possible models.
D. 7 predictors (customer_age is also left out), AIC =
1924.65: the lowest AIC of all 1,023 possible models.
E. 8 predictors (all but coverage_limit_k and
annual_premium_k), AIC = 1922.00: the lowest AIC among
8-predictor models only.
How to read it
| The question says | So you … |
|---|---|
| “best subset selection” | bestglm() fits every subset: 2¹⁰ − 1 = 1,023
models. |
| “by AIC” | IC = "AIC"; best$BestModel is the
lowest-AIC model. |
| “over ten candidates” | A data frame with only those 10 columns and fraud as the last column. |
library(bestglm)
cand <- c("claim_amount_k", "days_to_report", "police_report", "witness_present",
"documents_submitted", "prior_claims", "customer_age",
"coverage_limit_k", "annual_premium_k", "credit_score")
claims_bs <- claims[, c(cand, "fraud")] # fraud must be the LAST column
best <- bestglm(claims_bs, family = binomial, IC = "AIC")
best$BestModel
What the code does
claims[, c(cand, "fraud")] keeps only the ten
candidates and the outcome; bestglm() needs the outcome as
the last column.bestglm(claims_bs, family = binomial, IC = "AIC") fits
all 2¹⁰ − 1 = 1,023 possible models and ranks them by AIC.best$BestModel prints the lowest-AIC model
(best$Subsets lists the best model of each size).What the output shows
The best model has 8 predictors (all but
coverage_limit_k and annual_premium_k) with
AIC = 1922.00. All 10 candidates give 1922.27, slightly
worse: the overlapping pair adds almost nothing. Best subset guarantees
only that no other subset of these ten candidates has a lower
AIC. It does not guarantee that these predictors cause fraud or that the
model will predict best on new claims. Ranking by BIC instead
(IC = "BIC") penalizes size more and picks 7
predictors.
Result. Best model: 8 predictors, AIC =
1922.00. It leaves out coverage_limit_k
and annual_premium_k; all 10 give 1922.27.
Answer C. Best subset guarantees the lowest AIC among all 1,023 subsets of these candidates, not a causal model or the best model for new data. 1924.65 belongs to the lowest-BIC model, not the lowest-AIC one.
Step 1: Which R function?
k05 holds 3.84, the χ² cutoff for p < .05. You want
forward selection by p-value from null over the candidates
in full. Which R call does that?
A.
step(null, scope = formula(full), direction = "forward")
B.
step(null, scope = formula(full), direction = "forward", k = k05)
C. step(full, direction = "backward", k = k05)
D.
step(null, scope = formula(full), direction = "forward", k = 0.05)
Instructor: Answer B. With k = k05 = 3.84, a 1-df term enters only when its LR χ² exceeds 3.84 (p < .05). A uses the default k = 2, which is AIC. C starts from the full model and removes terms. D is the trap: k is a penalty on the χ² scale, not α; k = 0.05 lets almost any term enter.
Step 2: Run the code and interpret the results
Run forward selection by p-value (a term enters only if p < .05) from the intercept-only model over all 14 candidate predictors. How many predictors are in the final model, and what is its AUC?
A. All 14 predictors; AUC = .770: a randomly chosen fraudulent claim
gets a higher predicted probability than a randomly chosen legitimate
claim 77.0% of the time.
B. 10 predictors (customer_age does not enter, since LR
χ²(1) = 4.74 is below 5); AUC = .768.
C. 11 predictors; AUC = .768: the model correctly flags 76.8% of the
fraudulent claims.
D. 11 predictors; AUC = .768: a randomly chosen fraudulent claim gets a
higher predicted probability than a randomly chosen legitimate claim
76.8% of the time.
E. 11 predictors; AUC = .768: the model classifies 76.8% of all claims
correctly.
How to read it
| The question says | So you … |
|---|---|
| “forward selection … from the intercept-only model” | step(null, scope = formula(full), direction = "forward"). |
| “by p-value (p < .05)” | Add k = k05, where
k05 <- qchisq(0.05, df = 1, lower.tail = FALSE) =
3.84. |
| “its AUC” | roc() with
predict(fwd_p, type = "response"), then
auc(). |
k05 <- qchisq(0.05, df = 1, lower.tail = FALSE) # 3.84
fwd_p <- step(null, scope = formula(full), direction = "forward",
k = k05, trace = 0)
formula(fwd_p)
fraud ~ claim_amount_k + police_report + days_to_report + documents_submitted +
credit_score + claim_type + policy_tenure_years + prior_claims +
channel + witness_present + customer_age
auc(roc(claims$fraud, predict(fwd_p, type = "response")))
Setting levels: control = 0, case = 1
Setting direction: controls < cases
Area under the curve: 0.7676
What the code does
qchisq(0.05, df = 1, lower.tail = FALSE) is 3.84: the
χ² value with p = .05 for a 1-df term.step(..., direction = "forward", k = k05) starts from
null and adds the best term only while its LR χ² exceeds
3.84 (p < .05 for a 1-df term); the default k = 2 would
be AIC.formula(fwd_p) lists the predictors that entered;
auc(roc(...)) uses the predicted probabilities
(type = "response") to compute the AUC.What the output shows
11 predictors enter, the same 11 as stepwise by AIC
in Q1. The last to enter is customer_age (LR χ²(1) = 4.74,
above 3.84). The AUC is .768: a randomly chosen
fraudulent claim gets a higher predicted probability than a randomly
chosen legitimate one 76.8% of the time. The two searches agree here
because every term that entered had χ² well above 3.84; a 1-df term with
χ² between 2 and 3.84 would enter by AIC but not by p-value.
Result. 11 predictors enter; the last is
customer_age (LR χ²(1) = 4.74 > 3.84). AUC =
.768.
Answer D. The AUC is about ranking fraudulent above legitimate claims across all cutoffs; it is not accuracy (option E) or sensitivity. .770 is the full model’s AUC.
step() with k = 2 is AIC and
k = qchisq(0.05, 1, lower.tail = FALSE) = 3.84 is p <
.05; bestglm() fits every subset of the candidates.anova(smaller, larger, test = "LRT"); to test each
slope, read summary().relevel()
before reading an odds ratio; odds are not probabilities.predict(type = "response"), then
confusionMatrix(..., positive = "1"); fraud must be the
positive class. The AUC measures ranking, not accuracy.This chunk stops the knit if any number in the review differs from the analysis.
cand <- c("claim_amount_k", "days_to_report", "police_report", "witness_present", "documents_submitted",
"prior_claims", "customer_age", "coverage_limit_k", "annual_premium_k", "credit_score")
stopifnot(sum(claims$fraud) == 395, length(coef(full)) - 1 == 19,
isTRUE(all.equal(AIC(final), 1867.79476755403, tolerance = 1e-8)),
isTRUE(all.equal(anova(final, full, test = "LRT")$Deviance[2], 6.2748757325694, tolerance = 1e-8)),
isTRUE(all.equal(anova(update(final, . ~ . - claim_type), final, test = "LRT")$Deviance[2], 29.0882057436838, tolerance = 1e-8)),
isTRUE(all.equal(as.numeric(auc(roc_final)), 0.767645449352055, tolerance = 1e-8)),
sum(summary(final)$coefficients[-1, 4] < .05) == 12,
isTRUE(all.equal(unname(exp(coef(final_home))["claim_typeTheft"]), 1.83597104544138, tolerance = 1e-8)),
isTRUE(all.equal(unname(car::vif(full)["coverage_limit_k", 1]), 17.4774456553201, tolerance = 1e-8)),
isTRUE(all.equal(min(unlist(lapply(1:10, function(k) lapply(combn(cand, k, simplify = FALSE),
function(s) AIC(glm(reformulate(s, "fraud"), family = binomial, data = claims)))))), 1922.00284823711, tolerance = 1e-8)),
isTRUE(all.equal(as.numeric(auc(roc(claims$fraud, predict(fwd_p, type = "response"), quiet = TRUE))), 0.767645449352055, tolerance = 1e-8)),
isTRUE(all.equal(anova(m_main, m_int, test = "LRT")$Deviance[2], 13.8646980756935, tolerance = 1e-8)),
isTRUE(all.equal(anova(m, test = "Chisq")$Deviance[4], 7.83061552843856, tolerance = 1e-8)),
isTRUE(all.equal(unname(confusionMatrix(pred, factor(claims$fraud), positive = "1")$byClass["Sensitivity"]), 0.463291139240506, tolerance = 1e-8)))
cat("All checked values match the slides.\n")
All checked values match the slides.
sessionInfo()
R version 4.3.3 (2024-02-29)
Platform: x86_64-pc-linux-gnu (64-bit)
Running under: Ubuntu 24.04.5 LTS
Matrix products: default
BLAS: /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.12.0
LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.12.0
locale:
[1] C
time zone: America/Chicago
tzcode source: system (glibc)
attached base packages:
[1] stats graphics grDevices utils datasets methods base
other attached packages:
[1] car_3.1-2 carData_3.0-5 pROC_1.18.5 caret_6.0-94 lattice_0.22-5
[6] ggplot2_3.4.4
loaded via a namespace (and not attached):
[1] gtable_0.3.4 xfun_0.41 bslib_0.6.1
[4] recipes_1.0.9 vctrs_0.6.5 tools_4.3.3
[7] generics_0.1.3 stats4_4.3.3 parallel_4.3.3
[10] proxy_0.4-27 tibble_3.2.1 fansi_1.0.5
[13] pkgconfig_2.0.3 ModelMetrics_1.2.2.2 Matrix_1.6-5
[16] data.table_1.14.10 lifecycle_1.0.4 compiler_4.3.3
[19] stringr_1.5.1 munsell_0.5.0 codetools_0.2-19
[22] htmltools_0.5.7 class_7.3-22 sass_0.4.8
[25] yaml_2.3.8 prodlim_2023.08.28 pillar_1.9.0
[28] jquerylib_0.1.4 MASS_7.3-60.0.1 cachem_1.0.8
[31] gower_1.0.1 iterators_1.0.14 abind_1.4-5
[34] rpart_4.1.23 foreach_1.5.2 nlme_3.1-164
[37] parallelly_1.37.1 lava_1.7.3 tidyselect_1.2.0
[40] digest_0.6.34 stringi_1.8.3 future_1.33.1
[43] dplyr_1.1.4 reshape2_1.4.4 purrr_1.0.2
[46] listenv_0.9.1 splines_4.3.3 fastmap_1.1.1
[49] grid_4.3.3 colorspace_2.1-0 cli_3.6.2
[52] magrittr_2.0.3 survival_3.5-8 utf8_1.2.4
[55] e1071_1.7-14 future.apply_1.11.1 withr_2.5.0
[58] scales_1.3.0 lubridate_1.9.3 timechange_0.3.0
[61] rmarkdown_2.25 globals_0.16.2 nnet_7.3-19
[64] timeDate_4032.109 evaluate_0.23 knitr_1.45
[67] hardhat_1.3.1 rlang_1.1.3 Rcpp_1.0.12
[70] glue_1.7.0 ipred_0.9-14 jsonlite_1.8.8
[73] R6_2.5.1 plyr_1.8.9