Interactive R programming · Machine learning

Lasso Regression in R, the game

Learn Lasso by playing it. Seven short missions, a live λ playground built on real data, and a final boss quiz. Collect XP and unlock the Lasso Master badge.

~15 minBeginner friendlyR · glmnet7 missions
Mission 1+50 XP✓ Complete

Meet the villain: overfitting

A model overfits when it learns the training data too well, noise included. It scores brilliantly on data it has seen and badly on data it hasn’t, because it has become too complex: too many features, or weights that are too large.

Regularization fights this. It adds a small penalty for complexity, so the model prefers simpler explanations that generalize to new data. Lasso is one of the most popular regularization techniques.

🔍Spot the overfit

Same training points, three models. Which one has memorized the data instead of learning the trend?

Mission 2+50 XP✓ Complete

Decode the name

Lasso is a special type of linear regression that adds a penalty based on the absolute values of the coefficients (the numbers in front of each feature). That penalty shrinks unimportant coefficients, and can push some of them all the way to zero, removing those features from the model. This is called L1 regularization.

Lasso is especially useful when:

  • your dataset has many features, maybe more than you have rows;
  • some features are very similar to each other (multicollinearity);
  • you want the model to pick the useful features for you.
🃏Flip all five letters
0 / 5
Mission 3+100 XP✓ Complete

Pull the λ lever

Lasso minimizes the usual error plus a penalty on the size of the coefficients:

Cost = Σ (yi − ŷi)² + λ · Σ |βj|Residual sum of squares + λ × sum of the absolute coefficient values
  • λ = 0: no penalty, so you get ordinary linear regression with every feature.
  • Bigger λ: coefficients shrink and unimportant ones hit exactly zero. More bias, less variance.
  • Very large λ: every coefficient is zero and the model just predicts the average.
🎛️λ playground
mtcars · predict mpg
0.0005λ value
10 / 10features kept
0.869R² on training data
raises mpglowers mpgBars are standardized coefficients, so sizes are comparable.
  • ✓Squeeze the model down to exactly 3 features+30 XP
  • ✓Raise λ until every feature is gone+20 XP
  • ✓Go back to λ ≈ 0 (plain linear regression)+20 XP

Prediction challenge: which two features survive the strongest penalty?

The playground uses the same algorithm as glmnet (coordinate descent on standardized features, 100 λ values) on R’s built-in mtcars data. At the smallest λ the coefficients match ordinary least squares, exactly as the theory says.

Mission 4+60 XP✓ Complete

Lasso vs Ridge: rapid fire

Ridge regression also adds a penalty, so what’s the difference? Lasso uses L1 (absolute values, |β|) and Ridge uses L2 (squares, β²). The L1 penalty produces sparse models: some coefficients become exactly zero. Ridge shrinks every coefficient towards zero but keeps them all.

⚡Lasso, Ridge or both?
1 / 6
correct on the first try
Mission 5+50 XP✓ Complete

Code it in R

Time to run Lasso yourself with the glmnet package. The workflow: load the data, split features and target, fit the model, then use cross-validation to pick the best λ.

Step 1Install and load glmnet

install.packages("glmnet")
library(glmnet)

Step 2Load the data

data(mtcars)
head(mtcars)

Step 3Separate the target and the features

target   <- mtcars$mpg
features <- as.matrix(mtcars[, -which(names(mtcars) == "mpg")])

glmnet needs the features as a matrix, not a data frame.

🧩Fill the blank
+25 XP

lasso <- glmnet(x = features, y = target, alpha = ___)
Which value makes this a Lasso model?

Step 4Fit Lasso and plot the coefficient paths

lasso <- glmnet(x = features, y = target, alpha = 1)

# How each coefficient shrinks as λ grows
plot(lasso, xvar = "lambda", label = TRUE)

This plot is exactly what you played with in Mission 3: each line is one feature, dropping to zero as λ increases.

Step 5Find the best λ with cross-validation

set.seed(42)  # CV folds are random; this makes results repeatable
cv_lasso <- cv.glmnet(x = features, y = target, alpha = 1)

# Cross-validation error for every λ
plot(cv_lasso)

# Best lambda value
best_lambda <- cv_lasso$lambda.min
print(paste("Best lambda:", best_lambda))

# Coefficients at the best λ (a "." means the feature was dropped)
coef(cv_lasso, s = "lambda.min")
🧠Read the output
+25 XP

In the output of coef(cv_lasso, s = "lambda.min"), some rows show a . instead of a number. What does that mean?

Mission 6+80 XP✓ Complete

Strength or weakness?

Every algorithm has trade-offs. Lasso is great at simplifying models, but it isn’t magic. Sort each statement to see where it shines and where it struggles.

⚖️Sort the cards
1 / 8
sorted correctly
Final boss+105 XP✓ Defeated

Defeat the Overfit Dragon 🐉

Seven questions and three hearts. A wrong answer costs a heart; lose all three and the dragon wins this round (you can try again). Beat it to earn the Lasso Master badge.

Question 1 / 7
❤️❤️❤️

🐉 The dragon winsReview the missions above, then try again.

You’re a Lasso Master!

Share on LinkedIn
What’s next

Keep levelling up

In this lesson you learned what Lasso regression is, how the λ penalty works, how it differs from Ridge, how to run it in R with glmnet, and where it shines or struggles.

Lv 1 Rookie 0 / 495 XP