Training
We’ve already seen a ton of small examples of training models with scikit-learn. It really only takes a few lines!
Here we’ll look at some more end-to-end examples of training scikit-learn pipelines, starting with a basic (and very explicit) workflow, and building up to a more comprehensive pipeline.
This Lesson Will Cover
- 🤖 Training machine learning models with scikit-learn
- 🔍 Using cross-validation for model evaluation
- 🔄 Building scikit-learn pipelines
- 🏆 Implementing different models (Logistic Regression, SVM, XGBoost)
- 🎨 Feature engineering and preprocessing techniques
Training Machine Learning Models
Here’s the general steps that we’ll see in the examples below:
- Select an appropriate algorithm: Based on the problem type (classification, regression, etc.) and data characteristics.
- Split data: Separating our dataset into training and testing sets to evaluate performance on unseen data.
- Do feature engineering and preprocessing: Ensuring that data is transformed to meet the requirements of the chosen algorithm.
- Do model evaluation: Using validation strategies, such as cross-validation, to assess model performance and avoid overfitting.
This process will allow us to generate results on test metrics that can be used to benchmark model performance or do hyperparameter optimization and model selection.
Of course, once we’ve identified the model that we’re going to use, there is no need to withhold the test and eval data during training. That’s the final step (which we don’t see below); training our selected model on the full set of available data.
Logistic Regression with Manual K-Fold Cross-Validation
Here’s a simple logistic regression model where we implement K-Fold cross-validation using the KFold helper class from scikit-learn.
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
from sklearn.model_selection import KFold
import numpy as np
# Generate a binary classification dataset
X, y = make_classification(n_samples=500, n_features=10, n_informative=5, n_redundant=2, random_state=42)
# Initialize K-Fold cross-validation
kf = KFold(n_splits=5, shuffle=True, random_state=42)
accuracies = []
print("Training Logistic Regression with Manual K-Fold Cross-Validation")
for fold, (train_idx, test_idx) in enumerate(kf.split(X), start=1):
# Split data into training and testing sets for this fold
X_train, X_test = X[train_idx], X[test_idx]
y_train, y_test = y[train_idx], y[test_idx]
# Initialize and train the model
model = LogisticRegression()
model.fit(X_train, y_train)
# Make predictions and calculate accuracy
y_pred = model.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
accuracies.append(accuracy)
print(f"Fold {fold} Accuracy: {accuracy:.3f}")
# Final results
print(f"\nCross-Validation Accuracies: {accuracies}")
print(f"Mean Accuracy: {np.mean(accuracies):.3f}")
# Outputs:
# Training Logistic Regression with Manual K-Fold Cross-Validation
# Fold 1 Accuracy: 0.820
# Fold 2 Accuracy: 0.860
# Fold 3 Accuracy: 0.810
# Fold 4 Accuracy: 0.870
# Fold 5 Accuracy: 0.830
#
# Cross-Validation Accuracies: [0.82, 0.86, 0.81, 0.87, 0.83]
# Mean Accuracy: 0.838
Support Vector Machine (SVM) with Feature Scaling and Pipelines
Now, we extend the workflow by introducing feature scaling and using a pipeline.
We also use cross_val_score to simplify the cross-validation process, and switch out the logistic regression model for an SVM.
from sklearn.svm import SVC
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import Pipeline
from sklearn.model_selection import cross_val_score
# Define a pipeline with scaling and SVM
pipeline = Pipeline([
('scaler', StandardScaler()), # Standardize features
('svm', SVC(kernel='linear', C=1.0)) # Linear Support Vector Machine
])
# Perform cross-validation
print("\nTraining Support Vector Machine (SVM) with Feature Scaling")
scores = cross_val_score(pipeline, X, y, cv=5, scoring='accuracy')
# Results
print(f"Cross-Validation Accuracies: {scores}")
print(f"Mean Accuracy: {np.mean(scores):.3f}")
# Outputs:
# Training Support Vector Machine (SVM) with Feature Scaling
# Cross-Validation Accuracies: [0.84 0.87 0.82 0.81 0.85]
# Mean Accuracy: 0.838
XGBoost with Feature Engineering and Cross-Validation
For our final example, we’ll upgrade to a more advanced model: XGBoost, which uses a gradient boosting algorithm. We’ll also include additional feature transformations in the pipeline.
Intermediate pipeline steps transform the data and implement fit and transform. The final XGBClassifier fits the model and supplies prediction methods. It can be the final estimator without implementing transform.
from xgboost import XGBClassifier
from sklearn.preprocessing import PolynomialFeatures
from sklearn.pipeline import Pipeline
from sklearn.model_selection import cross_val_score
# Create a pipeline with polynomial features and XGBoost
pipeline = Pipeline([
('poly', PolynomialFeatures(degree=2, include_bias=False)), # Add polynomial features
('scaler', StandardScaler()), # Standardize features
('xgb', XGBClassifier(use_label_encoder=False, eval_metric='logloss')) # XGBoost Classifier
])
# Perform cross-validation
print("\nTraining XGBoost with Polynomial Features")
scores = cross_val_score(pipeline, X, y, cv=5, scoring='accuracy')
# Results
print(f"Cross-Validation Accuracies: {scores}")
print(f"Mean Accuracy: {np.mean(scores):.3f}")
# Outputs
# Training XGBoost with Polynomial Features
# Cross-Validation Accuracies: [0.9 0.92 0.89 0.88 0.91]
# Mean Accuracy: 0.900
Key Takeaways
Model Training Pipelines:
- Pipelines simplify workflows by chaining preprocessing and modeling steps.
- They reduce the risk of data leakage and improve code readability.
Cross-Validation:
- Essential for evaluating model performance reliably.
- Helps identify overfitting and ensures the model generalizes well.
Flexibility with Scikit-learn:
- Scikit-learn’s pipelines integrate well with feature transformations and advanced models like XGBoost.
Conclusion
This lesson was the first time that we saw pipelines in scikit-learn. They are an important abstraction as our models begin to grow in complexity.
The first time I saw pipelines was in a book called Feature Engineering Bookcamp[1]. The author makes stock trading models as a hobby, so needless to say, the book was quite interesting ;)
Key Takeaways
🏗️ Scikit-learn provides a robust framework for building and training machine learning models.
🔄 Cross-validation is important for training reliable models and preventing overfitting.
⚙️ Pipelines streamline the machine learning workflow by combining preprocessing and modeling steps.
🧩 Feature engineering and preprocessing are essential steps that can significantly impact model performance.
📊 Different models (Logistic Regression, SVM, XGBoost) offer varying levels of complexity and performance.
🎯 Model selection should be based on both the problem requirements and data characteristics.
Next: Model Evaluation
In the next lesson, we’ll dive deeper into model evaluation techniques and metrics to help assess and improve our models’ performance.
Footnotes
I recorded a 30 minute walk-through of my notes about this book over on Patreon. If you’ve bought this course then I’d be happy to share them with you (along with the PDF and MP3). Ping me over on Discord in the #ai-engineering-roadmap channel. ↩︎
Comments (0)
No comments yet.