23  Regularization

23.1 Case study: recommendation systems

Recommendation systems, such as the one used by Amazon, operate by analyzing the ratings that customers give to various products. These ratings form a large dataset. The system uses this data to predict how likely a specific user is to favorably rate a particular product. For example, if the system predicts that a user is likely to give a high rating to a certain book or gadget, it will recommend that item to them. In essence, the system tries to guess which products a user will like based on the ratings provided by them and other customers for various items. This approach helps in personalizing recommendations to suit individual preferences.

During its initial years of operation, Netflix used a 5-star recommendation system. One star suggested it was not a good movie, whereas five stars suggested it was an excellent movie. Here, we provide the basics of how these recommendations are made, motivated by some of the approaches taken by the winners of the Netflix challenges.

In October 2006, Netflix offered a challenge to the data science community: improve our recommendation algorithm by 10% and win a million dollars. In September 2009, the winners were announced1. You can read a summary of how the winning algorithm was put together here: http://blog.echen.me/2011/10/24/winning-the-netflix-prize-a-summary/ and a more detailed explanation here: https://www2.seas.gwu.edu/~simhaweb/champalg/cf/papers/KorenBellKor2009.pdf. We will now show you some of the data analysis strategies used by the winning team.

23.1.1 Movielens data

The Netflix data is not publicly available, but the GroupLens research lab2 generated their own database with over 20 million ratings for over 27,000 movies by more than 138,000 users. We make a small subset of this data available via the dslabs package:

movielens |> as_tibble() |> head(5)
#> # A tibble: 5 × 7
#>   movieId title                      year genres userId rating timestamp
#>     <int> <chr>                     <int> <fct>   <int>  <dbl>     <int>
#> 1      31 Dangerous Minds            1995 Drama       1    2.5    1.26e9
#> 2    1029 Dumbo                      1941 Anima…      1    3      1.26e9
#> 3    1061 Sleepers                   1996 Thril…      1    3      1.26e9
#> 4    1129 Escape from New York       1981 Actio…      1    2      1.26e9
#> 5    1172 Cinema Paradiso (Nuovo c…  1989 Drama       1    4      1.26e9

Each row represents a rating given by one user to one movie.

It will later be convenient that our userId and movieId are factors, so we change that:

movielens <- mutate(movielens, userId = factor(userId), movieId = factor(movieId))

We can see the number of unique users that provided ratings and how many unique movies were rated:

movielens |> summarize(n_distinct(userId), n_distinct(movieId))
#>   n_distinct(userId) n_distinct(movieId)
#> 1                671                9066

If we multiply those two numbers, we get a number larger than 5 million, yet our data table has about 100,000 rows. This implies that not every user rated every movie. We can think of these data as a very large matrix, with users on the rows and movies on the columns, with many empty cells. Here is the matrix for six users and four movies:

userId Pulp Fiction Shawshank Redemption Forrest Gump Silence of the Lambs
13 3.5 4.5 5.0 NA
15 5.0 2.0 1.0 5.0
16 NA 4.0 NA NA
17 5.0 5.0 2.5 4.5
19 5.0 4.0 5.0 3.0
20 0.5 4.5 2.0 0.5

You can think of the task of a recommendation system as filling in the NAs in the table above. To see how sparse the matrix is, here is the matrix for a random sample of 100 movies and 100 users with yellow indicating a user/movie combination for which we have a rating:

Let’s look at some of the general properties of the data to better understand the challenges.

The first thing we notice is that some movies get rated more than others. Below is the distribution. This is not surprising given that there are blockbuster movies watched by millions and artsy, independent movies watched by just a few. Our second observation is that some users are more active than others at rating movies:

We need to build an algorithm with the collected data that will then be applied outside our control when users look for movie recommendations. To test our idea, we will split the data into a training set, which we will use to develop our approach, and a test set in which we will compute the accuracy of our predictions.

We will do this only for users that have provided at least 100 ratings.

movielens <- movielens |> 
  group_by(userId) |>
  filter(n() >= 100) |>

For each one of these users, we will split their ratings into 80% for training and 20% for testing.

indexes <- split(1:nrow(movielens), movielens$userId)
test_ind <- sapply(indexes, function(i) sample(i, ceiling(length(i)*.2))) |> 
  unlist() |>
test_set <- movielens[test_ind,] 
train_set <- movielens[-test_ind,]

To make sure we don’t include movies in the training set that should not be there, we remove entries using the semi_join function:

test_set <- test_set |> semi_join(train_set, by = "movieId")

We will use the array representation described in Section 17.5, for the training data: we denote ranking for movie \(j\) by user \(i\) as \(y_{i,j}\). To create this matrix, we use pivot_wider:

y <- select(train_set, movieId, userId, rating) |>
  pivot_wider(names_from = movieId, values_from = rating) |>
  column_to_rownames("userId") |>

To be able to map movie IDs to titles we create the following lookup table:

movie_map <- train_set |> select(movieId, title) |> distinct(movieId, .keep_all = TRUE)

Note that two different movies can have the same title. For example, our dataset has three movies titled “King Kong”. Titles are therefore not unique and we can’t use them as IDs.

23.2 Loss function

The Netflix challenge decided on a winner based on the root mean squared error (RMSE) computed on the test set. Specifically, if \(y_{i,j}\) is the rating for movie \(j\) by user \(i\) in the test set and \(\hat{y}_{i,j}\) is our prediction based on the training set, RMSE was defined as:

\[ \mbox{RMSE} = \sqrt{\frac{1}{N} \sum_{i,j}^{N} (y_{i,j} - \hat{y}_{i,j})^2} \]

with \(N\) being the number of user/movie combinations for which we made predictions and the sum occurring over all these combinations.

We can interpret the RMSE similarly to a standard deviation: it is the typical error we make when predicting a movie rating. If this number is larger than 1, it means our typical error is larger than one star, which is not good. We define a function to compute this quantity for any set of residuals:

rmse <- function(r) sqrt(mean(r^2))

In this chapter and the next, we introduce two concepts, regularization and matrix factorization, that were used by the winners of the Netflix challenge to obtain the winning RMSE.

In Chapter 29, we provide a formal discussion of the mean squared error.

23.3 A first model

Let’s start by building the simplest possible recommendation system: we predict the same rating for all movies regardless of user. What number should this prediction be? We can use a model based approach to answer this. A model that assumes the same rating for all movies and users with all the differences explained by random variation would look as follows:

\[ Y_{i,j} = \mu + \varepsilon_{i,j} \]

with \(\varepsilon_{i,j}\) independent errors sampled from the same distribution centered at 0 and \(\mu\) the true rating for all movies. We know that the estimate that minimizes the RMSE is the least squares estimate of \(\mu\) and, in this case, is the average of all ratings:

mu <- mean(y, na.rm = TRUE)

If we predict all unknown ratings with \(\hat{\mu}\), we obtain the following RMSE:

rmse(test_set$rating - mu)
#> [1] 1.04

Keep in mind that if you plug in any other number, you get a higher RMSE. For example:

rmse(test_set$rating - 3)
#> [1] 1.16

To win the grand prize of $1,000,000, a participating team had to get an RMSE of about 0.857. So we can definitely do better!

23.4 User effects

If we visualize the average rating for each user:

hist(rowMeans(y, na.rm = TRUE), nclass = 30)

we notice that there is substantial variability across users: some users are very cranky and others love most movies. To account for this, we can use a linear model with a treatment effect \(\alpha_i\) for each user. The sum \(\mu+\alpha_i\) can be interpreted as the typical rating user \(i\) gives to movies. We can write the model as:

\[ Y_{i,j} = \mu + \alpha_i + \varepsilon_{i,j} \]

Statistics textbooks refer to the \(\alpha\)s as treatment effects. In the Netflix challenge papers, they refer to them as bias.

We can again use least squares to estimate the \(\alpha_i\) in the following way:

fit <- lm(rating ~ userId, data = train_set)

Because there are hundreds of \(\alpha_i\), as each movie gets one, the lm() function will be very slow here. In this case, we can show that the least squares estimate \(\hat{\alpha}_i\) is just the average of \(y_{i,j} - \hat{\mu}\) for each user \(i\). So we can compute them this way:

a <- rowMeans(y - mu, na.rm = TRUE)

Note that going forward, we drop the hat notation in the code to represent estimates.

Let’s see how much our prediction improves once we use \(\hat{y}_{i,j} = \hat{\mu} + \hat{\alpha}_i\). Because we know ratings can’t be below 0.5 or above 5, we define the function clamp:

clamp <- function(x, min = 0.5, max = 5) pmax(pmin(x, max), min)

to keep predictions in that range and then compute the RMSE:

test_set |> 
  left_join(data.frame(userId = names(a), a = a), by = "userId") |>
  mutate(resid = rating - clamp(mu + a)) |> pull(resid) |> rmse()
#> [1] 0.958

We already see an improvement. But can we make it better?

23.5 Movie effects

We know from experience that some movies are just generally rated higher than others. We can use a linear model with a treatment effect \(\beta_j\) for each movie, which can be interpreted as movie effect or the difference between the average ranking for movie \(j\) and the overall average \(\mu\):

\[ Y_{i,j} = \mu + \alpha_i + \beta_j +\varepsilon_{i,j} \]

We can again use least squares to estimate the \(b_i\) in the following way:

fit <- lm(rating ~ userId + movieId, data = train_set)

However, this code generates a very large matrix with all the indicator variables needed to represent all the movies and the code will take time to run. We instead use an approximation by first computing the least square estimate \(\hat{\mu}\) and \(\hat{\alpha}_i\), and then estimating \(\hat{\beta}_j\) as the average of the residuals \(y_{i,j} - \hat{\mu} - \hat{\alpha}_i\):

b <- colMeans(y - mu - a, na.rm = TRUE)

We can now construct predictors and see how much the RMSE improves:

test_set |> 
  left_join(data.frame(userId = names(a), a = a), by = "userId") |>
  left_join(data.frame(movieId = names(b), b = b), by = "movieId") |>
  mutate(resid = rating - clamp(mu + a + b)) |> pull(resid) |> rmse()
#> [1] 0.911

23.6 Penalized least squares

If we look at the top movies based on our estimates of the movie effect \(\hat{\beta}_j\), we find that they all obscure movies with just one rating:

n <- colSums(!is.na(y))
ind <- which(b == max(b))
filter(movie_map, movieId %in% names(b)[ind]) |> pull(title)
#> [1] "Prisoner of the Mountains (Kavkazsky plennik)"
#> [2] "Dream With the Fishes"                        
#> [3] "Storefront Hitchcock"                         
#> [4] "Anatomy (Anatomie)"                           
#> [5] "Two Ninas"                                    
#> [6] "Erik the Viking"                              
#> [7] "Grass Is Greener, The"                        
#> [8] "Caveman"
#> 1450 1563 1819 3892 4076 4591 4796 5427 
#>    1    1    1    1    1    1    1    1

Do we really think these are the top movies in our database? The one of these that appears in our test set receives a terrible rating:

filter(test_set, movieId %in% names(b)[ind]) |> 
  group_by(title, movieId) |>
  summarize(rating = mean(rating), .groups = "drop")
#> # A tibble: 1 × 3
#>   title              movieId rating
#>   <chr>              <fct>    <dbl>
#> 1 Anatomy (Anatomie) 3892         1

Large estimates, negative or positive, should not trusted when based on a small number of ratings. Because large errors can increase our RMSE, we would rather be conservative when unsure.

In previous sections, we computed standard error and constructed confidence intervals to account for different levels of uncertainty. However, when making predictions, we need one number, one prediction, not an interval. For this, we introduce the concept of regularization.

Regularization permits us to penalize large estimates that are formed using small sample sizes. It has commonalities with the Bayesian approach that shrunk predictions described in Chapter 12.

The general idea behind regularization is to constrain the total variability of the effect sizes. Why does this help? Consider a case in which we have movie \(j=1\) with 100 user ratings and 4 movies \(j=2,3,4,5\) with just one user rating. Suppose we know the average rating is, say, \(\mu = 3\). If we use least squares, the estimate for the first movie effect is the average of 100 user ratings, which we expect to be quite precise. However, the estimate for movies 2, 3, 4, and 5 will be based on one observation. Note that because the average is based on a single observation, the error for \(j=2,3,4,5\) is 0, but we don’t expect to be this lucky next time, when asked to predict. In fact, ignoring the one user and guessing that movies 2,3,4, and 5 are just average movies might provide a better prediction. The general idea of penalized regression is to control the total variability of the movie effects: \(\sum_{j=1}^5 \beta_j^2\). Specifically, instead of minimizing the least squares equation, we minimize an equation that adds a penalty:

\[ \sum_{i,j} \left(y_{u,i} - \mu - \alpha_i - \beta_j \right)^2 + \lambda \sum_{j} \beta_j^2 \] The first term is just the sum of squares and the second is a penalty that gets larger when many \(\beta_i\)s are large. Using calculus, we can actually show that the values of \(\beta_i\) that minimize this equation are:

\[ \hat{\beta}_j(\lambda) = \frac{1}{\lambda + n_j} \sum_{i=1}^{n_i} \left(Y_{i,j} - \mu - \alpha_i\right) \]

where \(n_j\) is the number of ratings made for movie \(j\).

When we estimate the parameters of a linear model with penalized least squares, we refer to the approach as ridge regression. The lm.ridge function in the MASS package can perform the estimation. We don’t use it here due to the large numbers of parameters associated with movie effects.

This approach will have our desired effect: when our sample size \(n_j\) is very large, we obtain a stable estimate and the penalty \(\lambda\) is effectively ignored since \(n_j+\lambda \approx n_j\). Yet when the \(n_j\) is small, then the estimate \(\hat{\beta}_i(\lambda)\) is shrunken towards 0. The larger the \(\lambda\), the more we shrink.

But how do we select \(\lambda\)? In Chapter 29, we describe an approach to do this. Here we will simply compute the RMSE we for different values of \(\lambda\) to illustrate the effect:

n <- colSums(!is.na(y))
sums <- colSums(y - mu - a, na.rm = TRUE)
lambdas <- seq(0, 10, 0.1)
rmses <- sapply(lambdas, function(lambda){
  b <-  sums / (n + lambda)
  test_set |> 
    left_join(data.frame(userId = names(a), a = a), by = "userId") |>
    left_join(data.frame(movieId = names(b), b = b), by = "movieId") |>
    mutate(resid = rating - clamp(mu + a + b)) |> pull(resid) |> rmse()

Here is a plot of the RMSE versus \(\lambda\):

plot(lambdas, rmses, type = "l")

The minimum is obtained for \(\lambda=\) 3.2

Using this \(\lambda\), we can compute the regularized estimates and add to our table of estimates:

lambda <- lambdas[which.min(rmses)] 
b_reg <- sums / (n + lambda)

To see how the estimates shrink, let’s make a plot of the regularized estimates versus the least squares estimates.

Now, let’s look at the top 5 best movies based on the penalized estimates \(\hat{b}_i(\lambda)\):

#> # A tibble: 10 × 5
#>   title                      year rating b_reg     n
#>   <chr>                     <int>  <dbl> <dbl> <dbl>
#> 1 Shawshank Redemption, The  1994   4.57 0.793   138
#> 2 Chinatown                  1974   4.5  0.734    51
#> 3 Dangerous Beauty           1998   4.5  0.764     2
#> 4 Godfather, The             1972   4.45 0.774   107
#> 5 Usual Suspects, The        1995   4.40 0.752   109
#> # ℹ 5 more rows

These make more sense with some movies that are watched more and have more ratings in the training set.

Notice Swinger has a lower rating than the other top 10, yet a large movie effect estimate. This is due to the fact that it was rated by harsher users.

Note that regularization improves our RMSE:

test_set |> 
  left_join(data.frame(userId = names(a), a = a), by = "userId") |>
  left_join(data.frame(movieId = names(b_reg), b_reg = b_reg), by = "movieId") |>
  mutate(resid = rating - clamp(mu + a + b_reg)) |> pull(resid) |> rmse()
#> [1] 0.889

The penalized estimates provide an improvement over the least squares estimates:

model RMSE
Just the mean 1.043
User effect 0.958
User + movie effect 0.911
User + regularized movie effect 0.889

23.7 Exercises

1. For the movielens data, compute the number of ratings for each movie and then plot it against the year the movie was released. Use the square root transformation on the counts.

2. We see that, on average, movies that were released after 1993 get more ratings. We also see that with newer movies, starting in 1993, the number of ratings decreases with year: the more recent a movie is, the less time users have had to rate it.

Among movies that came out in 1993 or later, what are the 25 movies with the most ratings per year? Also, report their average rating.

3. From the table constructed in the previous example, we see that the most rated movies tend to have above average ratings. This is not surprising: more people watch popular movies. To confirm this, stratify the post 1993 movies by ratings per year and compute their average ratings. Make a plot of average rating versus ratings per year and show an estimate of the trend.

4. In the previous exercise, we see that the more a movie is rated, the higher the rating. Suppose you are doing a predictive analysis in which you need to fill in the missing ratings with some value. Which of the following strategies would you use?

  1. Fill in the missing values with average rating of all movies.
  2. Fill in the missing values with 0.
  3. Fill in the value with a lower value than the average since lack of rating is associated with lower ratings. Try out different values and evaluate prediction in a test set.
  4. None of the above.

5. The movielens dataset also includes a time stamp. This variable represents the time and data in which the rating was provided. The units are seconds since January 1, 1970. Create a new column date with the date. Hint: Use the as_datetime function in the lubridate package.

6. Compute the average rating for each week and plot this average against day. Hint: Use the round_date function before you group_by.

7. The plot shows some evidence of a time effect. If we define \(d_{u,i}\) as the day for user’s \(u\) rating of movie \(i\), which of the following models is most appropriate:

  1. \(Y_{u,i} = \mu + b_i + \beta_j + d_{u,i} + \varepsilon_{u,i}\).
  2. \(Y_{u,i} = \mu + b_i + \beta_j + d_{u,i}\beta + \varepsilon_{u,i}\).
  3. \(Y_{u,i} = \mu + b_i + \beta_j + d_{u,i}\beta_i + \varepsilon_{u,i}\).
  4. \(Y_{u,i} = \mu + b_i + \beta_j + f(d_{u,i}) + \varepsilon_{u,i}\), with \(f\) a smooth function of \(d_{u,i}\).

8. The movielens data also has a genres column. This column includes every genre that applies to the movie. Some movies fall under several genres. Define a category as whatever combination appears in this column. Keep only categories with more than 1,000 ratings. Then compute the average and standard error for each category. Plot these as error bar plots.

9. The plot shows strong evidence of a genre effect. If we define \(g_{u,i}\) as the genre for user’s \(u\) rating of movie \(i\), which of the following models is most appropriate:

  1. \(Y_{u,i} = \mu + b_i + \beta_j + d_{u,i} + \varepsilon_{u,i}\).
  2. \(Y_{u,i} = \mu + b_i + \beta_j + d_{u,i}\beta + \varepsilon_{u,i}\).
  3. \(Y_{u,i} = \mu + b_i + \beta_j + \sum_{k=1}^K x_{u,i} \beta_k + \varepsilon_{u,i}\), with \(x^k_{u,i} = 1\) if \(g_{u,i}\) is genre \(k\).
  4. \(Y_{u,i} = \mu + b_i + \beta_j + f(d_{u,i}) + \varepsilon_{u,i}\), with \(f\) a smooth function of \(d_{u,i}\).

An education expert is advocating for smaller schools. The expert bases this recommendation on the fact that among the best performing schools, many are small schools. Let’s simulate a dataset for 100 schools. First, let’s simulate the number of students in each school.

n <- round(2^rnorm(1000, 8, 1))

Now let’s assign a true quality for each school completely independent from size. This is the parameter we want to estimate.

mu <- round(80 + 2 * rt(1000, 5))
schools <- data.frame(id = paste("PS",1:100), 
                      size = n, 
                      quality = mu,
                      rank = rank(-mu))

We can see that the top 10 schools are:

schools |> top_n(10, quality) |> arrange(desc(quality))

Now let’s have the students in the school take a test. There is random variability in test taking so we will simulate the test scores as normally distributed with the average determined by the school quality and standard deviations of 30 percentage points:

scores <- sapply(1:nrow(schools), function(i){
  scores <- rnorm(schools$size[i], schools$quality[i], 30)
schools <- schools |> mutate(score = sapply(scores, mean))

10. What are the top schools based on the average score? Show just the ID, size, and the average score.

11. Compare the median school size to the median school size of the top 10 schools based on the score.

12. According to this test, it appears small schools are better than large schools. Five out of the top 10 schools have 100 or fewer students. But how can this be? We constructed the simulation so that quality and size are independent. Repeat the exercise for the worst 10 schools.

13. The same is true for the worst schools! They are small as well. Plot the average score versus school size to see what’s going on. Highlight the top 10 schools based on the true quality. Use the log scale transform for the size.

14. We can see that the standard error of the score has larger variability when the school is smaller. This is a basic statistical reality we learned in the probability and inference sections. In fact, note that 4 of the top 10 schools are in the top 10 schools based on the exam score.

Let’s use regularization to pick the best schools. Remember regularization shrinks deviations from the average towards 0. So to apply regularization here, we first need to define the overall average for all schools:

overall <- mean(sapply(scores, mean))

and then define, for each school, how it deviates from that average. Write code that estimates the score above average for each school, but dividing by \(n + \lambda\) instead of \(n\), with \(n\) the school size and \(\lambda\) a regularization parameter. Try \(\lambda = 3\).

15. Notice that this improves things a bit. The number of small schools that are not highly ranked is now 4. Is there a better \(\lambda\)? Find the \(\lambda\) that minimizes the RMSE = \(1/100 \sum_{i=1}^{100} (\mbox{quality} - \mbox{estimate})^2\).

16. Rank the schools based on the average obtained with the best \(\alpha\). Note that no small school is incorrectly included.

17. A common mistake to make when using regularization is shrinking values towards 0 that are not centered around 0. For example, if we don’t subtract the overall average before shrinking, we actually obtain a very similar result. Confirm this by re-running the code from exercise 6, but without removing the overall mean.

  1. http://bits.blogs.nytimes.com/2009/09/21/netflix-awards-1-million-prize-and-starts-a-new-contest/↩︎

  2. https://grouplens.org/↩︎