About this case. This is a hypothetical scenario. Netflix is used only because it is a familiar name. Every row of data is simulated for class; nothing here reflects Netflix’s actual data, design or results, and the course is not affiliated with Netflix.

1 How to use this document

This walkthrough follows the live-session slides (L8. Live Session) and the script L8_NetflixPicks.R line by line. Each section names the slides it explains:

  1. Set up — load the packages and the data, set reference levels, check the base rate.
  2. Check the full model — sample size, multicollinearity, linearity in the logit and one interaction.
  3. Select the predictors — forward, backward, stepwise and best subset selection, each run by AIC and by p-value; then a stepwise search that includes all two-way interactions.
  4. The final model — is it useful, does it meet the assumptions, what do the odds ratios say, and how well does it discriminate and fit?

Each step has three parts: what the code does, the code, and how to read the output. Numbers in the text are computed by R as the document knits, so the explanations always match the output.

No training/validation split (slide 4). In Lecture 7 we held out a test set. Here every method is fit to all 3,000 visits so the methods can be compared on the same data. The cost is that the final model’s AUC, its Hosmer–Lemeshow test and its p-values are optimistic: the same data chose the predictors and then judged them. Lecture 8’s cross-validation section shows the fix.

Before knitting, install the packages once (in the Console):

install.packages(c("tidyverse", "broom", "car", "lmtest", "pROC",
                   "ResourceSelection", "mgcv", "bestglm", "knitr"))

2 The business problem

Slides 2–3.

On every visit, the home screen opens with one featured movie at the top. The featured spot is the most visible place on the screen, so a title that goes unplayed wastes it. The question:

Which movie and moment features are associated with a member pressing Play on the featured movie — and which of the 11 candidate predictors belong in the model?

With 11 candidates there are \(2^{11} - 1 = 2{,}047\) possible models (with at least one predictor). We cannot test them all by hand, so we let selection methods choose, using two different rules for “earns its place”: AIC and a likelihood-ratio p-value below .05.

2.1 The data dictionary

Each row is one member visit (3,000 visits, 3,000 different members).

Variable Type Meaning
member_id ID Member identifier (not a predictor)
match_score continuous (55–99) How well the title fits the member’s viewing history
imdb_rating continuous (3.8–9.0) The movie’s IMDb-style rating
audience_score continuous (0–100 scale) The movie’s audience score
runtime_min continuous Running time in minutes
years_since_release continuous (0–45) Age of the movie in years (0 = released this year)
genre_match No / Yes The movie is in one of the member’s favorite genres
top10 No / Yes The movie carries a Top 10 badge
original No / Yes A streaming-service original
maturity G/PG, PG-13, R Maturity rating
weekend No / Yes The visit happened on a weekend
device TV, Mobile, Computer Device used for the visit
played 0 / 1 Outcome: 1 = pressed Play on the featured movie

3 Set up

3.1 Load the packages

Slide 6.

What the code does. library() loads a package into today’s R session. You install a package once per computer with install.packages(), but you load it every time you open R. Each comment says what we use the package for. Two more packages are used later: mgcv (called as mgcv::gam(), so it needs no library() line) and bestglm (loaded in the best-subset section).

library(tidyverse)           # read_csv(), mutate(), select(), count() and the |> pipe
library(broom)               # tidy() for odds ratios; augment() for residuals
library(car)                 # Anova(), vif() and influencePlot()
library(lmtest)              # lrtest(): likelihood-ratio test comparing two models
library(pROC)                # roc() and auc(): ROC curve and area under it
library(ResourceSelection)   # hoslem.test(): Hosmer-Lemeshow goodness-of-fit test
library(knitr)               # kable(): tables in this document

# small helpers for writing numbers in the text (not part of the class script)
f     <- function(x, d = 2) formatC(x, digits = d, format = "f", big.mark = ",")
pct   <- function(x, d = 1) paste0(formatC(100 * x, digits = d, format = "f"), "%")
p_txt <- function(p) if (p < .001) "p < .001" else
  paste0("p = ", sub("^0", "", formatC(p, digits = 3, format = "f")))

How to read it. Nothing prints when a package loads correctly. Messages such as “Attaching package” or “The following objects are masked” are normal. An error such as “there is no package called ‘car’” means the package must be installed first.

3.2 Read the data and set the factors

Slide 7.

What the code does.

  • read_csv() reads the file. It looks in your working directory; in RStudio use Session › Set Working Directory › To Source File Location.
  • mutate(... = factor(..., levels = ...)) tells R that a variable is categorical. The first level listed is the reference level: every odds ratio for that variable compares a level with the reference. We use No for each Yes/No factor, G/PG for maturity and TV for device.
  • select(-member_id) removes the ID column. This matters here because played ~ . (used below) means “every other column”, and an ID is not a predictor.
  • played stays numeric 0/1 rather than a factor. R models the probability that played = 1 (the event), and bestglm() needs a numeric 0/1 outcome. So, unlike clicked in Lecture 7, there is no event level to set.
movies <- read_csv("NetflixPicks.csv") |>
  mutate(genre_match = factor(genre_match, levels = c("No", "Yes")),
         top10       = factor(top10,       levels = c("No", "Yes")),
         original    = factor(original,    levels = c("No", "Yes")),
         weekend     = factor(weekend,     levels = c("No", "Yes")),
         maturity    = factor(maturity,    levels = c("G/PG", "PG-13", "R")),
         device      = factor(device,      levels = c("TV", "Mobile", "Computer"))) |>
  select(-member_id)        # drop the ID column: an ID is not a predictor

glimpse(movies)
#> Rows: 3,000
#> Columns: 12
#> $ match_score         <dbl> 91, 73, 91, 86, 79, 75, 89, 76, 78, 76, 80, 86, 92, 84, 75, 93, 84, 76~
#> $ imdb_rating         <dbl> 7.4, 6.7, 6.1, 6.9, 6.6, 6.9, 5.6, 7.2, 6.5, 6.9, 6.2, 6.0, 7.8, 6.1, ~
#> $ audience_score      <dbl> 79, 69, 68, 74, 69, 76, 56, 78, 64, 73, 68, 63, 82, 65, 69, 57, 65, 80~
#> $ runtime_min         <dbl> 90, 124, 100, 116, 133, 148, 131, 140, 109, 164, 121, 108, 94, 126, 14~
#> $ years_since_release <dbl> 5, 2, 9, 13, 13, 4, 6, 15, 10, 0, 24, 18, 2, 18, 4, 25, 5, 1, 6, 16, 5~
#> $ genre_match         <fct> Yes, No, Yes, No, Yes, No, No, No, Yes, No, Yes, Yes, Yes, Yes, No, Ye~
#> $ top10               <fct> No, No, No, No, No, No, No, No, No, No, Yes, No, Yes, Yes, No, No, No,~
#> $ original            <fct> Yes, No, Yes, No, No, No, No, Yes, No, Yes, Yes, Yes, No, Yes, No, Yes~
#> $ maturity            <fct> PG-13, PG-13, R, PG-13, R, G/PG, R, G/PG, R, PG-13, R, G/PG, R, R, R, ~
#> $ weekend             <fct> Yes, No, No, No, Yes, No, No, Yes, Yes, No, No, No, No, No, No, Yes, N~
#> $ device              <fct> TV, Mobile, Mobile, TV, TV, Mobile, TV, Computer, TV, TV, TV, Computer~
#> $ played              <dbl> 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0~
# Base rate: how many visits ended in Play (played = 1), and what share?
movies |> count(played) |> mutate(pct = n / sum(n))
#> # A tibble: 2 x 3
#>   played     n    pct
#>    <dbl> <int>  <dbl>
#> 1      0  2323 0.7743
#> 2      1   677 0.2257

How to read it. glimpse() confirms 3,000 rows, the six factors (<fct>) and the numeric outcome. Of the 3,000 visits, 677 (22.6%) ended in Play. That base rate is the benchmark: a model is useful only if it separates likely plays from unlikely ones better than guessing 22.6% for everyone.

4 Check the full model

Before any method chooses predictors, we check that the full model (all 11 candidates) is a sensible starting point. Selection methods do not fix sample-size, collinearity or linearity problems; they inherit them.

4.1 Assumption 1: adequate sample size

Not on the slides: script Section 2. This is also where full, used from slide 8 on, is created.

What the code does. glm(played ~ ., family = binomial) fits a logistic regression with every other column as a predictor:

\[\log\left(\frac{p}{1-p}\right) = \beta_0 + \beta_1 x_1 + \dots + \beta_k x_k,\]

where \(p\) is the probability of Play. R turns each factor into dummy variables, one for every level except the reference. The next lines count the events (plays, the rarer outcome) and the parameters (slopes, not counting the intercept), then divide.

full <- glm(played ~ ., data = movies, family = binomial)   # all 11 candidates

events <- sum(movies$played == 1)        # events = the rarer outcome (plays)
k      <- length(coef(full)) - 1         # parameters (slopes); - 1 drops the intercept
c(events = events, parameters = k, EPV = events / k)   # want EPV of at least 10
#>     events parameters        EPV 
#>  677.00000   13.00000   52.07692

How to read it. Events per parameter (EPV) = 677 / 13 = 52.1, well above the common rule of thumb of 10–20. Count parameters, not variables: there are 11 variables, but maturity and device each need 2 dummies, so 9 + 2 + 2 = 13. We use the full model because it is the largest model any method could choose. Pass.

4.2 Fit the full model: two views

Slides 8–9.

What the code does. summary() shows one row per coefficient (log-odds scale) with a Wald z test. Anova(type = "III", test.statistic = "LR") shows one likelihood-ratio (LR) test per predictor, holding the other predictors constant; a factor’s dummies are tested together.

summary(full)                                       # coefficients (log-odds scale)
#> 
#> Call:
#> glm(formula = played ~ ., family = binomial, data = movies)
#> 
#> Coefficients:
#>                      Estimate Std. Error z value Pr(>|z|)    
#> (Intercept)         -7.365487   0.699182 -10.534  < 2e-16 ***
#> match_score          0.055024   0.006172   8.915  < 2e-16 ***
#> imdb_rating          0.225477   0.189818   1.188 0.234890    
#> audience_score       0.016335   0.018030   0.906 0.364954    
#> runtime_min         -0.008929   0.002397  -3.726 0.000195 ***
#> years_since_release -0.028605   0.005844  -4.895 9.84e-07 ***
#> genre_matchYes       0.625000   0.099450   6.285 3.29e-10 ***
#> top10Yes             0.649624   0.101781   6.383 1.74e-10 ***
#> originalYes         -0.024439   0.093920  -0.260 0.794705    
#> maturityPG-13       -0.051062   0.116926  -0.437 0.662324    
#> maturityR           -0.103062   0.120446  -0.856 0.392179    
#> weekendYes           0.170900   0.096597   1.769 0.076858 .  
#> deviceMobile        -0.654714   0.111091  -5.894 3.78e-09 ***
#> deviceComputer      -0.397599   0.137102  -2.900 0.003731 ** 
#> ---
#> Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
#> 
#> (Dispersion parameter for binomial family taken to be 1)
#> 
#>     Null deviance: 3203.9  on 2999  degrees of freedom
#> Residual deviance: 2847.1  on 2986  degrees of freedom
#> AIC: 2875.1
#> 
#> Number of Fisher Scoring iterations: 4
Anova(full, type = "III", test.statistic = "LR")    # one LR test per predictor
#> Analysis of Deviance Table (Type III tests)
#> 
#> Response: played
#>                     LR Chisq Df Pr(>Chisq)    
#> match_score           83.669  1  < 2.2e-16 ***
#> imdb_rating            1.412  1  0.2347484    
#> audience_score         0.821  1  0.3648494    
#> runtime_min           14.042  1  0.0001787 ***
#> years_since_release   26.043  1  3.339e-07 ***
#> genre_match           39.554  1  3.192e-10 ***
#> top10                 39.843  1  2.752e-10 ***
#> original               0.068  1  0.7946694    
#> maturity               0.737  2  0.6919425    
#> weekend                3.113  1  0.0776848 .  
#> device                38.495  2  4.374e-09 ***
#> ---
#> Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

How to read it.

  • In summary(), each Estimate is the change in the log-odds of Play for a one-unit increase (continuous predictor) or the difference from the reference level (dummy), holding the other predictors constant.
  • In the Type III table, device and maturity get a single 2-df test, which is the right way to judge a factor as a whole.
  • 5 predictors have p > .05: imdb_rating, audience_score, original, maturity, weekend.
  • Something looks wrong. Both quality ratings are non-significant: imdb_rating (p = .235) and audience_score (p = .365). Does movie quality really not matter? The next check explains it.
  • weekend is close (χ² = 3.11, p = .078). Watch what each selection method does with it.

4.3 Assumption 2: multicollinearity

Slide 10.

What the code does. vif() computes a variance inflation factor for each predictor: how much the variance of its coefficient is inflated because it overlaps with the other predictors. With factors in the model, car reports a generalized VIF (GVIF); for factors, read the last column, GVIF^(1/(2*Df)). cor() shows how closely the two ratings move together.

The rubric. About 1: no overlap. Above 5: deserves a look. Above 10: a problem.

vif(full)                                           # read the last column (GVIF^(1/(2*Df)))
#>                          GVIF Df GVIF^(1/(2*Df))
#> match_score          1.147262  1        1.071103
#> imdb_rating         11.828747  1        3.439295
#> audience_score      11.819252  1        3.437914
#> runtime_min          1.004162  1        1.002079
#> years_since_release  1.008999  1        1.004489
#> genre_match          1.138772  1        1.067133
#> top10                1.011475  1        1.005721
#> original             1.002958  1        1.001478
#> maturity             1.005250  2        1.001310
#> weekend              1.006207  1        1.003099
#> device               1.009061  2        1.002258
cor(movies$imdb_rating, movies$audience_score)      # how closely the two ratings move
#> [1] 0.9572071

How to read it. imdb_rating (GVIF = 11.83) and audience_score (GVIF = 11.82) are both above 10; every other predictor is below 1.15. The ratings correlate at r = 0.957, consistent with both measuring the same quality signal.

  • Multicollinearity does not bias coefficients; it inflates their variance. The square root of the VIF is roughly how much a standard error is inflated: √11.8 ≈ 3.4.
  • With so much overlap, each rating adds little once the other is in the model, so both Type III tests are weak. That is not evidence that quality is unrelated to Play.
  • These are not final results: selection may remove either rating. But the overlap tells us what to expect — selection will usually keep one of the two — and how to read it: which rating survives is not a strong finding.

4.4 Assumption 3: linearity in the logit

Slide 11.

What the code does. Logistic regression assumes each continuous predictor has a straight-line relationship with the log-odds. The Box–Tidwell check adds \(x \cdot \ln(x)\) for each continuous predictor; if that extra term is significant (p < .05), the relationship is curved.

  • update(full, . ~ . + ...) keeps every term in full and adds the new ones.
  • I() tells R to compute the product as written rather than read * as an interaction.
  • \(\ln(0)\) is undefined and years_since_release has zeros (movies released this year), so it is shifted by 1 first. Adding 1 to every value keeps the order and makes the term computable.
  • grep("log", ...) keeps only the \(x \cdot \ln(x)\) rows of the coefficient table.

audience_score is not tested: it overlaps almost completely with imdb_rating.

bt <- update(full, . ~ . + I(match_score * log(match_score)) +
               I(imdb_rating * log(imdb_rating)) + I(runtime_min * log(runtime_min)) +
               I((years_since_release + 1) * log(years_since_release + 1)))
summary(bt)$coefficients[grep("log", names(coef(bt))), ]   # show only the x*log(x) rows
#>                                                                Estimate Std. Error     z value
#> I(match_score * log(match_score))                           -0.03020379 0.08850314 -0.34127359
#> I(imdb_rating * log(imdb_rating))                            0.01155661 0.62139443  0.01859787
#> I(runtime_min * log(runtime_min))                           -0.02329011 0.02349804 -0.99115099
#> I((years_since_release + 1) * log(years_since_release + 1)) -0.01486087 0.01344579 -1.10524367
#>                                                              Pr(>|z|)
#> I(match_score * log(match_score))                           0.7328976
#> I(imdb_rating * log(imdb_rating))                           0.9851619
#> I(runtime_min * log(runtime_min))                           0.3216119
#> I((years_since_release + 1) * log(years_since_release + 1)) 0.2690540

How to read it. R prints the matrix in more than one block because the row names are long; look for the Pr(>|z|) column. All four p-values are above .05 (.733, .985, .322, .269): no evidence of nonlinearity. Pass.

Why check before selection at all? Strictly, the assumption matters for the model you interpret, and we check the final model again in the final-model section. But selection methods only choose among the terms they are given: a predictor whose true effect is strongly curved, entered as a straight line, could look weak and be dropped. A quick check now protects against that.

4.5 One interaction worth testing

Slide 11.

What the code does. An interaction says the effect of one predictor depends on the level of another. We test one that has a business reason: does a Top 10 badge matter more when the movie is in a genre the member likes? lrtest() compares the model without the product term to the model with it.

lrtest(full, update(full, . ~ . + genre_match:top10))      # p < .05 = keep the interaction
#> Likelihood ratio test
#> 
#> Model 1: played ~ match_score + imdb_rating + audience_score + runtime_min + 
#>     years_since_release + genre_match + top10 + original + maturity + 
#>     weekend + device
#> Model 2: played ~ match_score + imdb_rating + audience_score + runtime_min + 
#>     years_since_release + genre_match + top10 + original + maturity + 
#>     weekend + device + genre_match:top10
#>   #Df  LogLik Df  Chisq Pr(>Chisq)
#> 1  14 -1423.6                     
#> 2  15 -1423.4  1 0.3297     0.5659

How to read it. Model 2 adds one parameter. LR χ²(1) = 0.33, p = .566: no evidence that the interaction is needed. Keep the main-effects model.

5 Select the predictors

5.1 Two ways to decide: AIC or p-value

Slide 13.

Every selection method asks the same question at each step: does this term earn its place? We use two rules.

AIC (Akaike information criterion). \(\text{AIC} = -2\log L + 2k\), where \(L\) is the likelihood and \(k\) the number of parameters. Lower is better. Adding a term with \(d\) degrees of freedom changes AIC by

\[\Delta\text{AIC} = -\,\chi^2_{LR} + 2d,\]

so AIC falls only if the term’s LR χ² exceeds \(2d\). For a 1-df term that means χ² > 2, which corresponds to about p < .157; for a 2-df term (like device), χ² > 4.

p-value. Keep a term if its LR test gives p < .05. For a 1-df term that needs χ² > 3.84; for 2 df, χ² > 5.99.

What to expect. AIC is the more lenient rule, so any 1-df term with χ² between 2 and 3.84 is kept by AIC and dropped by the p-value rule. In the full model, weekend has χ² = 3.11 — right in that gap. A difference in AIC under 2 is small: the two models are about equally supported (Burnham & Anderson, 2002).

5.2 Selection by AIC: forward, backward, stepwise

Slides 14–15 (forward), 18–19 (backward), 20 (stepwise).

What the code does. step() adds or removes one term at a time, making the move that lowers AIC most, and stops when no move lowers AIC.

  • null is the intercept-only model (no predictors).
  • Forward: start from null. scope = list(lower = null, upper = full) sets the smallest and largest models allowed.
  • Backward: start from full and remove one term at a time.
  • Stepwise (direction = "both"): start from null; at each step a term may enter or leave.
  • step() charges a penalty of k per parameter. The default is k = 2, which is AIC, so the code does not need to say it. You will see k written out in the next section, where it is changed to select by p-value.

step() prints a table at every step. The full forward trace is shown below so you can see how it works; for backward and stepwise we show only the summary of steps ($anova).

null <- glm(played ~ 1, data = movies, family = binomial)   # intercept only: no predictors

# Forward: start from null; scope sets the smallest (lower) and largest (upper) models
fwd_aic <- step(null, scope = list(lower = null, upper = full),
                direction = "forward")
#> Start:  AIC=3205.92
#> played ~ 1
#> 
#>                       Df Deviance    AIC
#> + match_score          1   3061.7 3065.7
#> + genre_match          1   3100.9 3104.9
#> + imdb_rating          1   3151.6 3155.6
#> + audience_score       1   3153.0 3157.0
#> + device               2   3163.6 3169.6
#> + top10                1   3168.1 3172.1
#> + years_since_release  1   3184.0 3188.0
#> + runtime_min          1   3190.7 3194.7
#> + weekend              1   3200.7 3204.7
#> <none>                     3203.9 3205.9
#> + original             1   3203.9 3207.9
#> + maturity             2   3203.3 3209.3
#> 
#> Step:  AIC=3065.66
#> played ~ match_score
#> 
#>                       Df Deviance    AIC
#> + imdb_rating          1   3010.6 3016.6
#> + audience_score       1   3012.0 3018.0
#> + top10                1   3017.8 3023.8
#> + device               2   3021.0 3029.0
#> + genre_match          1   3023.8 3029.8
#> + years_since_release  1   3037.8 3043.8
#> + runtime_min          1   3049.3 3055.3
#> + weekend              1   3058.8 3064.8
#> <none>                     3061.7 3065.7
#> + original             1   3061.6 3067.6
#> + maturity             2   3061.1 3069.1
#> 
#> Step:  AIC=3016.62
#> played ~ match_score + imdb_rating
#> 
#>                       Df Deviance    AIC
#> + top10                1   2966.4 2974.4
#> + genre_match          1   2971.3 2979.3
#> + device               2   2972.0 2982.0
#> + years_since_release  1   2987.5 2995.5
#> + runtime_min          1   2997.5 3005.5
#> + weekend              1   3007.3 3015.3
#> <none>                     3010.6 3016.6
#> + audience_score       1   3010.1 3018.1
#> + original             1   3010.5 3018.5
#> + maturity             2   3009.7 3019.7
#> 
#> Step:  AIC=2974.44
#> played ~ match_score + imdb_rating + top10
#> 
#>                       Df Deviance    AIC
#> + genre_match          1   2930.2 2940.2
#> + device               2   2929.3 2941.3
#> + years_since_release  1   2942.7 2952.7
#> + runtime_min          1   2952.9 2962.9
#> + weekend              1   2963.3 2973.3
#> <none>                     2966.4 2974.4
#> + audience_score       1   2965.8 2975.8
#> + original             1   2966.3 2976.3
#> + maturity             2   2965.4 2977.4
#> 
#> Step:  AIC=2940.2
#> played ~ match_score + imdb_rating + top10 + genre_match
#> 
#>                       Df Deviance    AIC
#> + device               2   2892.2 2906.2
#> + years_since_release  1   2904.7 2916.7
#> + runtime_min          1   2915.8 2927.8
#> + weekend              1   2927.2 2939.2
#> <none>                     2930.2 2940.2
#> + audience_score       1   2929.7 2941.7
#> + original             1   2930.0 2942.0
#> + maturity             2   2929.2 2943.2
#> 
#> Step:  AIC=2906.25
#> played ~ match_score + imdb_rating + top10 + genre_match + device
#> 
#>                       Df Deviance    AIC
#> + years_since_release  1   2866.3 2882.3
#> + runtime_min          1   2877.9 2893.9
#> + weekend              1   2889.4 2905.4
#> <none>                     2892.2 2906.2
#> + audience_score       1   2891.1 2907.1
#> + original             1   2892.1 2908.1
#> + maturity             2   2891.3 2909.3
#> 
#> Step:  AIC=2882.3
#> played ~ match_score + imdb_rating + top10 + genre_match + device + 
#>     years_since_release
#> 
#>                  Df Deviance    AIC
#> + runtime_min     1   2852.1 2870.1
#> + weekend         1   2862.9 2880.9
#> <none>                2866.3 2882.3
#> + audience_score  1   2865.2 2883.2
#> + original        1   2866.2 2884.2
#> + maturity        2   2865.4 2885.4
#> 
#> Step:  AIC=2870.13
#> played ~ match_score + imdb_rating + top10 + genre_match + device + 
#>     years_since_release + runtime_min
#> 
#>                  Df Deviance    AIC
#> + weekend         1   2848.8 2868.8
#> <none>                2852.1 2870.1
#> + audience_score  1   2851.1 2871.1
#> + original        1   2852.0 2872.0
#> + maturity        2   2851.4 2873.4
#> 
#> Step:  AIC=2868.75
#> played ~ match_score + imdb_rating + top10 + genre_match + device + 
#>     years_since_release + runtime_min + weekend
#> 
#>                  Df Deviance    AIC
#> <none>                2848.8 2868.8
#> + audience_score  1   2847.9 2869.9
#> + original        1   2848.7 2870.7
#> + maturity        2   2848.0 2872.0

How to read the trace. Each block is one step. <none> is the current model; each + term row is the AIC after adding that term. The rows are sorted, so the top row is the term that lowers AIC most, and that term is added. The search stops when <none> is at the top: no addition lowers AIC.

# Backward: start from the full model and remove one term at a time
bwd_aic <- step(full, direction = "backward")
# Stepwise: start from null; at each step a term may enter or leave
both_aic <- step(null, scope = list(lower = null, upper = full),
                 direction = "both")
fwd_aic$anova      # forward: one row per step
#>                    Step Df   Deviance Resid. Df Resid. Dev      AIC
#> 1                       NA         NA      2999   3203.922 3205.922
#> 2         + match_score -1 142.258115      2998   3061.664 3065.664
#> 3         + imdb_rating -1  51.045547      2997   3010.619 3016.619
#> 4               + top10 -1  44.176249      2996   2966.443 2974.443
#> 5         + genre_match -1  36.244361      2995   2930.198 2940.198
#> 6              + device -2  37.946479      2993   2892.252 2906.252
#> 7 + years_since_release -1  25.948996      2992   2866.303 2882.303
#> 8         + runtime_min -1  14.176252      2991   2852.126 2870.126
#> 9             + weekend -1   3.380619      2990   2848.746 2868.746
bwd_aic$anova      # backward
#>               Step Df   Deviance Resid. Df Resid. Dev      AIC
#> 1                  NA         NA      2986   2847.117 2875.117
#> 2       - maturity  2 0.73650488      2988   2847.853 2871.853
#> 3       - original  1 0.07074343      2989   2847.924 2869.924
#> 4 - audience_score  1 0.82176897      2990   2848.746 2868.746
both_aic$anova     # stepwise
#>                    Step Df   Deviance Resid. Df Resid. Dev      AIC
#> 1                       NA         NA      2999   3203.922 3205.922
#> 2         + match_score -1 142.258115      2998   3061.664 3065.664
#> 3         + imdb_rating -1  51.045547      2997   3010.619 3016.619
#> 4               + top10 -1  44.176249      2996   2966.443 2974.443
#> 5         + genre_match -1  36.244361      2995   2930.198 2940.198
#> 6              + device -2  37.946479      2993   2892.252 2906.252
#> 7 + years_since_release -1  25.948996      2992   2866.303 2882.303
#> 8         + runtime_min -1  14.176252      2991   2852.126 2870.126
#> 9             + weekend -1   3.380619      2990   2848.746 2868.746

How to read it.

  • Forward by AIC adds, in order: match_score, then imdb_rating, then top10, then genre_match, then device, then years_since_release, then runtime_min, then weekend. AIC falls from 3,205.9 (no predictors) to 2,868.7 with 8 predictors. weekend enters last and lowers AIC by only 1.38.
  • Once imdb_rating is in (step 2), audience_score never lowers AIC: the collinearity found in the multicollinearity check at work.
  • Backward by AIC removes maturity, original, audience_score and stops at the same 8 predictors. It removes maturity first because dropping a 2-df term saves 4 in penalty: AIC changes by χ² − 2d = 0.74 − 4.
  • Stepwise by AIC never removes a term and ends at the same 8 predictors.
  • Left out by every AIC method: audience_score, original, maturity.

5.3 Selection by p-value: forward, backward, stepwise

Slides 16–17 (forward), 18–19 (backward), 20 (stepwise).

What the code does. step() can also select by p-value. It charges a penalty of k for every parameter; the default, k = 2, is AIC, so a 1-df term enters when its LR χ² > 2. If we set k to 3.84 — the χ² value with 5% of the distribution above it (1 df) — a term enters only when its LR χ² > 3.84, which is exactly p < .05. qchisq(0.05, df = 1, lower.tail = FALSE) computes 3.84.

  • The three calls are the AIC calls from the previous section with k = k05 added.
  • In this output the column labeled “AIC” is deviance + 3.84 per parameter, not AIC. Read it only to see which term enters or leaves.
  • The match to p < .05 is exact for 1-df terms. A 2-df factor (device, maturity) must clear 2 × 3.84 = 7.68 rather than 5.99, a slightly stricter bar.
  • step() does not print p-values, so anova(fwd_p, test = "Chisq") lists each term’s LR χ² and p in the order the terms entered — the same χ² values as each forward step.
# step() can also select by p-value. With its default penalty (k = 2 per parameter), a
# 1-df term enters when its LR chi-square > 2. Setting k = 3.84 -- the chi-square value
# for p = .05 with 1 df -- means a term enters only if its LR chi-square > 3.84 (p < .05).
# For a 2-df factor (device, maturity) the bar is 7.68 rather than 5.99: slightly stricter.
# In this output the column labeled "AIC" is deviance + 3.84 per parameter, not AIC.
k05 <- qchisq(0.05, df = 1, lower.tail = FALSE)    # 3.84: chi-square for p = .05 (1 df)

fwd_p  <- step(null, scope = list(lower = null, upper = full),
               direction = "forward", k = k05)           # forward by p-value
#> Start:  AIC=3207.76
#> played ~ 1
#> 
#>                       Df Deviance    AIC
#> + match_score          1   3061.7 3069.3
#> + genre_match          1   3100.9 3108.6
#> + imdb_rating          1   3151.6 3159.3
#> + audience_score       1   3153.0 3160.7
#> + device               2   3163.6 3175.1
#> + top10                1   3168.1 3175.8
#> + years_since_release  1   3184.0 3191.7
#> + runtime_min          1   3190.7 3198.4
#> <none>                     3203.9 3207.8
#> + weekend              1   3200.7 3208.4
#> + original             1   3203.9 3211.6
#> + maturity             2   3203.3 3214.8
#> 
#> Step:  AIC=3069.35
#> played ~ match_score
#> 
#>                       Df Deviance    AIC
#> + imdb_rating          1   3010.6 3022.1
#> + audience_score       1   3012.0 3023.5
#> + top10                1   3017.8 3029.3
#> + genre_match          1   3023.8 3035.3
#> + device               2   3021.0 3036.4
#> + years_since_release  1   3037.8 3049.4
#> + runtime_min          1   3049.3 3060.9
#> <none>                     3061.7 3069.3
#> + weekend              1   3058.8 3070.3
#> + original             1   3061.6 3073.1
#> + maturity             2   3061.1 3076.4
#> 
#> Step:  AIC=3022.14
#> played ~ match_score + imdb_rating
#> 
#>                       Df Deviance    AIC
#> + top10                1   2966.4 2981.8
#> + genre_match          1   2971.3 2986.7
#> + device               2   2972.0 2991.2
#> + years_since_release  1   2987.5 3002.8
#> + runtime_min          1   2997.5 3012.8
#> <none>                     3010.6 3022.1
#> + weekend              1   3007.3 3022.7
#> + audience_score       1   3010.1 3025.5
#> + original             1   3010.5 3025.8
#> + maturity             2   3009.7 3028.9
#> 
#> Step:  AIC=2981.81
#> played ~ match_score + imdb_rating + top10
#> 
#>                       Df Deviance    AIC
#> + genre_match          1   2930.2 2949.4
#> + device               2   2929.3 2952.3
#> + years_since_release  1   2942.7 2961.9
#> + runtime_min          1   2952.9 2972.1
#> <none>                     2966.4 2981.8
#> + weekend              1   2963.3 2982.5
#> + audience_score       1   2965.8 2985.1
#> + original             1   2966.3 2985.5
#> + maturity             2   2965.4 2988.5
#> 
#> Step:  AIC=2949.41
#> played ~ match_score + imdb_rating + top10 + genre_match
#> 
#>                       Df Deviance    AIC
#> + device               2   2892.2 2919.1
#> + years_since_release  1   2904.7 2927.7
#> + runtime_min          1   2915.8 2938.8
#> <none>                     2930.2 2949.4
#> + weekend              1   2927.2 2950.2
#> + audience_score       1   2929.7 2952.8
#> + original             1   2930.0 2953.1
#> + maturity             2   2929.2 2956.1
#> 
#> Step:  AIC=2919.14
#> played ~ match_score + imdb_rating + top10 + genre_match + device
#> 
#>                       Df Deviance    AIC
#> + years_since_release  1   2866.3 2897.0
#> + runtime_min          1   2877.9 2908.6
#> <none>                     2892.2 2919.1
#> + weekend              1   2889.4 2920.2
#> + audience_score       1   2891.1 2921.9
#> + original             1   2892.1 2922.8
#> + maturity             2   2891.3 2925.8
#> 
#> Step:  AIC=2897.03
#> played ~ match_score + imdb_rating + top10 + genre_match + device + 
#>     years_since_release
#> 
#>                  Df Deviance    AIC
#> + runtime_min     1   2852.1 2886.7
#> <none>                2866.3 2897.0
#> + weekend         1   2862.9 2897.5
#> + audience_score  1   2865.2 2899.8
#> + original        1   2866.2 2900.8
#> + maturity        2   2865.4 2903.8
#> 
#> Step:  AIC=2886.7
#> played ~ match_score + imdb_rating + top10 + genre_match + device + 
#>     years_since_release + runtime_min
#> 
#>                  Df Deviance    AIC
#> <none>                2852.1 2886.7
#> + weekend         1   2848.8 2887.2
#> + audience_score  1   2851.1 2889.5
#> + original        1   2852.0 2890.4
#> + maturity        2   2851.4 2893.6
anova(fwd_p, test = "Chisq")                  # LR chi-sq and p for each term, in the order added
#> Analysis of Deviance Table
#> 
#> Model: binomial, link: logit
#> 
#> Response: played
#> 
#> Terms added sequentially (first to last)
#> 
#> 
#>                     Df Deviance Resid. Df Resid. Dev  Pr(>Chi)    
#> NULL                                 2999     3203.9              
#> match_score          1  142.258      2998     3061.7 < 2.2e-16 ***
#> imdb_rating          1   51.046      2997     3010.6 9.025e-13 ***
#> top10                1   44.176      2996     2966.4 3.001e-11 ***
#> genre_match          1   36.244      2995     2930.2 1.741e-09 ***
#> device               2   37.946      2993     2892.3 5.755e-09 ***
#> years_since_release  1   25.949      2992     2866.3 3.506e-07 ***
#> runtime_min          1   14.176      2991     2852.1 0.0001665 ***
#> ---
#> Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
bwd_p  <- step(full, direction = "backward", k = k05)    # backward by p-value
both_p <- step(null, scope = list(lower = null, upper = full),
               direction = "both", k = k05)              # stepwise by p-value
bwd_p$anova        # backward by p-value: one row per term removed
#>               Step Df   Deviance Resid. Df Resid. Dev      AIC
#> 1                  NA         NA      2986   2847.117 2900.897
#> 2       - maturity  2 0.73650488      2988   2847.853 2893.951
#> 3       - original  1 0.07074343      2989   2847.924 2890.180
#> 4 - audience_score  1 0.82176897      2990   2848.746 2887.160
#> 5        - weekend  1 3.38061948      2991   2852.126 2886.700
both_p$anova       # stepwise by p-value
#>                    Step Df  Deviance Resid. Df Resid. Dev      AIC
#> 1                       NA        NA      2999   3203.922 3207.764
#> 2         + match_score -1 142.25811      2998   3061.664 3069.347
#> 3         + imdb_rating -1  51.04555      2997   3010.619 3022.143
#> 4               + top10 -1  44.17625      2996   2966.443 2981.808
#> 5         + genre_match -1  36.24436      2995   2930.198 2949.405
#> 6              + device -2  37.94648      2993   2892.252 2919.142
#> 7 + years_since_release -1  25.94900      2992   2866.303 2897.034
#> 8         + runtime_min -1  14.17625      2991   2852.126 2886.700

How to read it.

  • Forward by p-value adds the same terms in the same order as forward by AIC, but stops after 7 predictors: weekend is the best remaining term, yet its LR χ² is 3.38 (p = .066), below 3.84. The table summarizes the sequential tests:
seq_tab |>
  as.data.frame() |>
  rownames_to_column("term") |>
  filter(term != "NULL") |>
  transmute(step = row_number(), `term added` = term, df = Df,
            `LR chi-sq` = round(Deviance, 2), p = signif(`Pr(>Chi)`, 3)) |>
  kable()
step term added df LR chi-sq p
1 match_score 1 142.26 0.00e+00
2 imdb_rating 1 51.05 0.00e+00
3 top10 1 44.18 0.00e+00
4 genre_match 1 36.24 0.00e+00
5 device 2 37.95 0.00e+00
6 years_since_release 1 25.95 4.00e-07
7 runtime_min 1 14.18 1.66e-04
  • Backward by p-value removes maturity, original, audience_score, weekend (LR χ² = 0.74, 0.07, 0.82, 3.38), each below its bar, and stops when every remaining term clears it. Like the AIC search, it removes maturity first: removing a term changes the criterion by χ² − k × df, and a 2-df term saves twice the penalty (0.74 − 7.68 beats 0.07 − 3.84).
  • Stepwise by p-value never removes a term and ends at the same 7 predictors.

So every AIC method picks the same 8-predictor model and every p-value method picks the same 7-predictor model. The only disagreement is weekend, whose χ² sits between 2 and 3.84.

Aside: MASS::stepAIC() gives the same results as step(); it is needed only for model types that step() does not support. Loading MASS after tidyverse hides dplyr::select(), so call it as MASS::stepAIC() if you use it.

5.4 Best subset selection

Slides 21–22.

What the code does. Forward, backward and stepwise follow one path of single moves; they can miss a better combination that is not on that path. Best subset fits every combination of the candidates and keeps the one with the lowest AIC.

5.4.1 Option 1: the bestglm package

bestglm() needs a data.frame (not a tibble) with the outcome as the last column. as.data.frame() converts the tibble; played is already the last column after select(-member_id), so it does not need to be renamed. IC = "AIC" ranks the models by AIC. best$BestModel is the lowest-AIC model; best$Subsets lists the best model of each size.

This chunk runs only if bestglm is installed (otherwise the code is shown but not run, and Option 2 below gives the same search).

library(bestglm)
# bestglm() needs a plain data.frame (not a tibble) with the outcome as the LAST column.
movies_df <- as.data.frame(movies)                          # played is already the last column
best <- bestglm(movies_df, family = binomial, IC = "AIC")   # fit all 2,047 models; rank by AIC
best$BestModel                                              # the lowest-AIC model
best$Subsets                                                # the best model of each size

5.4.2 Option 2: the same search without a package

What the code does.

  • combn(preds, s, simplify = FALSE) lists every set of s predictors; lapply() repeats that for s = 1 to 11; unlist(..., recursive = FALSE) joins them into one list of sets.
  • reformulate(v, "played") builds a formula such as played ~ match_score + top10 from a set of names; sapply() fits every model and keeps its AIC.
  • which.min(aics) finds the position of the smallest AIC.
  • The last three lines find the best model of each size: lengths(subsets) counts the predictors in each model, and for each size which.min() picks the lowest AIC among models of that size.
preds   <- setdiff(names(movies), "played")              # the 11 candidate predictors
subsets <- unlist(lapply(seq_along(preds), function(s) combn(preds, s, simplify = FALSE)),
                  recursive = FALSE)                      # every set of 1 to 11 predictors
aics    <- sapply(subsets, function(v)                    # fit each model; keep its AIC
             AIC(glm(reformulate(v, "played"), data = movies, family = binomial)))
subsets[[which.min(aics)]]                                # the best subset by AIC
#> [1] "match_score"         "imdb_rating"         "runtime_min"         "years_since_release"
#> [5] "genre_match"         "top10"               "weekend"             "device"
length(subsets)                                           # 2,047 models searched
#> [1] 2047
# The best model of each size (1 to 11 predictors): lowest AIC within each size
sizes <- lengths(subsets)                                 # number of predictors in each model
best_of_size <- sapply(1:11, function(s) which(sizes == s)[which.min(aics[sizes == s])])
data.frame(size = 1:11, AIC = round(aics[best_of_size], 1),
           predictors = sapply(subsets[best_of_size], paste, collapse = ", "))
#>    size    AIC
#> 1     1 3065.7
#> 2     2 3016.6
#> 3     3 2974.4
#> 4     4 2940.2
#> 5     5 2906.2
#> 6     6 2882.2
#> 7     7 2870.1
#> 8     8 2868.7
#> 9     9 2869.9
#> 10   10 2871.9
#> 11   11 2875.1
#>                                                                                                                             predictors
#> 1                                                                                                                          match_score
#> 2                                                                                                             match_score, imdb_rating
#> 3                                                                                                      match_score, imdb_rating, top10
#> 4                                                                                         match_score, imdb_rating, genre_match, top10
#> 5                                                                              match_score, audience_score, genre_match, top10, device
#> 6                                                         match_score, audience_score, years_since_release, genre_match, top10, device
#> 7                                               match_score, imdb_rating, runtime_min, years_since_release, genre_match, top10, device
#> 8                                      match_score, imdb_rating, runtime_min, years_since_release, genre_match, top10, weekend, device
#> 9                      match_score, imdb_rating, audience_score, runtime_min, years_since_release, genre_match, top10, weekend, device
#> 10           match_score, imdb_rating, audience_score, runtime_min, years_since_release, genre_match, top10, original, weekend, device
#> 11 match_score, imdb_rating, audience_score, runtime_min, years_since_release, genre_match, top10, original, maturity, weekend, device

How to read it.

  • 2,047 models were fit (\(2^{11} - 1\)). The lowest AIC is 2,868.7, with the same 8 predictors as every AIC method: best subset confirms the stepwise result.
  • The best model of each size shows the cost–benefit of each extra predictor. AIC falls quickly up to about 7 predictors, reaches its minimum at size 8, and rises again as useless predictors are added.
  • A swap that forward selection cannot see. At sizes 5 and 6 the best model uses audience_score instead of imdb_rating. With r = 0.957, either rating can stand in for the other. Forward selection’s 5-predictor model (with imdb_rating) has AIC 2,906.25; the best 5-predictor model has AIC 2,906.19. Forward selection cannot swap a term out, so it never sees that model. Here the difference is trivial and the paths meet again at size 7.
  • What best subset guarantees: no subset of the candidates has a lower AIC. What it does not guarantee: better predictions for new members (it was judged on the same data), significant p-values for every term, or that assumptions hold.

5.5 Compare the methods and choose

Slides 23–24.

Method By AIC By p-value (α = .05)
Forward 8 predictors (AIC 2,868.7) 7 predictors (AIC 2,870.1)
Backward 8 predictors (AIC 2,868.7) 7 predictors (AIC 2,870.1)
Stepwise 8 predictors (AIC 2,868.7) 7 predictors (AIC 2,870.1)
Best subset 8 predictors (AIC 2,868.7) — (not a p-value method)

What the code does. The AIC methods kept weekend; the p-value methods did not. AIC() lists the AIC of several models at once; lrtest(fwd_p, fwd_aic) tests whether adding weekend to the 7-predictor model improves it.

AIC(fwd_aic, fwd_p, full)                      # lower is better; a gap under 2 is small
#>         df      AIC
#> fwd_aic 10 2868.746
#> fwd_p    9 2870.126
#> full    14 2875.117
lrtest(fwd_p, fwd_aic)                         # LR test for adding weekend to fwd_p
#> Likelihood ratio test
#> 
#> Model 1: played ~ match_score + imdb_rating + top10 + genre_match + device + 
#>     years_since_release + runtime_min
#> Model 2: played ~ match_score + imdb_rating + top10 + genre_match + device + 
#>     years_since_release + runtime_min + weekend
#>   #Df  LogLik Df  Chisq Pr(>Chisq)  
#> 1   9 -1426.1                       
#> 2  10 -1424.4  1 3.3806    0.06597 .
#> ---
#> Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

How to read it.

  • By AIC: weekend lowers AIC from 2,870.1 to 2,868.7, a gain of only 1.38. Under 2: the two models are about equally supported.
  • By p-value: LR χ²(1) = 3.38, p = .066. No evidence at α = .05 that weekend is needed.
  • Decision: use the simpler 7-predictor model. Neither criterion gives strong support for weekend. (If the business question were about weekend scheduling, or if prediction rather than explanation were the goal, keeping it would be defensible; report the choice either way.)
  • The full model (AIC 2,875.1) is worse than both: its extra predictors add penalty without adding fit.

5.6 Do we need interaction terms?

Slide 25.

So far every model has used main effects only: each predictor’s effect is the same whatever the other predictors’ values. An interaction lets the effect of one predictor depend on another. Two questions to discuss before running any code:

  1. Which pairs of predictors have a business reason to interact? Examples: genre_match × top10 (a Top 10 badge may matter more for a genre the member likes — already tested on slide 11 and not needed), device × runtime_min (long movies may be less appealing on a phone) and weekend × runtime_min (more time for long movies on weekends).
  2. What could go wrong if we test every pair? With 11 predictors there are 55 two-way interactions. Testing them all at α = .05 makes chance findings likely, and the model gains many more parameters. The next section runs that search so you can see the result.

5.7 Stepwise with all two-way interactions

Slides 26–27.

What the code does. So far the search considered main effects only. Here it may consider every pair of predictors.

  • played ~ .^2 means every predictor plus every two-way interaction. (a:b is the interaction term alone; a*b is a + b + a:b.) full2 is only the upper limit of the search — the largest model allowed — not a model to interpret.
  • step() and add1() respect hierarchy: an interaction is offered only when both of its main effects are already in the model, and a main effect cannot leave while its interaction is in.
  • trace = 0 hides the many step tables; both_int$anova and both_int_p$anova list the steps each search took. The p-value search is the same step() call with k = k05.
# .^2 means every predictor plus every pair of predictors (all two-way interactions).
full2 <- glm(played ~ .^2, data = movies, family = binomial)   # the largest model allowed
length(attr(terms(full2), "term.labels"))     # 66 terms: 11 main effects + 55 interactions
#> [1] 66
length(coef(full2)) - 1                       # 89 parameters: EPV = 677 / 89 = 7.6 (< 10)
#> [1] 89
# Stepwise from null, allowing any term up to full2. step() and add1() respect hierarchy:
# an interaction can enter only after both of its main effects are in the model.
both_int   <- step(null, scope = list(lower = null, upper = full2),
                   direction = "both", trace = 0)      # by AIC; trace = 0 hides the tables
both_int$anova                                # the steps the AIC search took
#>                                 Step Df   Deviance Resid. Df Resid. Dev      AIC
#> 1                                    NA         NA      2999   3203.922 3205.922
#> 2                      + match_score -1 142.258115      2998   3061.664 3065.664
#> 3                      + imdb_rating -1  51.045547      2997   3010.619 3016.619
#> 4                            + top10 -1  44.176249      2996   2966.443 2974.443
#> 5                      + genre_match -1  36.244361      2995   2930.198 2940.198
#> 6                           + device -2  37.946479      2993   2892.252 2906.252
#> 7              + years_since_release -1  25.948996      2992   2866.303 2882.303
#> 8                      + runtime_min -1  14.176252      2991   2852.126 2870.126
#> 9                + runtime_min:top10 -1   6.890258      2990   2845.236 2865.236
#> 10                         + weekend -1   3.148495      2989   2842.088 2864.088
#> 11             + match_score:weekend -1   3.548085      2988   2838.540 2862.540
#> 12 + imdb_rating:years_since_release -1   2.843087      2987   2835.697 2861.697
both_int_p <- step(null, scope = list(lower = null, upper = full2),
                   direction = "both", k = k05, trace = 0)   # by p-value (k = 3.84)
both_int_p$anova                              # the steps the p-value search took
#>                    Step Df   Deviance Resid. Df Resid. Dev      AIC
#> 1                       NA         NA      2999   3203.922 3207.764
#> 2         + match_score -1 142.258115      2998   3061.664 3069.347
#> 3         + imdb_rating -1  51.045547      2997   3010.619 3022.143
#> 4               + top10 -1  44.176249      2996   2966.443 2981.808
#> 5         + genre_match -1  36.244361      2995   2930.198 2949.405
#> 6              + device -2  37.946479      2993   2892.252 2919.142
#> 7 + years_since_release -1  25.948996      2992   2866.303 2897.034
#> 8         + runtime_min -1  14.176252      2991   2852.126 2886.700
#> 9   + runtime_min:top10 -1   6.890258      2990   2845.236 2883.651
AIC(fwd_p, both_int, both_int_p)              # fwd_p = the 7-predictor main-effects model
#>            df      AIC
#> fwd_p       9 2870.126
#> both_int   13 2861.697
#> both_int_p 10 2865.236

How to read it.

  • full2 has 66 terms and 89 parameters: EPV = 677 / 89 = 7.6, below 10. That is another reason never to interpret full2 itself.
  • By AIC, the search adds the same 7 main effects, then weekend and 3 interactions (top10:runtime_min, match_score:weekend, imdb_rating:years_since_release); final AIC 2,861.7.
  • By p-value, it adds the same 7 main effects and 1 interaction (top10:runtime_min); AIC 2,865.2.
  • Real or chance? These data were simulated with no interactions at all (see Make_Netflix_Picks.R), so every interaction selected here is a chance finding. Search 55 interactions at α = .05 and roughly 55 × .05 ≈ 3 will pass by chance even if none is real (the tests are not independent, so this is only a rough guide).
  • Why does the AIC model look better (2,861.7 vs. 2,870.1)? AIC rewards fit to this sample. With many candidates, the best-looking model is partly fitting noise — the optimism described at the top of this document.

When to consider an interaction: when theory, business logic or earlier evidence predicts that one predictor’s effect depends on another’s level (as with genre_match × top10). When to add one: when an LR test supports it, it makes sense, and both main effects stay in the model. An interaction picked by an all-pairs search should be confirmed on new data before anyone acts on it. Our final model stays the 7-predictor main-effects model.

6 The final model

Selection changed the model, so we check it again before interpreting it. Each check ends in pass, fix, or limitation.

6.1 Is the final model useful?

Slides 29–30.

What the code does. lrtest(final) compares the final model with the intercept-only model (the global test). Anova(type = "III") tests each predictor as a whole, holding the others constant.

final <- fwd_p                                 # the 7-predictor model chosen by p-value

lrtest(final)                                       # final model vs. intercept-only model
#> Likelihood ratio test
#> 
#> Model 1: played ~ match_score + imdb_rating + top10 + genre_match + device + 
#>     years_since_release + runtime_min
#> Model 2: played ~ 1
#>   #Df  LogLik Df Chisq Pr(>Chisq)    
#> 1   9 -1426.1                        
#> 2   1 -1602.0 -8 351.8  < 2.2e-16 ***
#> ---
#> Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
Anova(final, type = "III", test.statistic = "LR")   # each predictor, holding the others constant
#> Analysis of Deviance Table (Type III tests)
#> 
#> Response: played
#>                     LR Chisq Df Pr(>Chisq)    
#> match_score           83.681  1  < 2.2e-16 ***
#> imdb_rating           50.520  1  1.180e-12 ***
#> top10                 40.006  1  2.531e-10 ***
#> genre_match           39.868  1  2.718e-10 ***
#> device                38.258  2  4.926e-09 ***
#> years_since_release   25.742  1  3.902e-07 ***
#> runtime_min           14.176  1  0.0001665 ***
#> ---
#> Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

How to read it.

  • Global test: χ²(8) = 351.8, p < .001. (R prints the Df as negative because Model 2, the intercept-only model, is the smaller one.) The model is far better than no predictors.
  • Every predictor has p < .001. Compare imdb_rating: χ² = 1.41 in the full model, 50.52 here, once audience_score is gone. That is the collinearity story in one line.
  • Reminder: after selection on the same data, these p-values are optimistic.

6.2 Sample size and multicollinearity

Slide 31.

k_final <- length(coef(final)) - 1             # parameters in the final model
c(events = events, parameters = k_final, EPV = events / k_final)   # want at least 10
#>     events parameters        EPV 
#>    677.000      8.000     84.625
vif(final)                                     # read the last column (GVIF^(1/(2*Df)))
#>                         GVIF Df GVIF^(1/(2*Df))
#> match_score         1.145044  1        1.070067
#> imdb_rating         1.004829  1        1.002412
#> top10               1.010500  1        1.005236
#> genre_match         1.137403  1        1.066491
#> device              1.004315  2        1.001077
#> years_since_release 1.007968  1        1.003976
#> runtime_min         1.002759  1        1.001378

How to read it.

  • EPV = 677 / 8 = 84.6: fewer parameters than the full model, so more events per parameter. Pass.
  • VIF: the largest is 1.15 (match_score). imdb_rating dropped from 11.83 to 1.00 once audience_score left. Pass.

6.3 Linearity in the logit: look at smooth curves

Slides 32–33.

What the code does. As in Lecture 7, we look before we test. A generalized additive model (GAM) replaces each continuous predictor with a smooth curve s() that can bend freely; the factors stay as they are. If the fitted curve is a straight line, linearity holds. A smooth curve needs no logarithm, so years_since_release (which has zeros) can be checked directly.

  • plot(..., pages = 1) puts all panels on one page; shade = TRUE draws the 95% band; scale = 0 gives each panel its own y-axis.
  • summary(gam_final)$s.table reports the effective degrees of freedom (edf): edf = 1 is a straight line; larger values mean more bend. (Its p-value tests whether the predictor matters at all, not whether it is curved.)
gam_final <- mgcv::gam(played ~ s(match_score) + s(imdb_rating) + s(runtime_min) +
                         s(years_since_release) + top10 + genre_match + device,
                       data = movies, family = binomial)   # same predictors as final
plot(gam_final, pages = 1, shade = TRUE, scale = 0)   # one panel each: log-odds + 95% band

summary(gam_final)$s.table                            # edf near 1 = straight line
#>                             edf   Ref.df   Chi.sq      p-value
#> s(match_score)         1.000464 1.000927 79.54208 0.000000e+00
#> s(imdb_rating)         1.000060 1.000119 49.06585 0.000000e+00
#> s(runtime_min)         1.107493 1.207505 14.67032 3.938694e-04
#> s(years_since_release) 1.509622 1.864914 25.57310 1.746745e-05

How to read it.

  • match_score (edf 1.00), imdb_rating (1.00) and runtime_min (1.11) are straight lines.
  • years_since_release (edf 1.51) bends slightly past 30 years. Only 109 of 3,000 movies (3.6%) are that old, so the band is wide there, and a straight line still fits inside the band across the whole range. Keep it linear. Pass.
  • If a curve were clearly bent where the band is narrow, the fix would be a log or a centered quadratic term, as in Lecture 7.

6.4 Residuals and influence

Slide 34.

What the code does. Same code as Lecture 7.

  • augment(final, type.residuals = "deviance") returns one row per visit with its deviance residual (.resid); cooks.distance() adds Cook’s distance, a measure of how much the coefficients change when that visit is removed.
  • 4/n flags candidates worth a look; only Cook’s distances near 1 threaten the estimates.
  • dfbetas() measures how many standard errors each coefficient moves when a visit is removed; values near 1 matter.
  • influencePlot() plots and lists the most unusual visits by row number.
diag <- augment(final, type.residuals = "deviance") |>    # one row per visit
  mutate(cooks = cooks.distance(final))                   # add Cook's distance
mean(abs(diag$.resid) > 2)                     # share of |deviance residual| > 2
#> [1] 0.03
c(max_cooks = max(diag$cooks), cutoff_4n = 4 / nrow(movies))   # 4/n flags candidates
#>   max_cooks   cutoff_4n 
#> 0.004930544 0.001333333
sum(diag$cooks > 4 / nrow(movies))             # how many visits exceed 4/n
#> [1] 201
max(abs(dfbetas(final)))                       # compare with 1
#> [1] 0.1411608
influencePlot(final)                           # the most unusual visits, labeled by row

#>         StudRes         Hat        CookD
#> 69    2.5515587 0.001429816 0.0038994711
#> 1042  1.3310511 0.014710379 0.0023568368
#> 1117  2.5313210 0.001914767 0.0049305438
#> 1706  2.3840589 0.002625775 0.0046325094
#> 2605 -0.9106152 0.012900202 0.0007484135

How to read it.

  • 3.0% of visits have |deviance residual| > 2. With a 0/1 outcome, deviance residuals are not normal, so there is no fixed share to expect; look for patterns rather than a count.
  • The largest Cook’s distance is 0.0049. 201 visits exceed 4/n (0.00133), which sounds like many, but with n = 3,000 the 4/n cutoff is tiny; the largest Cook’s distance is about 203 times smaller than 1.
  • The largest |DFBETAS| is 0.14, far below 1. No single visit drives the results. Pass.

6.5 Summary of the checks

Slide 35.

Check Result Verdict
Useful (global LR test) χ²(8) = 351.8, p < .001 Pass
Sample size (EPV) 677 ÷ 8 = 84.6 Pass (≥ 10)
Multicollinearity Largest VIF = 1.15 Pass (< 5)
Linearity in the logit edf 1.00 to 1.51 Pass (slight bend in years, thin data)
Residuals and influence Max Cook’s D = 0.005; max |DFBETAS| = 0.14 Pass
Independence One visit per member Pass (by design)
Calibration (Hosmer–Lemeshow) See “How good is the final model?” below Pass

The one limitation is not an assumption: the predictors were chosen and judged on the same data.

6.6 Odds ratios

Slides 36–37.

What the code does.

  • tidy(final, exponentiate = TRUE, conf.int = TRUE) gives every odds ratio (estimate) with its 95% confidence interval (conf.low, conf.high), as in Lecture 7.
  • One unit is too small to discuss for some predictors (one point of match score, one minute of runtime), so we rescale: multiply the log-odds coefficient and its CI by a sensible unit, then exponentiate. confint() gives profile-likelihood CIs on the log-odds scale (“Waiting for profiling to be done…” is normal); cbind(OR = b, ci) puts the estimate and both limits in one row, so a single exp(10 * ...) rescales all three.
tidy(final, exponentiate = TRUE, conf.int = TRUE)   # OR and 95% CI for every term
#> # A tibble: 9 x 7
#>   term                 estimate std.error statistic   p.value  conf.low conf.high
#>   <chr>                   <dbl>     <dbl>     <dbl>     <dbl>     <dbl>     <dbl>
#> 1 (Intercept)         0.0006844  0.6912     -10.54  5.493e-26 0.0001746  0.002625
#> 2 match_score         1.057      0.006165     8.916 4.817e-19 1.044      1.069   
#> 3 imdb_rating         1.473      0.05526      7.003 2.507e-12 1.322      1.642   
#> 4 top10Yes            1.916      0.1017       6.396 1.594e-10 1.569      2.338   
#> 5 genre_matchYes      1.871      0.09929      6.309 2.804e-10 1.540      2.274   
#> 6 deviceMobile        0.5218     0.1108      -5.871 4.341e- 9 0.4190     0.6471  
#> 7 deviceComputer      0.6714     0.1369      -2.910 3.618e- 3 0.5113     0.8750  
#> 8 years_since_release 0.9720     0.005831    -4.868 1.125e- 6 0.9608     0.9830  
#> 9 runtime_min         0.9911     0.002393    -3.743 1.818e- 4 0.9864     0.9957
# One unit is tiny for some predictors, so rescale: multiply the log-odds and its CI
# by a sensible unit, then exponentiate with exp().
b  <- coef(final); ci <- confint(final)        # log-odds and 95% CIs (log-odds scale)
exp(10 * cbind(OR = b, ci)["match_score", ])           # per 10 points of match score
#>       OR    2.5 %   97.5 % 
#> 1.732751 1.536765 1.957062
exp(10 * cbind(OR = b, ci)["years_since_release", ])   # per 10 years older
#>        OR     2.5 %    97.5 % 
#> 0.7528690 0.6701541 0.8423954
exp(30 * cbind(OR = b, ci)["runtime_min", ])           # per 30 more minutes
#>        OR     2.5 %    97.5 % 
#> 0.7643920 0.6636918 0.8794477

How to read it. An odds ratio above 1 means higher odds of Play; below 1, lower odds. Each is holding the other predictors constant, and each describes an association in observational (here, simulated) data, not a cause.

Predictor Change Odds ratio 95% CI
match_score +10 points 1.73 1.54 – 1.96
imdb_rating +1 point 1.47 1.32 – 1.64
top10 Yes vs. No 1.92 1.57 – 2.34
genre_match Yes vs. No 1.87 1.54 – 2.27
device Mobile vs. TV 0.52 0.42 – 0.65
device Computer vs. TV 0.67 0.51 – 0.87
years_since_release +10 years 0.75 0.67 – 0.84
runtime_min +30 minutes 0.76 0.66 – 0.88
  • Match score: a 10-point higher match score is associated with 1.73 times the odds of pressing Play (95% CI 1.54 to 1.96).
  • Rating: each additional rating point, 1.47 times the odds (95% CI 1.32 to 1.64).
  • Top 10 badge: 1.92 times the odds (95% CI 1.57 to 2.34); genre match: 1.87 times (95% CI 1.54 to 2.27).
  • Device: compared with TV, Mobile visits have 0.52 times the odds — about 48% lower — and Computer visits 0.67 times.
  • Older and longer movies are less likely to be played: 0.75 times the odds per 10 years older and 0.76 times per 30 extra minutes.
  • Every CI excludes 1, consistent with the Type III tests.

6.7 How good is the final model?

Slide 38.

What the code does.

  • fitted(final) gives each visit’s predicted probability of Play.
  • roc() builds the ROC curve: for every possible cutoff it records sensitivity (share of plays correctly flagged) and specificity (share of non-plays correctly cleared). levels = c(0, 1) says 0 = no play and 1 = play; direction = "<" says higher scores mean play.
  • auc() is the area under the curve: the probability that a randomly chosen play gets a higher predicted probability than a randomly chosen non-play. 0.5 = coin flip; 1 = perfect ranking.
  • hoslem.test() is the Hosmer–Lemeshow test of calibration: it sorts visits into 10 groups by predicted probability and compares observed with expected plays in each. A large p-value means no evidence of misfit.
roc_final <- roc(movies$played, fitted(final), levels = c(0, 1), direction = "<")
auc(roc_final)                                           # area under the ROC curve
#> Area under the curve: 0.7254
plot(roc_final, legacy.axes = TRUE, print.auc = TRUE)    # x-axis = 1 - specificity

hoslem.test(movies$played, fitted(final), g = 10)        # 10 groups; p > .05 = no misfit
#> 
#>  Hosmer and Lemeshow goodness of fit (GOF) test
#> 
#> data:  movies$played, fitted(final)
#> X-squared = 6.3782, df = 8, p-value = 0.6049

How to read it.

  • AUC = 0.725: a randomly chosen play receives a higher predicted probability than a randomly chosen non-play 72.5% of the time. A common guide calls .7–.8 acceptable and .8–.9 excellent discrimination (Hosmer et al., 2013), so this model is useful for ranking visits, not for confident predictions about a single visit.
  • Hosmer–Lemeshow: χ²(8) = 6.38, p = .605. No evidence of misfit: predicted and observed play rates agree across the 10 groups. Pass.
  • Both are in-sample, so both are optimistic. The honest next step is to estimate them on data the model has not seen (cross-validation or a holdout set).

6.8 Choose a cutpoint and compare it with others

Slides 39–41.

What the code does. A cutpoint (cutoff) turns each predicted probability into a prediction: play if \(\hat p \ge\) cutpoint, no play otherwise. Every cutpoint trades sensitivity (the share of actual plays the model flags) against specificity (the share of non-plays it clears).

  • coords(roc_final, "best", best.method = "youden") finds the cutpoint with the largest Youden’s J = sensitivity + specificity − 1, the point on the ROC curve farthest above the diagonal. We name the result youden so it does not overwrite the bestglm() result best.
  • ifelse(... >= youden$threshold, 1, 0) makes the predictions; table() cross-tabulates them against the actual outcome (the confusion matrix).
  • coords(..., x = cutoffs, input = "threshold") reports the same statistics at any list of cutpoints. Change or add cutpoints in the cutoffs line.
  • mean(movies$played == 0) is a benchmark: the accuracy of predicting “no play” for everyone.
# A cutpoint turns each predicted probability into a prediction: play if p >= cutpoint.
# Youden's J picks the cutpoint with the largest sensitivity + specificity - 1.
youden <- coords(roc_final, "best", best.method = "youden",
                 ret = c("threshold", "sensitivity", "specificity", "accuracy"))
youden                                                   # the Youden cutpoint and its results
#>           threshold sensitivity specificity  accuracy
#> threshold 0.2241671   0.6676514   0.6685321 0.6683333
pred <- ifelse(fitted(final) >= youden$threshold, 1, 0)  # 1 = predicted play
table(Predicted = pred, Actual = movies$played)          # confusion matrix at that cutpoint
#>          Actual
#> Predicted    0    1
#>         0 1553  225
#>         1  770  452
# Compare the Youden cutpoint with other cutpoints (change or add cutpoints here)
cutoffs <- c(0.2, youden$threshold, 0.3, 0.4, 0.5)
coords(roc_final, x = cutoffs, input = "threshold",
       ret = c("threshold", "sensitivity", "specificity", "accuracy"))
#>   threshold sensitivity specificity  accuracy
#> 1 0.2000000   0.7237814   0.6035299 0.6306667
#> 2 0.2241671   0.6676514   0.6685321 0.6683333
#> 3 0.3000000   0.4859675   0.8084374 0.7356667
#> 4 0.4000000   0.2850812   0.9130435 0.7713333
#> 5 0.5000000   0.1669129   0.9655618 0.7853333
mean(movies$played == 0)                       # accuracy of predicting "no play" for everyone
#> [1] 0.7743333
Sensitivity, specificity, accuracy and Youden’s J at each cutpoint (in-sample)
cutpoint sensitivity specificity accuracy J
.200 0.724 0.604 0.631 0.327
.224 (Youden) 0.668 0.669 0.668 0.336
.300 0.486 0.808 0.736 0.294
.400 0.285 0.913 0.771 0.198
.500 0.167 0.966 0.785 0.132
No model: all “no play” 0.000 1.000 0.774 0.000

How to read it.

  • The Youden cutpoint is .224, almost exactly the base rate of plays (22.6%): the model flags a visit when its predicted probability is above average. At that cutpoint sensitivity = .668, specificity = .669 and overall accuracy = .668 (J = .336).
  • The confusion matrix shows where those rates come from: the model catches 452 of the 677 plays (452 / 677 = .668) and clears 1,553 of the 2,323 non-plays (= .669); 225 plays are missed and 770 non-plays are flagged.
  • The trade-off: as the cutpoint rises from .2 to .5, sensitivity falls from .724 to .167 and specificity rises from .604 to .966.
  • The accuracy trap: accuracy is highest at .5 (.785), but that cutpoint catches only 17% of plays — barely better than predicting “no play” for every visit, which is .774 accurate and catches none. With an uncommon outcome, report sensitivity and specificity, not accuracy alone.
  • Which cutpoint to use depends on the business goal. Youden’s J weighs the two errors equally; if missing a likely play is the costlier error, choose a lower cutpoint, and if wrongly flagging a title is costlier, a higher one. With known costs, choose by expected cost, as in Lecture 7.
  • These rates are in-sample: the cutpoint was chosen and judged on the same data. With a holdout set, choose the cutpoint on the training data and report the rates on the test data.

7 Recommendations and limitations

What the model says (associations, in this simulated scenario):

  • Personal fit matters most: a higher match score and a genre match are associated with much higher odds of Play.
  • Signals of quality and popularity help: higher-rated movies and Top 10 titles are more likely to be played.
  • Older and longer movies are less likely to be played from the featured spot.
  • Device: visits on Mobile (and, to a lesser degree, Computer) have lower odds than TV visits.

What the team could do:

  1. Favor high-match, highly rated, Top 10 titles for the featured spot.
  2. Look more closely at Mobile visits, which are less likely to end in Play, and test what works there before changing the featured-title rules for that device.
  3. Validate the model on new visits (holdout or cross-validation) and test featured-title rules with an A/B test before treating any association as causal.

Limitations:

  • Simulated, observational data: associations, not causal effects.
  • The predictors were selected and evaluated on the same data, so AUC, Hosmer–Lemeshow and the p-values are optimistic.
  • Results depend on the candidate list: selection never adds curves or interactions we did not offer, and an all-pairs interaction search finds chance interactions.
  • The two ratings overlap so strongly that the choice of imdb_rating over audience_score is not a substantive finding.

8 Key takeaways

Slide 42.

  1. Check assumptions before selection and again on the final model. Selection inherits sample-size, collinearity and linearity problems, and it changes the model you interpret.
  2. AIC keeps a 1-df term when χ² > 2; p < .05 needs χ² > 3.84. In R both rules use step(): k = 2 (the default) is AIC and k = 3.84 is the p-value rule. Terms in between (like weekend) are where the two rules disagree.
  3. Interactions need a reason; an all-pairs search finds noise. The all-pairs search added interactions although the data were simulated with none. Add an interaction when there is a reason to expect it and an LR test supports it.
  4. Choose cutpoints by sensitivity and specificity, not accuracy. At .5 the model is .785 accurate but catches only 17% of plays; predicting “no play” for everyone is already .774 accurate. The Youden cutpoint (.224) balances the two errors.
  5. An AIC gain under 2 is small: prefer the simpler model. That is why the final model leaves out weekend (AIC gain 1.38).

9 References

Burnham, K. P., & Anderson, D. R. (2002). Model selection and multimodel inference: A practical information-theoretic approach (2nd ed.). Springer.

Hosmer, D. W., Lemeshow, S., & Sturdivant, R. X. (2013). Applied logistic regression (3rd ed.). Wiley.

James, G., Witten, D., Hastie, T., & Tibshirani, R. (2021). An introduction to statistical learning: With applications in R (2nd ed.). Springer.

10 Session information

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] knitr_1.45                   ResourceSelection_0.0.0.9000 pROC_1.18.5                 
#>  [4] lmtest_0.9-40                zoo_1.8-12                   car_3.1-2                   
#>  [7] carData_3.0-5                broom_1.0.5                  lubridate_1.9.3             
#> [10] forcats_1.0.0                stringr_1.5.1                dplyr_1.1.4                 
#> [13] purrr_1.0.2                  readr_2.1.5                  tidyr_1.3.1                 
#> [16] tibble_3.2.1                 ggplot2_3.4.4                tidyverse_2.0.0             
#> 
#> loaded via a namespace (and not attached):
#>  [1] gtable_0.3.4     xfun_0.41        bslib_0.6.1      lattice_0.22-5   tzdb_0.4.0      
#>  [6] vctrs_0.6.5      tools_4.3.3      generics_0.1.3   parallel_4.3.3   fansi_1.0.5     
#> [11] highr_0.10       pkgconfig_2.0.3  Matrix_1.6-5     lifecycle_1.0.4  compiler_4.3.3  
#> [16] farver_2.1.1     munsell_0.5.0    htmltools_0.5.7  sass_0.4.8       yaml_2.3.8      
#> [21] pillar_1.9.0     crayon_1.5.2     jquerylib_0.1.4  MASS_7.3-60.0.1  ellipsis_0.3.2  
#> [26] cachem_1.0.8     abind_1.4-5      nlme_3.1-164     tidyselect_1.2.0 digest_0.6.34   
#> [31] stringi_1.8.3    splines_4.3.3    fastmap_1.1.1    grid_4.3.3       colorspace_2.1-0
#> [36] cli_3.6.2        magrittr_2.0.3   utf8_1.2.4       withr_2.5.0      scales_1.3.0    
#> [41] backports_1.4.1  bit64_4.0.5      timechange_0.3.0 rmarkdown_2.25   bit_4.0.5       
#> [46] hms_1.1.3        evaluate_0.23    mgcv_1.9-1       rlang_1.1.3      Rcpp_1.0.12     
#> [51] glue_1.7.0       vroom_1.6.5      jsonlite_1.8.8   R6_2.5.1         plyr_1.8.9