Let’s look at prediction accuracy on our training data:
# Get predictions for all training datatraining_results <- carseat_fit |>predict(new_data = Carseats) |>bind_cols(Carseats)# Look at first few rowstraining_results |>select(Sales, .pred, Price) |>head()
# A tibble: 1 × 3
.metric .estimator .estimate
<chr> <chr> <dbl>
1 rsq standard 0.198
How do we interpret R² = 0.2?
The Problem with Training Accuracy
Is training R² = 0.2 a good estimate of how well our model will predict new sales?
Problem: We’re testing the model on the same data we used to train it!
Cross-Validation for Better Estimates
# Create cross-validation foldsset.seed(1)carseat_folds <-vfold_cv(Carseats, v =5)# Fit model on each fold and test on held-out datacv_results <-linear_reg() |>fit_resamples( Sales ~ Price,resamples = carseat_folds )# Get test performance metricscollect_metrics(cv_results)
# A tibble: 2 × 6
.metric .estimator mean n std_err .config
<chr> <chr> <dbl> <int> <dbl> <chr>
1 rmse standard 2.54 5 0.0717 Preprocessor1_Model1
2 rsq standard 0.202 5 0.0308 Preprocessor1_Model1
Training vs Test Performance
Metric
Training
Cross-Validation
RMSE
2.5
2.5
R-squared
0.2
0.2
What do you notice about training vs cross-validation performance?
Application Exercise
Using your simulated data, create the design matrix X (including intercept column)
Calculate the coefficients manually using: solve(crossprod(X)) %*% t(X) %*% y
Compare these coefficients to what you got from linear_reg() |> tidy()
Try changing the noise standard deviation from 0.5 to 2.0 - how do the predictions change for X₁=1, X₂=0, X₃=0, X₄=0, X₅=0?