R1 Part 2: Regularised Feature Selection & Predictive ML Benchmarking

Mohammad Abbas

2026-11-30

Purpose of R1 Part 2

R1 Part 1 established interpretable models of aerobic demand and rested status using derived physiological variables within the sportsfeatures framework. The Decomposed Multiple Linear Regression Model explained approximately 76.5% of the observed variation in aerobic demand, providing a benchmark for further predictive analysis. R1 Part 2 extends this work through regularised feature selection and out-of-sample predictive evaluation. LASSO and Elastic Net assess predictor retention, while Random Forest provides a non-linear comparison of predictive performance.

Why Machine Learning?

Traditional regression models provide interpretable estimates of physiological relationships and support our understanding in data modelling. Within the sportsfeatures context, as the number of derived variables increases, correlated predictors and non-linear relationships can make modelling more challenging. Machine-learning approaches offer alternative ways to address these challenges. LASSO and Elastic Net support regularised feature selection, while Random Forest addresses non-linear relationships and interactions without requiring them to be specified explicitly. These methods allow predictive performance to be evaluated beyond the statistical benchmarks established in R1 Part 1.

Why LASSO, Elastic Net and Random Forest?

This vignette uses three complementary modelling approaches to explore feature selection and predictive performance. Each provides a different perspective on predictor selection, model complexity, and out-of-sample performance. LASSO applies an L1 penalty that progressively shrinks coefficient estimates towards zero as the penalty increases. This allows a smaller set of predictors to be identified from the wider collection of physiological, session-level, and contextual features. Elastic Net combines L1 and L2 penalties, retaining the feature-selection properties of LASSO while allowing correlated predictors to remain represented in the fitted model. Random Forest provides a contrasting non-linear approach without estimating a penalised linear coefficient structure. It uses an ensemble of decision trees to represent more complex relationships among predictors.

MODEL 04: LASSO and Elastic Net Feature Selection

Model Overview

Unlike the models examined in the preceding vignette, Model 04 applies regularised feature selection. LASSO and Elastic Net apply coefficient penalties that can shrink predictor estimates towards zero during model fitting.

Hypothesis and Intent

Hypothesis: A regularised regression framework can identify a simpler subset of physiological, session-level, activity-related, and contextual predictors of VO₂ utilisation by shrinking less informative coefficient estimates towards zero.

Intent: Using a common predictor matrix and cross-validated penalty selection, the analysis compares LASSO and Elastic Net to identify which predictors remain active under regularisation. Model 05 subsequently evaluates predictive performance.

Mathematical Formulation

For observations i = 1, …, N, the Elastic Net objective can be written as

$$ \min_{\beta_0,\boldsymbol{\beta}} \left[ \frac{1}{2N} \sum_{i=1}^{N} \left( y_i-\beta_0-\mathbf{x}_i^{\mathsf T}\boldsymbol{\beta} \right)^2 + \lambda \left( \frac{1-\alpha}{2}\|\boldsymbol{\beta}\|_2^2 + \alpha\|\boldsymbol{\beta}\|_1 \right) \right]. $$

Here, λ controls the overall strength of regularisation and α determines the balance between L1 and L2 penalties. Setting α = 1 produces the LASSO specification, whereas α = 0.5 produces the Elastic Net specification used in this analysis. Cross-validation is used to select the penalty parameter, with lambda.1se providing the more parsimonious cross-validated solution used for coefficient inspection.

Load Required R Libraries

library(dplyr)
library(ggplot2)
library(glmnet)
library(stringr)
library(tidyr)
library(ranger)
library(broom)

data("sports_features_missing", package = "sportsfeatures")

df_sports <- sports_features_missing %>%
type.convert(as.is = TRUE)

Predictor Derivation, Recoding and Selection

df_ml1 <- df_sports %>%
  mutate(pace_min_km = round(duration_min / distance_km, 2)) %>%
  group_by(athlete_id) %>%
  mutate(
    athlete_mean_distance = round(mean(distance_km, na.rm = TRUE), 2),
    distance_centered     = round(distance_km - athlete_mean_distance, 2),
    athlete_mean_pace     = round(mean(pace_min_km, na.rm = TRUE), 2),
    pace_centered         = round(pace_min_km - athlete_mean_pace, 2),
    athlete_mean_fatigue  = round(mean(fatigue_score, na.rm = TRUE), 2),
    fatigue_deviation     = round(fatigue_score - athlete_mean_fatigue, 2)
  ) %>%
  ungroup() %>%
  mutate(
    activity_group = factor(case_when(
      str_detect(activity_type, regex("cycle|bike", ignore_case = TRUE)) ~ "Cycling",
      str_detect(activity_type, regex("walk", ignore_case = TRUE)) ~ "Walking",
      str_detect(activity_type, regex("hiking", ignore_case = TRUE)) ~ "Hiking",
      str_detect(activity_type, regex("run|jog", ignore_case = TRUE)) ~ "Running",
      TRUE ~ "Other"
    )),
    weather_group = factor(case_when(
      str_detect(weather_type, regex("cloud", ignore_case = TRUE)) ~ "Cloudy",
      str_detect(weather_type, regex("overcast", ignore_case = TRUE)) ~ "Overcast",
      str_detect(weather_type, regex("rain|shower", ignore_case = TRUE)) ~ "Rain",
      str_detect(weather_type, regex("sun|clear", ignore_case = TRUE)) ~ "Sunny",
      TRUE ~ "Other"
    )),
    personal_status = factor(str_replace_all(str_to_title(personal_status), "_", " "))
  ) %>%
  filter(!is.na(vo2_utilisation))

Construct the Predictor Matrix and Outcome Vector

# Dummy-code categorical factors automatically
X_matrix <- model.matrix(
  vo2_utilisation ~ distance_centered + athlete_mean_distance +
                    pace_centered + athlete_mean_pace +
                    fatigue_deviation + athlete_mean_fatigue +
                    age + calories_per_min +
                    activity_group + weather_group + personal_status,
  data = df_ml1
)[, -1] # Remove intercept column

Y_vector <- df_ml1$vo2_utilisation

Fit the Cross-Validated LASSO Model

set.seed(42)
cv_lasso <- cv.glmnet(X_matrix, Y_vector, alpha = 1, nfolds = 10, standardize = TRUE)

cat("--- LASSO FEATURE SELECTION (lambda.1se) ---\n")
cat("Optimal Lambda (min):", round(cv_lasso$lambda.min, 5), "\n")
cat("Parsimonious Lambda (1se):", round(cv_lasso$lambda.1se, 5), "\n\n")

# Robust extraction using broom::tidy
lasso_coefs <- tidy(cv_lasso$glmnet.fit) %>%
  filter(lambda == cv_lasso$lambda.1se & estimate != 0) %>%
  select(term, estimate) %>%
  rename(Feature = term, Coefficient = estimate) %>%
  mutate(Coefficient = round(Coefficient, 5))

print(lasso_coefs)

Fit the Cross-Validated Elastic Net Model

set.seed(42)
cv_enet <- cv.glmnet(X_matrix, Y_vector, alpha = 0.5, nfolds = 10, standardize = TRUE)

cat("\n--- ELASTIC NET FEATURE SELECTION (alpha = 0.5, lambda.1se) ---\n")
cat("Optimal Lambda (min):", round(cv_enet$lambda.min, 5), "\n")
cat("Parsimonious Lambda (1se):", round(cv_enet$lambda.1se, 5), "\n\n")

enet_coefs <- tidy(cv_enet$glmnet.fit) %>%
  filter(lambda == cv_enet$lambda.1se & estimate != 0) %>%
  select(term, estimate) %>%
  rename(Feature = term, Coefficient = estimate) %>%
  mutate(Coefficient = round(Coefficient, 5))

 print(enet_coefs)

Table 4.1. Elastic Net Coefficients at lambda.1se

Feature / Predictor Regularised Coefficient (β) Interpretation at lambda.1se
(Intercept) 0.50900 Penalised-model intercept.
distance_centered +0.00107 Retained with a small positive coefficient.
pace_centered −0.01460 Retained with a negative coefficient.
athlete_mean_pace −0.02110 Retained with a negative coefficient.
athlete_mean_fatigue +0.00630 Retained with a positive coefficient.
age −0.00011 Retained, but strongly shrunk towards zero.
calories_per_min +0.00314 Retained with a small positive coefficient.
activity_groupRunning +0.05390 Retained activity-group contrast relative to the model-matrix reference level.
activity_groupWalking −0.01270 Retained activity-group contrast relative to the model-matrix reference level.
weather_groupOther +0.00434 Retained weather-group contrast with a small positive coefficient.
weather_groupOvercast −0.00037 Retained, but strongly shrunk towards zero.
weather_groupRain +0.00624 Retained weather-group contrast with a small positive coefficient.
personal_statusOptimal −0.00305 Retained personal-status contrast with a small negative coefficient.
personal_statusPoor sleep −0.00466 Retained personal-status contrast with a small negative coefficient.
personal_statusTired −0.00346 Retained personal-status contrast with a small negative coefficient.

Cross-Validation Profiles for LASSO and Elastic Net

# Cross-Validation Profiles for LASSO and Elastic Net
par(mfrow = c(1, 2))
plot(cv_lasso, main = "LASSO (alpha = 1)")
plot(cv_enet, main = "Elastic Net (alpha = 0.5)")

Figure 4.1. Cross-validation error profiles across the LASSO and Elastic Net penalty paths.
par(mfrow = c(1, 1))

Key Findings and Analytical Insight

Key Summary Statistics

The visual summary below brings together the main Model 04 results: the LASSO and Elastic Net penalty specifications, the cross-validated lambda.1se solutions, and selected retained or strongly shrunk coefficients.

Figure 4.2. Key regularisation settings and selected coefficient patterns from the LASSO and Elastic Net models.

From Model 04 to Model 05: Feature Selection to Predictive Generalisation

As feature selection and retention do not establish predictive performance, Model 05 evaluates OLS, Elastic Net, and Random Forest using a common train-test split to compare predictive performance on held-out observations.

MODEL 05: Out-of-Sample Predictive Benchmarking

Model Overview

This model focuses on predictive evaluation through held-out observations. A common predictor specification is used to compare three modelling approaches: ordinary least-squares regression, Elastic Net regression, and Random Forest regression.

The available observations are divided into an 80% training subset and a 20% test subset. Each model is fitted using the training data, and predictive performance is then evaluated against the observed vo2_utilisation values in the held-out test data.

Hypothesis and Intent

Hypothesis: Predictive performance on the held-out test subset may differ across linear, regularised linear, and non-linear ensemble approaches because the models represent predictor relationships with different levels of flexibility.

Intent: The analysis compares Ordinary Least Squares, Elastic Net, and Random Forest regression using a common random train-test partition. Performance is evaluated using Root Mean Squared Error, Mean Absolute Error, and out-of-sample R2. The objective is to identify which model predicts the held-out observations best within this data split.

Out-of-Sample Evaluation Metrics

For a test subset containing ntest observations, predictive error is evaluated using Root Mean Squared Error:

$$ \mathrm{RMSE} = \sqrt{ \frac{1}{n_{\mathrm{test}}} \sum_{i=1}^{n_{\mathrm{test}}} (y_i-\hat{y}_i)^2 }, $$

and Mean Absolute Error:

$$ \mathrm{MAE} = \frac{1}{n_{\mathrm{test}}} \sum_{i=1}^{n_{\mathrm{test}}} |y_i-\hat{y}_i|. $$

Out-of-sample R2 is calculated as

$$ R^2_{\mathrm{test}} = 1- \frac{ \sum_{i=1}^{n_{\mathrm{test}}}(y_i-\hat{y}_i)^2 }{ \sum_{i=1}^{n_{\mathrm{test}}}(y_i-\bar{y}_{\mathrm{test}})^2 }. $$

Lower RMSE and MAE values indicate smaller prediction errors, while a higher out-of-sample R2 indicates that the fitted predictions account for a greater proportion of variation in the held-out outcome values.

Prepare Row-Level Data for Out-of-Sample Evaluation

# Create only variables that can be calculated independently for each row.
# Athlete means and centred predictors are intentionally not calculated here.

df_ml_base <- df_sports %>%
  mutate(
    pace_min_km = round(duration_min / distance_km, 2),

    activity_group = factor(
      case_when(
        str_detect(
          activity_type,
          regex("cycle|bike", ignore_case = TRUE)
        ) ~ "Cycling",

        str_detect(
          activity_type,
          regex("walk", ignore_case = TRUE)
        ) ~ "Walking",

        str_detect(
          activity_type,
          regex("hiking", ignore_case = TRUE)
        ) ~ "Hiking",

        str_detect(
          activity_type,
          regex("run|jog", ignore_case = TRUE)
        ) ~ "Running",

        TRUE ~ "Other"
      )
    ),

    weather_group = factor(
      case_when(
        str_detect(
          weather_type,
          regex("cloud", ignore_case = TRUE)
        ) ~ "Cloudy",

        str_detect(
          weather_type,
          regex("overcast", ignore_case = TRUE)
        ) ~ "Overcast",

        str_detect(
          weather_type,
          regex("rain|shower", ignore_case = TRUE)
        ) ~ "Rain",

        str_detect(
          weather_type,
          regex("sun|clear", ignore_case = TRUE)
        ) ~ "Sunny",

        TRUE ~ "Other"
      )
    ),

    personal_status = factor(
      str_replace_all(
        str_to_title(personal_status),
        "_",
        " "
      )
    )
  ) %>%
  filter(
    !is.na(vo2_utilisation),
    !is.na(athlete_id),
    !is.na(distance_km),
    !is.na(pace_min_km),
    !is.na(fatigue_score),
    !is.na(calories_per_min),
    !is.na(activity_group),
    !is.na(weather_group),
    !is.na(personal_status)
  )

Generate an 80/20 Random Train-Test Split

set.seed(123)

train_indices <- sample(
  seq_len(nrow(df_ml_base)),
  size = floor(0.8 * nrow(df_ml_base))
)

train_base <- df_ml_base[train_indices, , drop = FALSE]
test_base  <- df_ml_base[-train_indices, , drop = FALSE]

cat("--- DATA SPLIT SUMMARY ---\n")
--- DATA SPLIT SUMMARY ---
cat("Training Set Rows:", nrow(train_base), "\n")
Training Set Rows: 322 
cat("Testing Set Rows :", nrow(test_base), "\n\n")
Testing Set Rows : 81 

Apply the training-derived means to both subsets

# Construct Training and Test Predictors

train_data <- train_base %>%
  select(
    -any_of(c(
      "athlete_mean_distance",
      "athlete_mean_pace",
      "athlete_mean_fatigue",
      "distance_centered",
      "pace_centered",
      "fatigue_deviation"
    ))
  ) %>%
  left_join(
    athlete_training_means,
    by = "athlete_id"
  ) %>%
  mutate(
    distance_centered = round(
      distance_km - athlete_mean_distance,
      2
    ),

    pace_centered = round(
      pace_min_km - athlete_mean_pace,
      2
    ),

    fatigue_deviation = round(
      fatigue_score - athlete_mean_fatigue,
      2
    )
  )

test_data <- test_base %>%
  select(
    -any_of(c(
      "athlete_mean_distance",
      "athlete_mean_pace",
      "athlete_mean_fatigue",
      "distance_centered",
      "pace_centered",
      "fatigue_deviation"
    ))
  ) %>%
  left_join(
    athlete_training_means,
    by = "athlete_id"
  ) %>%
  mutate(
    distance_centered = round(
      distance_km - athlete_mean_distance,
      2
    ),

    pace_centered = round(
      pace_min_km - athlete_mean_pace,
      2
    ),

    fatigue_deviation = round(
      fatigue_score - athlete_mean_fatigue,
      2
    )
  )

Compute Out-of-Sample Performance Metrics

calc_metrics <- function(actual, predicted) {

  complete_predictions <- complete.cases(
    actual,
    predicted
  )

  actual_complete <- actual[complete_predictions]
  predicted_complete <- predicted[complete_predictions]

  rmse_val <- sqrt(
    mean(
      (actual_complete - predicted_complete)^2
    )
  )

  mae_val <- mean(
    abs(
      actual_complete - predicted_complete
    )
  )

  test_sse <- sum(
    (actual_complete - predicted_complete)^2
  )

  test_sst <- sum(
    (actual_complete - mean(actual_complete))^2
  )

  r2_val <- 1 - (test_sse / test_sst)

  c(
    RMSE = rmse_val,
    MAE = mae_val,
    R2_OutSample = r2_val
  )
}

results_ols <- calc_metrics(
  test_data$vo2_utilisation,
  pred_ols
)

results_enet <- calc_metrics(
  test_data$vo2_utilisation,
  pred_enet
)

results_rf <- calc_metrics(
  test_data$vo2_utilisation,
  pred_rf
)

benchmark_table <- tibble(
  Model = c(
    "Linear Regression (OLS)",
    "Elastic Net (GLMNET)",
    "Random Forest (Ranger)"
  ),

  RMSE = c(
    results_ols["RMSE"],
    results_enet["RMSE"],
    results_rf["RMSE"]
  ),

  MAE = c(
    results_ols["MAE"],
    results_enet["MAE"],
    results_rf["MAE"]
  ),

  `R2 Out-of-Sample` = c(
    results_ols["R2_OutSample"],
    results_enet["R2_OutSample"],
    results_rf["R2_OutSample"]
  )
) %>%
  mutate(
    across(
      c(RMSE, MAE, `R2 Out-of-Sample`),
      ~ round(.x, 4)
    )
  )

cat(
  "--- OUT-OF-SAMPLE PREDICTIVE BENCHMARKING RESULTS ---\n"
)

print(benchmark_table)

Table 5.1. Out-of-Sample Predictive Performance

Model Test RMSE Test MAE Out-of-Sample R2 Interpretation
Ordinary Least Squares 0.0513 0.0398 0.611 Provides the conventional linear-regression benchmark for the held-out test subset.
Elastic Net 0.0552 0.0426 0.549 Produces slightly larger test errors and lower out-of-sample R2 than OLS within this split.
Random Forest 0.0371 0.0278 0.796 Produces the lowest test errors and highest out-of-sample R2 among the three fitted models within this split.

Observed and Predicted VO₂ Utilisation in the Test Subset

df_preds <- test_data %>%
  transmute(
    vo2_utilisation,
    activity_group,
    OLS = pred_ols,
    ElasticNet = pred_enet,
    RandomForest = pred_rf
  ) %>%
  pivot_longer(
    cols = c(
      OLS,
      ElasticNet,
      RandomForest
    ),
    names_to = "Model",
    values_to = "Predicted"
  ) %>%
  mutate(
    Model = factor(
      Model,
      levels = c(
        "OLS",
        "ElasticNet",
        "RandomForest"
      ),
      labels = c(
        "OLS",
        "Elastic Net",
        "Random Forest"
      )
    )
  )

p_predictive <- ggplot(
  df_preds,
  aes(
    x = vo2_utilisation,
    y = Predicted,
    colour = Model
  )
) +
  geom_point(
    alpha = 0.6
  ) +
  geom_abline(
    intercept = 0,
    slope = 1,
    linetype = "dashed",
    colour = "black"
  ) +
  facet_wrap(
    ~ Model
  ) +
  coord_equal() +
  theme_minimal() +
labs(
  title = "Out-of-Sample Predictions by Model",
  subtitle = paste0(
    "Observed and predicted VO2 utilisation in the held-out test subset, ",
    "n = ",
    nrow(test_data)
  ),
  x = "Observed VO2 Utilisation",
  y = "Predicted VO2 Utilisation",
  colour = "Model"
)

print(p_predictive)

Figure 5.1. Observed and predicted VO₂ utilisation for the three models in the held-out test subset.

Interpretation of Observed and Predicted VO₂ Utilisation in the Test Subset

The dashed identity line represents exact agreement between observed and predicted VO₂ utilisation. Predictions closer to this line indicate smaller errors for the corresponding test observations.

The Random Forest panel shows closer overall alignment with the identity line than the OLS and Elastic Net panels, consistent with its lower RMSE and MAE and higher out-of-sample R2. The OLS and Elastic Net predictions are more concentrated around the middle of the outcome range, while the lower and upper ends are represented less well.

These patterns describe performance on the current held-out test subset. Since the analysis uses one random row-level split, Figure 5.1 does not establish generalisation to new athletes, future sessions, or repeated resamples.

Key Findings and Analytical Insight

Key Summary Statistics

The following visual summary compares the principal out-of-sample performance metrics across OLS, Elastic Net, and Random Forest regression.

Figure 5.2. Out-of-sample performance metrics for OLS, Elastic Net, and Random Forest regression.

Concluding Remarks

This part of the vignette extended the traditional modelling approaches given in the preceding part through regularised feature selection and out-of-sample predictive benchmarking. Model 04 examined LASSO and Elastic Net regularisation, while Model 05 compared predictive performance on a held-out test subset.

The regularisation analysis, Model 04, showed that LASSO and Elastic Net retained non-zero coefficients across several feature groups. Pace-related predictors, centred session distance, activity-group contrasts, and selected contextual variables remained represented at the cross-validated lambda.1se solutions, while some coefficients were strongly shrunk towards zero. Regularisation provided a simpler representation of the candidate predictor structure without requiring all coefficients to contribute equally.

The out-of-sample benchmarking analysis compared Ordinary Least Squares, Elastic Net, and Random Forest regression using a common random 80/20 train-test split. Within this split, Random Forest produced the lowest test RMSE (0.0371) and MAE (0.0278), together with the highest out-of-sample R2 (0.796). OLS achieved an out-of-sample R2 of 0.611, while Elastic Net achieved 0.549. Random Forest appeared to provide the strongest predictive performance among the three models on the held-out observations used in this analysis.

Both parts of the R1 vignette provided complementary modelling perspectives on prediction within the sportsfeatures framework. Part 1 demonstrated interpretable statistical models for aerobic demand and rested status, whereas Part 2 explored regularised feature selection and comparative predictive performance on held-out observations. The R2 values reported should be interpreted in their respective evaluation contexts: the benchmark multiple-regression output describes in-sample model fit, whereas the Model 05 results describe performance on a held-out test subset.

The R1 vignette provides a foundation for moving from prediction towards explanation. R2 extends this work through hierarchical and mixed-effects modelling of physiological variation.