Model Selection
Model selection is the process of choosing the best final model from these candidates before deploying it in a production or decision-making environment.
This Lesson Will Cover
- 🔍 Model Selection Process
- 📊 Evaluation Dataset Usage
- ⚖️ Model Comparison Methods
- 🧩 Ensemble Model Concepts
- ✅ Final Model Decision Criteria
Generating Candidate Models
Let’s imagine that we’ve used the framework from the previous few lessons to generate a few candidate models for our problem:
model_logreg = LogisticRegression(C=0.5)
model_rf = RandomForestClassifier(n_estimators=100, max_depth=10, min_samples_split=5)
model_gb = GradientBoostingClassifier(n_estimators=150, learning_rate=0.1, max_depth=5)
For each of these, we found the optimal hyperparameters and trained them on the full training + test dataset.
How can we properly compare these models?
The Role of the Evaluation Dataset
Recall from the Data Splitting Strategies lesson, how we split off a portion of our data for evaluation?
- CV set (80%-85%): Used to train and test a model with cross-validation.
- Evaluation set (15-20%): Held out from training and tuning, then used here to compare candidate models.
As promised, it’s time to finally use that data.
Because this portion of the original training dataset was deliberately set aside at the very start and never used during model training or hyperparameter tuning, it gives a held-out comparison of candidates fixed before that comparison. Once its scores influence which candidate we choose, the winner’s score can be optimistically biased. Use fresh data excluded from training, tuning and model selection for a final performance estimate.
Process for Comparison Using the Eval Dataset
- Train and Optimize Candidates: Prepare the optimized candidate models and train them on all the training data that is not part of the evaluation set.
- Evaluate Each Model: For each candidate model, run inference on the evaluation dataset and record the chosen performance metric(s), e.g., accuracy or F1-score.
- Compare Metrics: Rank the candidates based on performance.
- Practical Considerations: Beyond raw performance numbers, consider aspects like model complexity, inference speed, and resource utilization if these are relevant constraints.
Holding out an evaluation dataset helps us avoid the mistake of overfitting to the validation set. When we use cross-validation scores to select models, we might inadvertently optimize for the validation set. The evaluation set is independent of the preceding training and tuning. Using it for model selection makes it part of development, so we must keep a separate final assessment out of that selection process.
Making the Final Decision on the Best Model
After comparing the models on the evaluation dataset, we’ll find a model that ranks best for our top performance metric. However, there are additional considerations to weigh before final selection:
- Stability Across Metrics: Are multiple metrics important for our application? Consider how well the models perform for each.
- Complexity vs. Performance: A marginal improvement in performance might not justify a model that is significantly more complex or computationally expensive.
Real-world constraints turn out to be way more important than they might seem when we’re hyper-focused on the data science component of an ML project.
Consider deployment infrastructure, latency requirements, or interpretability needs. Sometimes a simpler but slightly less accurate model is a better real-world choice.
Introduction to Ensemble Models
Sometimes, instead of picking a single “best” model, we might combine multiple models into an ensemble.
Ensembles can lead to better predictive performance by leveraging the strengths of different models.
We’ve actually already seen many examples of ensembles: random forests and gradient boosted tree ensembles! These are both literally a bunch of decision trees whose individual predictions are combined when making a prediction.
Why Use Ensembles?
- Reduction of Variance: By averaging predictions, ensembles tend to smooth out the noise and variance that might plague a single model’s predictions.
- Leveraging Diversity: Models with different error patterns can complement each other, leading to higher overall accuracy and more robust predictions.
At the model selection stage, we can combine candidate models into an ensemble that averages or votes on their predictions to potentially achieve better overall performance than any single model alone.
Example: Model Selection
Here’s a full example of model selection, following through the example from the start of this lesson and comparing three candidates: a logistic regression model, a random forest and a gradient boosted classifier:
import numpy as np
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier
from sklearn.metrics import accuracy_score, f1_score
RANDOM_STATE=42
# 1. Generate a synthetic classification dataset
X, y = make_classification(n_samples=2000, n_features=20, n_informative=10,
n_redundant=5, n_classes=2, random_state=RANDOM_STATE)
# 2. Split into CV and eval sets (this would have been done earlier, such that eval set has not yet been used)
X_cv, X_eval, y_cv, y_eval = train_test_split(X, y, test_size=0.15, random_state=RANDOM_STATE)
print("Training shape:", X_cv.shape, y_cv.shape)
print("Eval shape:", X_eval.shape, y_eval.shape)
# 3. Define three different models with chosen hyperparameters
# These hyperparameters are hypothetical "good" choices based on prior tuning on the CV data.
model_logreg = LogisticRegression(C=0.5, solver='liblinear', random_state=RANDOM_STATE)
model_rf = RandomForestClassifier(n_estimators=100, max_depth=10, min_samples_split=5, random_state=RANDOM_STATE)
model_gb = GradientBoostingClassifier(n_estimators=150, learning_rate=0.1, max_depth=5, random_state=RANDOM_STATE)
# 4. Train each model on the CV set
model_logreg.fit(X_cv, y_cv)
model_rf.fit(X_cv, y_cv)
model_gb.fit(X_cv, y_cv)
# 5. Evaluate on the eval set
logreg_preds = model_logreg.predict(X_eval)
rf_preds = model_rf.predict(X_eval)
gb_preds = model_gb.predict(X_eval)
# Choose a metric: let's use accuracy and also look at F1 score for more insight
logreg_accuracy = accuracy_score(y_eval, logreg_preds)
rf_accuracy = accuracy_score(y_eval, rf_preds)
gb_accuracy = accuracy_score(y_eval, gb_preds)
logreg_f1 = f1_score(y_eval, logreg_preds)
rf_f1 = f1_score(y_eval, rf_preds)
gb_f1 = f1_score(y_eval, gb_preds)
# Print results
print("Logistic Regression: Accuracy = {:.4f}, F1 = {:.4f}".format(logreg_accuracy, logreg_f1))
print("Random Forest: Accuracy = {:.4f}, F1 = {:.4f}".format(rf_accuracy, rf_f1))
print("Gradient Boosting: Accuracy = {:.4f}, F1 = {:.4f}".format(gb_accuracy, gb_f1))
# 6. Select the best model based on the evaluation set results
# Let's prioritize F1 score (just as an example); we could choose accuracy or a combination of metrics.
models = {
"Logistic Regression": (logreg_accuracy, logreg_f1),
"Random Forest": (rf_accuracy, rf_f1),
"Gradient Boosting": (gb_accuracy, gb_f1)
}
best_model = None
best_f1 = -1
for name, (acc, f1) in models.items():
if f1 > best_f1:
best_f1 = f1
best_model = name
print("\nThe best model based on the eval set is: {} with F1 = {:.4f}".format(best_model, best_f1))
# Outputs:
#
# Training shape: (1700, 20) (1700,)
# Eval shape: (300, 20) (300,)
# Logistic Regression: Accuracy = 0.9067, F1 = 0.9041
# Random Forest: Accuracy = 0.9267, F1 = 0.9262
# Gradient Boosting: Accuracy = 0.9533, F1 = 0.9514
#
# The best model based on the eval set is: Gradient Boosting with F1 = 0.9514
Conclusion
There’s a lot of nuance in doing model selection properly. I hope this lesson conveyed that.
With all this complexity we’re packing in (now a dozen or so lessons into the ML section of the course), let’s be mindful about Occam’s razor.
In the context of ML, we can apply this principle by avoiding complexity that doesn’t lead to significant value for the business (or core problem we’re solving).
Key Takeaways
🎯 Model selection is about choosing the best model after all training and tuning are completed.
📊 The evaluation dataset supports held-out candidate comparison. Once it guides model selection, use fresh data for the selected model’s final assessment.
🏆 Final decision-making considers multiple criteria: performance, complexity, interpretability, and resource constraints.
🔗 Ensemble models can outperform single models by aggregating multiple predictors, thus reducing variance and improving generalization.
Next: Tools and Frameworks
This completes our discussion of model training and evaluation!
Up next we’ll shift our thinking into tools and frameworks for actually doing ML/AI development.
Comments (0)
No comments yet.