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.05compatibility: Claude Code, Codex, Gemini CLI6metadata:7 author: ai-skills8 version: "1.0"9 category: ai-ml10 tags: machine-learning, scikit-learn, pytorch, classification, regression, clustering, pipeline11---1213## Overview1415Trains, 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.1617## When to Use This Skill1819- Building a predictive model on tabular data (CSV, database, features from other systems).20- The user has "a dataset with labels" or "predict X from these features".21- You need something interpretable and fast to train/infer (as opposed to deep learning or LLMs).2223## Prerequisites2425- Cleaned tabular dataset (pandas DataFrame) with target variable.26- Python with `scikit-learn`, `pandas`, `numpy`, `joblib`. Optionally `optuna`, `xgboost`, `lightgbm`, `catboost`, `pytorch`.27- Understanding of the business problem (what "good" looks like).2829## Steps30311. **Problem framing**:32 - Classification (binary, multiclass, multilabel)?33 - Regression (continuous target)?34 - Clustering (no labels, find groups)?35 - Time-series specific considerations?36372. **Feature engineering checklist**:38 - Handle missing values (imputer in pipeline).39 - Encode categoricals (OneHot, Target, Ordinal — choose per cardinality).40 - Scale numeric features (StandardScaler, RobustScaler).41 - Create interactions, polynomial features, date/time features, aggregations.42 - Feature selection (mutual info, permutation importance, or model-based).43443. **Model selection** (with tradeoffs):45 - Baseline: Dummy / Linear / Logistic.46 - Tree-based: RandomForest, XGBoost, LightGBM, CatBoost (often win on tabular).47 - Linear models for interpretability / speed.48 - Neural nets (MLP or more advanced) only when data volume justifies.49504. **Cross-validation & tuning**:51 - StratifiedKFold for classification.52 - TimeSeriesSplit for time-ordered data.53 - GridSearchCV or (better) Optuna for hyperparameter search.54 - Nested CV when you need unbiased performance estimate.55565. **Evaluation** (choose the right metrics):57 - Classification: Accuracy, Precision/Recall/F1 (per class + macro), ROC-AUC, PR-AUC, confusion matrix, calibration.58 - Regression: MAE, RMSE, R², MAPE (be careful with zeros).59 - Clustering: Silhouette, Davies-Bouldin, or downstream task performance.60616. **Full Pipeline**:62 - Use `sklearn.pipeline.Pipeline` + `ColumnTransformer` so preprocessing is fitted only on train and applied consistently.63 - Include the final estimator.64657. **Serialization & serving**:66 - `joblib.dump(pipeline, 'model.joblib')`.67 - ONNX for cross-platform / faster inference.68 - Simple FastAPI or Flask wrapper for real-time serving.69 - Batch scoring script.70718. **Output**:72 - Complete `train.py` that loads data → builds pipeline → tunes → evaluates → saves model + metrics.73 - Feature importance plot (for tree models).74 - Evaluation report (Markdown or notebook).75 - Inference example code.76 - Notes on monitoring (data drift, prediction drift).7778## Examples7980A 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.8182## Edge Cases & Error Handling8384- **Class imbalance**: Use `class_weight`, SMOTE (carefully), or appropriate metrics (not accuracy).85- **Data leakage**: Pipeline ensures no leakage; be extra careful with time-based features.86- **Categorical with high cardinality**: Target encoding with smoothing or embeddings.8788## Verification89901. The training script runs end-to-end and produces a saved model.912. Cross-validation scores are reasonable and stable.923. On a held-out test set, performance matches or exceeds the CV estimate.934. The pipeline can be loaded in a fresh environment and used to predict on new data with identical preprocessing.945. Feature importance or SHAP values make business sense.956. Success: You have a validated, serialized model that can be deployed and monitored.9697## References9899- [scikit-learn User Guide](https://scikit-learn.org/stable/user_guide.html)100- [Hands-On Machine Learning (book)](https://www.oreilly.com/library/view/hands-on-machine-learning/9781492032632/)101- [Optuna](https://optuna.org/)102- [XGBoost / LightGBM / CatBoost docs](https://xgboost.readthedocs.io/)103- [SHAP](https://shap.readthedocs.io/)104- [MLflow or DVC for experiment tracking](https://mlflow.org/)