Overview
Trains, evaluates, and serializes traditional machine learning models for tabular/structured data. Covers problem type identification, feature engineering checklist, model selection with tradeoffs, hyperparameter tuning (GridSearch, Optuna), cross-validation, evaluation metrics by problem type, full scikit-learn Pipeline, model serialization (joblib / pickle / ONNX), and a complete end-to-end training script template.
When to Use This Skill
- Building a predictive model on tabular data (CSV, database, features from other systems).
- The user has "a dataset with labels" or "predict X from these features".
- You need something interpretable and fast to train/infer (as opposed to deep learning or LLMs).
Prerequisites
- Cleaned tabular dataset (pandas DataFrame) with target variable.
- Python with
scikit-learn, pandas, numpy, joblib. Optionally optuna, xgboost, lightgbm, catboost, pytorch.
- Understanding of the business problem (what "good" looks like).
Steps
Problem framing:
- Classification (binary, multiclass, multilabel)?
- Regression (continuous target)?
- Clustering (no labels, find groups)?
- Time-series specific considerations?
Feature engineering checklist:
- Handle missing values (imputer in pipeline).
- Encode categoricals (OneHot, Target, Ordinal — choose per cardinality).
- Scale numeric features (StandardScaler, RobustScaler).
- Create interactions, polynomial features, date/time features, aggregations.
- Feature selection (mutual info, permutation importance, or model-based).
Model selection (with tradeoffs):
- Baseline: Dummy / Linear / Logistic.
- Tree-based: RandomForest, XGBoost, LightGBM, CatBoost (often win on tabular).
- Linear models for interpretability / speed.
- Neural nets (MLP or more advanced) only when data volume justifies.
Cross-validation & tuning:
- StratifiedKFold for classification.
- TimeSeriesSplit for time-ordered data.
- GridSearchCV or (better) Optuna for hyperparameter search.
- Nested CV when you need unbiased performance estimate.
Evaluation (choose the right metrics):
- Classification: Accuracy, Precision/Recall/F1 (per class + macro), ROC-AUC, PR-AUC, confusion matrix, calibration.
- Regression: MAE, RMSE, R², MAPE (be careful with zeros).
- Clustering: Silhouette, Davies-Bouldin, or downstream task performance.
Full Pipeline:
- Use
sklearn.pipeline.Pipeline + ColumnTransformer so preprocessing is fitted only on train and applied consistently.
- Include the final estimator.
Serialization & serving:
joblib.dump(pipeline, 'model.joblib').
- ONNX for cross-platform / faster inference.
- Simple FastAPI or Flask wrapper for real-time serving.
- Batch scoring script.
Output:
- Complete
train.py that loads data → builds pipeline → tunes → evaluates → saves model + metrics.
- Feature importance plot (for tree models).
- Evaluation report (Markdown or notebook).
- Inference example code.
- Notes on monitoring (data drift, prediction drift).
Examples
A full end-to-end script for a customer churn classification problem (tabular features): preprocessing with ColumnTransformer, LightGBM + Optuna tuning, cross-validation, SHAP importance, model save, and a simple prediction function is included. Similar template for regression and clustering.
Edge Cases & Error Handling
- Class imbalance: Use
class_weight, SMOTE (carefully), or appropriate metrics (not accuracy).
- Data leakage: Pipeline ensures no leakage; be extra careful with time-based features.
- Categorical with high cardinality: Target encoding with smoothing or embeddings.
Verification
- The training script runs end-to-end and produces a saved model.
- Cross-validation scores are reasonable and stable.
- On a held-out test set, performance matches or exceeds the CV estimate.
- The pipeline can be loaded in a fresh environment and used to predict on new data with identical preprocessing.
- Feature importance or SHAP values make business sense.
- Success: You have a validated, serialized model that can be deployed and monitored.
References
1---2name: ml-model-trainer3description: Trains a traditional ML model (classification, regression, clustering) using scikit-learn or PyTorch. Use when building predictive models on tabular or structured data.4license: Apache-2.05---67## Overview89Trains, evaluates, and serializes traditional machine learning models for tabular/structured data. Covers problem type identification, feature engineering checklist, model selection with tradeoffs, hyperparameter tuning (GridSearch, Optuna), cross-validation, evaluation metrics by problem type, full scikit-learn Pipeline, model serialization (joblib / pickle / ONNX), and a complete end-to-end training script template.1011## When to Use This Skill1213- Building a predictive model on tabular data (CSV, database, features from other systems).14- The user has "a dataset with labels" or "predict X from these features".15- You need something interpretable and fast to train/infer (as opposed to deep learning or LLMs).1617## Prerequisites1819- Cleaned tabular dataset (pandas DataFrame) with target variable.20- Python with `scikit-learn`, `pandas`, `numpy`, `joblib`. Optionally `optuna`, `xgboost`, `lightgbm`, `catboost`, `pytorch`.21- Understanding of the business problem (what "good" looks like).2223## Steps24251. **Problem framing**:26 - Classification (binary, multiclass, multilabel)?27 - Regression (continuous target)?28 - Clustering (no labels, find groups)?29 - Time-series specific considerations?30312. **Feature engineering checklist**:32 - Handle missing values (imputer in pipeline).33 - Encode categoricals (OneHot, Target, Ordinal — choose per cardinality).34 - Scale numeric features (StandardScaler, RobustScaler).35 - Create interactions, polynomial features, date/time features, aggregations.36 - Feature selection (mutual info, permutation importance, or model-based).37383. **Model selection** (with tradeoffs):39 - Baseline: Dummy / Linear / Logistic.40 - Tree-based: RandomForest, XGBoost, LightGBM, CatBoost (often win on tabular).41 - Linear models for interpretability / speed.42 - Neural nets (MLP or more advanced) only when data volume justifies.43444. **Cross-validation & tuning**:45 - StratifiedKFold for classification.46 - TimeSeriesSplit for time-ordered data.47 - GridSearchCV or (better) Optuna for hyperparameter search.48 - Nested CV when you need unbiased performance estimate.49505. **Evaluation** (choose the right metrics):51 - Classification: Accuracy, Precision/Recall/F1 (per class + macro), ROC-AUC, PR-AUC, confusion matrix, calibration.52 - Regression: MAE, RMSE, R², MAPE (be careful with zeros).53 - Clustering: Silhouette, Davies-Bouldin, or downstream task performance.54556. **Full Pipeline**:56 - Use `sklearn.pipeline.Pipeline` + `ColumnTransformer` so preprocessing is fitted only on train and applied consistently.57 - Include the final estimator.58597. **Serialization & serving**:60 - `joblib.dump(pipeline, 'model.joblib')`.61 - ONNX for cross-platform / faster inference.62 - Simple FastAPI or Flask wrapper for real-time serving.63 - Batch scoring script.64658. **Output**:66 - Complete `train.py` that loads data → builds pipeline → tunes → evaluates → saves model + metrics.67 - Feature importance plot (for tree models).68 - Evaluation report (Markdown or notebook).69 - Inference example code.70 - Notes on monitoring (data drift, prediction drift).7172## Examples7374A full end-to-end script for a customer churn classification problem (tabular features): preprocessing with ColumnTransformer, LightGBM + Optuna tuning, cross-validation, SHAP importance, model save, and a simple prediction function is included. Similar template for regression and clustering.7576## Edge Cases & Error Handling7778- **Class imbalance**: Use `class_weight`, SMOTE (carefully), or appropriate metrics (not accuracy).79- **Data leakage**: Pipeline ensures no leakage; be extra careful with time-based features.80- **Categorical with high cardinality**: Target encoding with smoothing or embeddings.8182## Verification83841. The training script runs end-to-end and produces a saved model.852. Cross-validation scores are reasonable and stable.863. On a held-out test set, performance matches or exceeds the CV estimate.874. The pipeline can be loaded in a fresh environment and used to predict on new data with identical preprocessing.885. Feature importance or SHAP values make business sense.896. Success: You have a validated, serialized model that can be deployed and monitored.9091## References9293- [scikit-learn User Guide](https://scikit-learn.org/stable/user_guide.html)94- [Hands-On Machine Learning (book)](https://www.oreilly.com/library/view/hands-on-machine-learning/9781492032632/)95- [Optuna](https://optuna.org/)96- [XGBoost / LightGBM / CatBoost docs](https://xgboost.readthedocs.io/)97- [SHAP](https://shap.readthedocs.io/)98- [MLflow or DVC for experiment tracking](https://mlflow.org/)