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)2026-11-30
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.
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.
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.
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.
glmnet)vo2_utilisationlambda.1seHypothesis: 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.
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.
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)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))# 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_utilisationset.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)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)| 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
par(mfrow = c(1, 2))
plot(cv_lasso, main = "LASSO (alpha = 1)")
plot(cv_enet, main = "Elastic Net (alpha = 0.5)")par(mfrow = c(1, 1))Regularised coefficient retention: At lambda.1se, both LASSO and Elastic Net retain non-zero coefficients across physiological, session-level, activity-related, weather, and personal-status predictors. The retained coefficients suggest that predictive information is spread across several feature groups rather than confined to one.
Pace-related predictors: pace_centered and athlete_mean_pace retain negative coefficients in the Elastic Net specification (β = −0.0146 and β = −0.0211, respectively), retaining both within-athlete pace deviation and athlete-level mean pace within the penalised model.
Distance and activity contrasts: distance_centered retains a small positive coefficient (β = +0.00107), while the Running and Walking activity contrasts remain non-zero (β = +0.0539 and β = −0.0127, respectively).
Strongly shrunk coefficients: Age (β = −0.00011) and the Overcast weather contrast (β = −0.00037) remain non-zero but are strongly shrunk towards zero at the selected Elastic Net penalty. These estimates should be interpreted as weak contributors within the penalised coefficient structure rather than as evidence of statistical non-significance.
LASSO and Elastic Net comparison: The two regularisation specifications produce broadly similar retained feature structures, while Elastic Net retains one additional non-zero term at lambda.1se. Their predictive performance is evaluated separately in Model 05 rather than inferred from coefficient retention alone.
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.
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.
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.
vo2_utilisationrangerHypothesis: 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.
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.
# 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)
)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
# 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
)
)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)| 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. |
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)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.
Random Forest performance: Random Forest achieves the lowest test RMSE (0.0371) and MAE (0.0278), together with the highest out-of-sample R2 (0.796), among the three models evaluated on the held-out subset.
OLS benchmark: The OLS model achieves a test RMSE of 0.0513, MAE of 0.0398, and out-of-sample R2 of 0.611. It performs better than Elastic Net within this split but does not match the Random Forest test metrics.
Elastic Net performance: This produces a test RMSE of 0.0552, MAE of 0.0426, and out-of-sample R2 of 0.549. Its regularised coefficient structure does not translate into improved test-set accuracy relative to OLS in this comparison.
Interpretation of the benchmark: Within this held-out subset, Random Forest provides stronger predictive performance than OLS and Elastic Net. In the absence of further modelling, this analysis does not establish which specific non-linearities or interactions account for that improvement.
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.
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.