{"data":{"slug":"discovered-4c658b1bcea2e2fc8726bd37f3b1f5b1cac3ffba11e88fb2","title":"Machine Learning","summary":"Build, train, evaluate, debug, or deploy machine learning models using tabular data with scikit-learn, XGBoost, LightGBM, or CatBoost, or deep learning with PyTorch. Includes feature engineering, train\/validation\/test splitting, cross-validation, metric selection, hyperparameter tuning, overfitting prevention, data leakage detection, probability calibration, model serving, and drift monitoring.","url":"https:\/\/skillshunter.net\/skills\/discovered-4c658b1bcea2e2fc8726bd37f3b1f5b1cac3ffba11e88fb2","json_url":"https:\/\/skillshunter.net\/api\/public\/v1\/skills\/discovered-4c658b1bcea2e2fc8726bd37f3b1f5b1cac3ffba11e88fb2","markdown_url":"https:\/\/skillshunter.net\/skills\/discovered-4c658b1bcea2e2fc8726bd37f3b1f5b1cac3ffba11e88fb2.md","download_url":"https:\/\/skillshunter.net\/skills\/discovered-4c658b1bcea2e2fc8726bd37f3b1f5b1cac3ffba11e88fb2\/download","category":{"slug":"software-development","name":"Software & Development"},"editor_note":"Before starting, ensure the data is split before any statistic is computed. Preprocessing steps like scaling, imputation, and encoding must be fitted on training folds only and included in a pipeline. Avoid using features derived from the label or recorded after the prediction moment. Target encoding must be computed out of fold. Entities and time periods must not straddle the split. Hyperparameters and thresholds should be chosen on validation data, not test data.","instructions":"---\nname: machine-learning\ndescription: Use when building, training, evaluating, debugging or deploying a machine learning model - tabular models with scikit-learn, XGBoost, LightGBM or CatBoost, deep learning with PyTorch, feature engineering, train\/validation\/test splitting, cross-validation, choosing metrics, class imbalance, hyperparameter tuning, overfitting, data leakage, probability calibration, model serving, drift monitoring. Triggers - \"train a model to predict\", \"which model should I use\", \"validation score is great but production is bad\", \"is this data leakage\", \"loss is not decreasing\", \"tune hyperparameters\", \"imbalanced classes\", \"deploy this model\", \"the model got worse over time\".\n---\n\n# Machine Learning\n\nMost machine learning failures are evaluation failures. The model trains, the\nnumber looks good, and the number was measuring the wrong thing: information\nleaked across the split, the metric did not match the decision, or the test set\nwas used to choose the model. So the evaluation is designed before the model.\n\n**Fix the split, the metric and a baseline before any modelling. Fit every\ndata-dependent step inside the training fold. Touch the test set once.**\n\n## Workflow\n\n1. **State the decision.** What action follows a prediction, and what does each\n   kind of error cost? That fixes the metric and the operating threshold.\n2. **Split first**, before looking at distributions or engineering features. The\n   split must mimic how the model will meet new data (table below).\n3. **Build a baseline**: predict the mean or majority class, then a linear model\n   or a default gradient-boosted model. Anything more complex has to beat it.\n4. **Put preprocessing in a pipeline** so scalers, imputers, encoders and feature\n   selection are fitted on training folds only.\n5. **Iterate on validation data**: features first, then model family, then\n   hyperparameters. Read the errors, not only the score.\n6. **Evaluate once on the test set**, with a confidence interval.\n7. **Ship with monitoring**: input drift, prediction drift, and the real outcome\n   when it arrives.\n\n## Choosing the split\n\n| Data | Split | Why |\n|---|---|---|\n| Independent rows | stratified K-fold | keeps class balance in every fold |\n| Several rows per user, patient, device or document | group K-fold by that entity | the same entity on both sides lets the model memorise it |\n| Time-ordered, or predicting the future | time-based: train on the past, test on what follows, with a gap as long as the label horizon | a random split trains on the future |\n| Both grouped and time-ordered | split by time, then check no group straddles the boundary | either leak alone is enough to fool you |\n| Very small data | repeated or nested cross-validation | one split is mostly noise |\n\nIf a random split and a time or group split give very different scores, the lower\none is the truth.\n\n## Choosing the metric\n\n| Task | Use | Avoid |\n|---|---|---|\n| Balanced classification | accuracy plus log loss | accuracy alone |\n| Rare positive class | PR-AUC, recall at a fixed precision | accuracy, and ROC-AUC alone (it looks fine at 1% prevalence) |\n| Probabilities drive the decision | log loss or Brier score, with a calibration plot | metrics that only rank |\n| Ranking or retrieval | NDCG, MAP, recall@k | accuracy |\n| Regression | MAE when all errors cost alike, RMSE when large ones cost more | R-squared alone; MAPE when targets are near zero |\n| Forecasting | error against a naive forecast (MASE), by horizon | a single number pooled over horizons |\n\nReport the metric with an interval (bootstrap the test set, or use the spread\nacross folds). A difference smaller than the interval is not an improvement.\n\n## Choosing the model\n\n| Data | Start with | Then |\n|---|---|---|\n| Tabular, any size | gradient-boosted trees (LightGBM, XGBoost, CatBoost) | linear or logistic regression as the interpretable reference |\n| Tabular, small and noisy | regularised linear model | boosted trees with strong regularisation |\n| Text | a pretrained transformer, fine-tuned or used for embeddings | TF-IDF plus a linear model as the baseline to beat |\n| Images, audio | a pretrained network, fine-tuned | train from scratch only with very large data |\n| Time series | seasonal-naive, then boosted trees on lag features | sequence models, when there are many related series |\n\nOn tabular data, deep networks rarely beat well-tuned boosted trees. Reach for\nthem when the input is raw signal, text or images.\n\n## Leakage checklist\n\n- [ ] Split made before any statistic was computed on the data\n- [ ] Scaling, imputation, encoding, feature selection and resampling happen\n      inside the pipeline, fitted on training folds only\n- [ ] No feature is recorded after the moment of prediction, or derived from the label\n- [ ] Target encoding is computed out of fold\n- [ ] Duplicates and near-duplicates do not straddle the split\n- [ ] Entities and time periods do not straddle the split\n- [ ] Hyperparameters and thresholds were chosen on validation data, never on test\n- [ ] One feature with implausibly high importance has been explained\n\nA score that looks too good is the main symptom. Investigate before celebrating.\n\n## Class imbalance\n\nKeep the natural class ratio in validation and test data. Then, in order: choose\na metric that reflects the rare class, set class weights, and tune the decision\nthreshold on validation data. Resampling such as SMOTE goes inside the pipeline\nso it touches training folds only, and it distorts predicted probabilities, so\nrecalibrate afterwards. Often class weights plus a tuned threshold is enough.\n\n## Tuning\n\nTune after the features and the split are settled; a better feature is usually\nworth more than any hyperparameter. Use random search or Optuna (TPE) rather\nthan a grid, with early stopping for boosted trees and networks. For boosted\ntrees the parameters that matter are learning rate with number of trees, tree\nsize (`num_leaves` or `max_depth`), minimum samples per leaf, and row and column\nsubsampling. Every configuration tried is a look at the validation set; with\nmany trials, confirm the winner on fresh folds.\n\n## Deep learning habits\n\n1. Overfit a single batch first. If the loss does not reach near zero, the bug is\n   in the model, the loss or the data pipeline, and more training will not fix it.\n2. Start from a known-good recipe: AdamW, learning-rate warmup then cosine decay,\n   gradient clipping, mixed precision on GPU.\n3. Change one thing at a time and log every run with its config and seed.\n4. Watch training and validation curves together; checkpoint on the best\n   validation metric and stop early.\n5. `model.train()` and `model.eval()` matter: dropout and batch norm behave\n   differently, and forgetting `eval()` silently degrades validation scores.\n\n## Reading symptoms\n\n| Symptom | Likely cause | Try |\n|---|---|---|\n| Train good, validation poor | overfitting | more data, regularisation, simpler model, early stopping |\n| Both poor | underfitting, weak features or a bug | check the pipeline end to end, add features, increase capacity |\n| Validation good, production poor | leakage, or production data differs from training data | audit the split; compare feature distributions train versus live |\n| Loss is NaN | learning rate too high, bad input values, log of zero | lower the rate, check inputs, clip gradients, add epsilon |\n| Loss flat from the start | learning rate too low or too high, labels misaligned, frozen parameters | overfit one batch; verify inputs and labels pair up |\n| Validation better than training | dropout or augmentation active only in training, or leakage in the validation set | usually benign; rule out leakage |\n| Good metric, bad decisions | metric does not match the cost of errors | return to step 1 |\n| Slow decay after deployment | drift in inputs or in the input-outcome relationship | monitor, retrain on a schedule or on a trigger |\n\n## References\n\n| File | When |\n|---|---|\n| `references\/tabular-recipes.md` | leak-free scikit-learn pipeline, group and time splits, LightGBM with early stopping, Optuna, calibration and threshold choice, bootstrap intervals |\n| `references\/pytorch-training.md` | training loop with mixed precision, clipping, scheduler, early stopping and checkpoints; reproducibility; debugging order |\n| `references\/production.md` | packaging and serving, training-serving skew, drift monitoring, retraining triggers, model card |\n\nFor financial time series, the `quantitative-finance` and `hedge-fund-blueprint`\nskills add purged splits, cost-aware evaluation and multiple-testing corrections.\n","use_cases":["Train a model to predict outcomes based on tabular data","Choose the right model for a classification or regression task","Debug a model that performs well on validation data but poorly in production","Detect and prevent data leakage in a machine learning pipeline","Tune hyperparameters for improved model performance","Address class imbalance in a classification task"],"limitations":[],"compatibility":[],"setup_tip":null,"sample_input":null,"sample_output":null,"source_url":"https:\/\/github.com\/Ricko12vPL\/claude-code-skills\/blob\/4bc1ba2d54dcd4ac48cef1689efd4ccb48de9c75\/skills\/machine-learning\/SKILL.md","source_commit":"4bc1ba2d54dcd4ac48cef1689efd4ccb48de9c75","license":null,"version":null,"listing_approved_at":"2026-11-29","created_at":"2026-11-28T18:52:27.000000Z","updated_at":"2026-11-29T10:53:39.000000Z","seo_title":"Machine Learning Model Development and Evaluation","seo_description":"Build, train, and evaluate machine learning models with best practices for splitting data, avoiding leakage, selecting metrics, and deploying models. Includes guidance on","seo_keywords":["machine learning","model training","data leakage","cross-validation","hyperparameter tuning","feature engineering","model deployment","probability calibration"]}}