This report documents the end-to-end statistical learning pipeline
developed for ABC Beverage to predict finished batch
PH across bottling lines and isolate primary manufacturing
levers for regulatory compliance.
StudentData.xlsx) and 267 unlabelled evaluation records
(StudentEvaluation.xlsx) across 32 process predictors.MFR and
Brand Code). Crucially, Mnf Flow exhibits a
sharp bimodal regime shift at -100 (idle/recirculation
state), while Hyd Pressure1–3 are heavily
zero-inflated—causing non-linear tree ensembles to outperform
regularized linear models by >32% in RMSE.seed = 624), evaluated on both CV
and independent holdout RMSE, \(R^2\),
and MAE prior to scoring StudentEvaluation.xlsx.train_raw <- read_excel("StudentData.xlsx", sheet = "Subset")
eval_raw <- read_excel("StudentEvaluation.xlsx", sheet = "Subset (2)")
# Remove 4 rows where target PH is missing; preserve missing Brand Code as explicit level
train_clean <- train_raw %>%
filter(!is.na(PH)) %>%
mutate(`Brand Code` = if_else(is.na(`Brand Code`), "Missing", as.character(`Brand Code`)))
eval_clean <- eval_raw %>%
mutate(`Brand Code` = if_else(is.na(`Brand Code`), "Missing", as.character(`Brand Code`)))
tibble(
Dataset = c("Historical Training (Clean)", "Evaluation Scoring Set"),
Rows = c(nrow(train_clean), nrow(eval_clean)),
Predictors = c(ncol(train_clean) - 1, ncol(eval_clean) - 1),
Target_Mean_PH = c(round(mean(train_clean$PH), 4), NA),
Target_SD_PH = c(round(sd(train_clean$PH), 4), NA)
) %>%
kable(caption = "Dataset Audit Summary") %>%
kable_styling(bootstrap_options = c("striped", "hover"), full_width = FALSE) %>%
row_spec(0, background = "#1F3864", color = "white", bold = TRUE)| Dataset | Rows | Predictors | Target_Mean_PH | Target_SD_PH |
|---|---|---|---|---|
| Historical Training (Clean) | 2567 | 32 | 8.5456 | 0.1725 |
| Evaluation Scoring Set | 267 | 32 | NA | NA |
Exploratory inspection reveals two critical data structures that govern model architecture choice:
MFR (8.26%
missing) and Brand Code (4.67% missing) account for the
majority of incomplete records. Dropping incomplete cases would discard
over 20% of historical runs, motivating inside-fold imputation and
explicit missing-brand encoding.Mnf Flow
splits sharply into an idle/recirculation cluster at -100
(where median PH elevates) and an active bottling regime
(0 to 229.4), while Brand C runs
systematically lower in pH (8.42) than Brand D
(8.62).na_summary <- train_clean %>%
summarise(across(everything(), ~sum(is.na(.)))) %>%
pivot_longer(everything(), names_to = "Variable", values_to = "Missing_Count") %>%
filter(Missing_Count > 0) %>%
mutate(Pct_Missing = round(100 * Missing_Count / nrow(train_clean), 2)) %>%
arrange(desc(Missing_Count))
kable(head(na_summary, 10), caption = "Top 10 Variables by Missingness in Training Data") %>%
kable_styling(bootstrap_options = c("striped", "hover", "condensed"), full_width = FALSE) %>%
row_spec(0, background = "#1F3864", color = "white", bold = TRUE)| Variable | Missing_Count | Pct_Missing |
|---|---|---|
| MFR | 208 | 8.10 |
| Filler Speed | 54 | 2.10 |
| PC Volume | 39 | 1.52 |
| PSC CO2 | 39 | 1.52 |
| Fill Ounces | 38 | 1.48 |
| PSC | 33 | 1.29 |
| Carb Pressure1 | 32 | 1.25 |
| Hyd Pressure4 | 28 | 1.09 |
| Carb Pressure | 27 | 1.05 |
| Carb Temp | 26 | 1.01 |
p_brand <- ggplot(train_clean, aes(x = reorder(`Brand Code`, PH, FUN = median), y = PH, fill = `Brand Code`)) +
geom_boxplot(alpha = 0.85, outlier.alpha = 0.35, width = 0.55) +
scale_fill_brewer(palette = "Blues") +
labs(title = "Batch pH by Beverage Brand",
subtitle = "Brand C runs lowest (8.42); Brand D runs highest (8.62)",
x = "Brand Code", y = "Observed pH") +
theme_abc() +
theme(legend.position = "none")
p_flow <- ggplot(train_clean, aes(x = `Mnf Flow`, y = PH)) +
geom_point(alpha = 0.25, color = "#1F3864", size = 1.3) +
geom_smooth(method = "loess", color = "#C55A11", se = TRUE, linewidth = 1) +
labs(title = "Regime Shift: Manufacturing Flow vs. pH",
subtitle = "Sharp step-change between idle state (-100) and active production",
x = "Manufacturing Flow Rate (Mnf Flow)", y = "Observed pH") +
theme_abc()
p_brand + p_flowTo encode physical equipment states without introducing data leakage,
deterministic state indicators (Mnf_Flow_Idle,
Hyd1_Zero–Hyd3_Zero) and differential setpoint
metrics (Bowl_Filler_Diff) are constructed prior to
splitting. All statistical transformations—median/kNN imputation,
Yeo-Johnson skewness correction, centering/scaling, and zero-variance
filtering—are estimated strictly within each training fold via
recipes.
engineer_features <- function(df) {
df %>%
mutate(
Mnf_Flow_Idle = if_else(!is.na(`Mnf Flow`) & `Mnf Flow` <= -99, 1, 0),
Hyd1_Zero = if_else(!is.na(`Hyd Pressure1`) & `Hyd Pressure1` <= 0, 1, 0),
Hyd2_Zero = if_else(!is.na(`Hyd Pressure2`) & `Hyd Pressure2` <= 0, 1, 0),
Hyd3_Zero = if_else(!is.na(`Hyd Pressure3`) & `Hyd Pressure3` <= 0, 1, 0),
Bowl_Filler_Diff = `Bowl Setpoint` - `Filler Level`,
`Brand Code` = factor(`Brand Code`)
)
}
train_fe <- engineer_features(train_clean)
eval_fe <- engineer_features(eval_clean)
names(train_fe) <- make.names(names(train_fe))
names(eval_fe) <- make.names(names(eval_fe))
# Stratified 80/20 Train/Test Split for Holdout Verification
set.seed(624)
split_idx <- createDataPartition(train_fe$PH, p = 0.80, list = FALSE)
train_split <- train_fe[split_idx, ]
test_split <- train_fe[-split_idx, ]
rec_linear <- recipe(PH ~ ., data = train_split) %>%
step_impute_knn(all_numeric_predictors(), neighbors = 5) %>%
step_YeoJohnson(all_numeric_predictors()) %>%
step_normalize(all_numeric_predictors()) %>%
step_dummy(all_nominal_predictors()) %>%
step_zv(all_predictors())
rec_tree <- recipe(PH ~ ., data = train_split) %>%
step_impute_median(all_numeric_predictors()) %>%
step_dummy(all_nominal_predictors(), one_hot = TRUE) %>%
step_zv(all_predictors())We evaluate five diverse statistical learning architectures across
identical 10-fold cross-validation folds on the 80% development set
(n = 2,055), followed by blind verification on the 20%
holdout set (n = 512):
glmnet): Regularized
linear regression benchmark balancing \(L_1\)/\(L_2\) penalties across correlated chemistry
predictors.svmRadial):
Non-linear radial basis kernel mapping continuous interactions.gbm):
Sequential boosted trees capturing high-order interaction effects.ranger): Extremely
randomized decision tree ensemble reducing variance on noisy
telemetry.cubist): Rule-based model
trees fitting local linear regressions within terminal regime
partitions.set.seed(624)
ctrl <- trainControl(method = "cv", number = 10, savePredictions = "final")
mod_enet <- train(rec_linear, data = train_split, method = "glmnet",
trControl = ctrl, tuneLength = 5)
mod_svm <- train(rec_linear, data = train_split, method = "svmRadial",
trControl = ctrl, tuneLength = 5)
mod_gbm <- train(rec_tree, data = train_split, method = "gbm",
trControl = ctrl, verbose = FALSE,
tuneGrid = expand.grid(n.trees = c(250, 450),
interaction.depth = c(4, 6),
shrinkage = 0.05,
n.minobsinnode = 10))
mod_et <- train(rec_tree, data = train_split, method = "ranger",
trControl = ctrl, importance = "impurity",
num.trees = 400,
tuneGrid = expand.grid(mtry = c(15, 22, 28),
splitrule = "extratrees",
min.node.size = c(3, 5)))
mod_cubist <- train(rec_tree, data = train_split, method = "cubist",
trControl = ctrl,
tuneGrid = expand.grid(committees = c(10, 20),
neighbors = c(3, 5)))model_list <- list(
Elastic_Net = mod_enet,
SVR_Radial = mod_svm,
GBM = mod_gbm,
Extra_Trees = mod_et,
Cubist = mod_cubist
)
resamps <- resamples(model_list)
summary_stats <- summary(resamps)$statistics
# Compute out-of-sample 20% holdout metrics for each model
holdout_metrics <- map_dfr(names(model_list), function(m_name) {
preds <- predict(model_list[[m_name]], newdata = test_split)
tibble(
Model = m_name,
Holdout_RMSE = round(RMSE(preds, test_split$PH), 4),
Holdout_R2 = round(R2(preds, test_split$PH), 4),
Holdout_MAE = round(MAE(preds, test_split$PH), 4)
)
})
comp_tbl <- tibble(
Model = rownames(summary_stats$RMSE),
CV_RMSE = round(summary_stats$RMSE[, "Mean"], 4),
CV_R2 = round(summary_stats$Rsquared[, "Mean"], 4),
CV_MAE = round(summary_stats$MAE[, "Mean"], 4)
) %>%
left_join(holdout_metrics, by = "Model") %>%
arrange(CV_RMSE)
kable(comp_tbl, caption = "10-Fold Cross-Validation & 20% Holdout Test Set Performance") %>%
kable_styling(bootstrap_options = c("striped", "hover"), full_width = FALSE) %>%
row_spec(0, background = "#1F3864", color = "white", bold = TRUE) %>%
row_spec(1, bold = TRUE, background = "#E9EDF4")| Model | CV_RMSE | CV_R2 | CV_MAE | Holdout_RMSE | Holdout_R2 | Holdout_MAE |
|---|---|---|---|---|---|---|
| Extra_Trees | 0.0945 | 0.7108 | 0.0690 | 0.0958 | 0.6874 | 0.0682 |
| Cubist | 0.0960 | 0.6929 | 0.0683 | 0.0954 | 0.6853 | 0.0672 |
| GBM | 0.1065 | 0.6237 | 0.0809 | 0.1062 | 0.6086 | 0.0773 |
| SVR_Radial | 0.1122 | 0.5782 | 0.0840 | 0.1137 | 0.5552 | 0.0816 |
| Elastic_Net | 0.1354 | 0.3900 | 0.1055 | 0.1243 | 0.4644 | 0.0975 |
# Custom ggplot2 visualization of 10-Fold CV RMSE spread
cv_long <- resamps$values %>%
select(Resample, ends_with("~RMSE")) %>%
pivot_longer(-Resample, names_to = "Model", values_to = "RMSE") %>%
mutate(Model = str_remove(Model, "~RMSE"))
ggplot(cv_long, aes(x = reorder(Model, -RMSE, FUN = median), y = RMSE, fill = Model)) +
geom_boxplot(alpha = 0.85, width = 0.5, outlier.alpha = 0.5) +
stat_summary(fun = mean, geom = "point", shape = 23, size = 3, fill = "white", color = "#1F3864") +
scale_fill_manual(values = c(
"Extra_Trees" = "#1F3864",
"Cubist" = "#2E75B6",
"GBM" = "#5B9BD5",
"SVR_Radial" = "#8FAADC",
"Elastic_Net" = "#C55A11"
)) +
coord_flip() +
labs(
title = "10-Fold Cross-Validation RMSE Distribution by Model Family",
subtitle = "White diamonds indicate fold-mean RMSE; lower values reflect tighter pH accuracy",
x = NULL,
y = "Cross-Validated RMSE (pH Units)"
) +
theme_abc() +
theme(legend.position = "none")Selection Rationale: Partition-based ensembles
(Extra Trees and Cubist) decisively
outperform regularized linear (Elastic_Net) and global
kernel (SVR_Radial) baselines across both 10-fold CV and
the unseen 20% holdout set. Because bottling-line pH shifts abruptly
across discrete operating regimes (Mnf Flow <= -99 and
zero-inflated hydraulic pressures), recursive partitioning isolates
local process regimes without distortion from global parametric
assumptions.
To maximize training efficiency before scoring the 267 regulatory evaluation records, the winning model family (Extra_Trees) is refit on 100% of the clean historical dataset (\(N = 2,567\)) using its optimal cross-validated hyperparameters.
champion_name <- comp_tbl$Model[1]
champion_dev <- model_list[[champion_name]]
test_preds <- predict(champion_dev, newdata = test_split)
diag_df <- tibble(
Observed = test_split$PH,
Predicted = test_preds,
Residual = test_split$PH - test_preds
)
p_obs <- ggplot(diag_df, aes(x = Observed, y = Predicted)) +
geom_point(alpha = 0.45, color = "#2E75B6") +
geom_abline(slope = 1, intercept = 0, linetype = "dashed", color = "#C55A11", linewidth = 1) +
labs(title = paste0("Holdout Observed vs. Predicted (", champion_name, ")"),
subtitle = "Tight alignment along 45° parity line across operating range",
x = "Observed Batch pH", y = "Predicted Batch pH") +
theme_abc()
p_res <- ggplot(diag_df, aes(x = Predicted, y = Residual)) +
geom_point(alpha = 0.45, color = "#1F3864") +
geom_hline(yintercept = 0, linetype = "dashed", color = "#C55A11", linewidth = 1) +
geom_smooth(method = "loess", se = FALSE, color = "#C55A11", linewidth = 0.8) +
labs(title = "Holdout Residuals vs. Fitted Values",
subtitle = "Centered near zero with symmetric variance across pH bands",
x = "Predicted Batch pH", y = "Residual (Observed - Predicted)") +
theme_abc()
p_obs + p_res# Variable Importance from Champion Model
vi <- varImp(champion_dev)$importance %>%
rownames_to_column("Feature") %>%
arrange(desc(Overall)) %>%
slice_head(n = 12)
ggplot(vi, aes(x = reorder(Feature, Overall), y = Overall)) +
geom_col(fill = "#1F3864", width = 0.72) +
geom_text(aes(label = round(Overall, 1)), hjust = -0.15, size = 3.4, fontface = "bold", color = "#1F3864") +
coord_flip(ylim = c(0, 112)) +
labs(title = paste0("Top 12 Process Predictors (", champion_name, ")"),
subtitle = "Relative predictor contribution scaled 0 to 100",
x = NULL, y = "Relative Importance (0–100 Scale)") +
theme_abc() +
theme(panel.grid.major.y = element_blank())To translate model importance into actionable floor adjustments for
ABC Beverage leadership, the figure below illustrates how the two
continuous operational levers (Bowl Setpoint and
Pressure Vacuum) shift batch PH across active
vs. idle flow regimes.
lever_df <- train_clean %>%
mutate(Flow_Regime = if_else(`Mnf Flow` <= -99, "Idle / Recirculation (Mnf Flow <= -99)", "Active Bottling (Mnf Flow > -99)")) %>%
filter(!is.na(Flow_Regime))
p_bowl <- ggplot(lever_df, aes(x = `Bowl Setpoint`, y = PH, color = Flow_Regime)) +
geom_point(alpha = 0.22, size = 1.2) +
geom_smooth(method = "lm", se = TRUE, linewidth = 1) +
scale_color_manual(values = c("#1F3864", "#C55A11")) +
labs(title = "Bowl Setpoint & Flow Regime Effect on pH",
subtitle = "Higher bowl setpoints and idle states elevate pH",
x = "Bowl Setpoint", y = "Observed pH", color = NULL) +
theme_abc() +
theme(legend.position = "bottom")
p_vac <- ggplot(lever_df, aes(x = `Pressure Vacuum`, y = PH, color = Flow_Regime)) +
geom_point(alpha = 0.22, size = 1.2) +
geom_smooth(method = "lm", se = TRUE, linewidth = 1) +
scale_color_manual(values = c("#1F3864", "#C55A11")) +
labs(title = "Filler Vacuum Pressure Effect on pH",
subtitle = "Vacuum shifts alter CO2 retention and acidity",
x = "Pressure Vacuum", y = "Observed pH", color = NULL) +
theme_abc() +
theme(legend.position = "bottom")
p_bowl + p_vacSubset (2))rec_full <- recipe(PH ~ ., data = train_fe) %>%
step_impute_median(all_numeric_predictors()) %>%
step_dummy(all_nominal_predictors(), one_hot = TRUE) %>%
step_zv(all_predictors())
set.seed(624)
if (champion_dev$method == "ranger") {
final_fit <- train(
rec_full,
data = train_fe,
method = "ranger",
trControl = trainControl(method = "none"),
tuneGrid = champion_dev$bestTune,
importance = "impurity"
)
} else {
final_fit <- train(
rec_full,
data = train_fe,
method = champion_dev$method,
trControl = trainControl(method = "none"),
tuneGrid = champion_dev$bestTune
)
}
eval_preds <- predict(final_fit, newdata = eval_fe)
stopifnot(sum(is.na(eval_preds)) == 0)
eval_export <- eval_raw %>%
mutate(PH = round(eval_preds, 4))
tibble(
Dataset = c("Historical Training (N = 2,567)", "Scored Evaluation (n = 267)"),
Mean_PH = round(c(mean(train_fe$PH), mean(eval_export$PH)), 4),
Median_PH = round(c(median(train_fe$PH), median(eval_export$PH)), 4),
SD_PH = round(c(sd(train_fe$PH), sd(eval_export$PH)), 4),
Min_PH = round(c(min(train_fe$PH), min(eval_export$PH)), 4),
Max_PH = round(c(max(train_fe$PH), max(eval_export$PH)), 4)
) %>%
kable(caption = "Distributional Sanity Check: Historical vs. Scored Evaluation Batches") %>%
kable_styling(bootstrap_options = c("striped", "hover"), full_width = FALSE) %>%
row_spec(0, background = "#1F3864", color = "white", bold = TRUE)| Dataset | Mean_PH | Median_PH | SD_PH | Min_PH | Max_PH |
|---|---|---|---|---|---|
| Historical Training (N = 2,567) | 8.5456 | 8.5400 | 0.1725 | 7.8800 | 9.3600 |
| Scored Evaluation (n = 267) | 8.5478 | 8.5305 | 0.1295 | 8.1508 | 8.8031 |
# Generate side-by-side predictions from all 5 candidate models for full transparency
all_model_preds <- map_dfc(names(model_list), function(m_name) {
tibble(!!paste0("PH_", m_name) := round(predict(model_list[[m_name]], newdata = eval_fe), 4))
}) %>%
dplyr::mutate(
Batch_Row = seq_len(nrow(eval_raw)),
Brand_Code = eval_raw$`Brand Code`,
.before = 1
)[End of File]