"Should we label more data?" and "should we use a bigger model?" are both answered by the same plot: training
and validation score as the training set grows. The gap between the curves measures variance, the
slope of the validation curve says whether rows still help, and the training curve is the ceiling the
validation curve converges towards. scripts/gen_learning_curve.py writes a correct scikit-learn
learning_curve script; scripts/diagnose_curve.py turns its CSV into a verdict, a data-size extrapolation
and the right next step.
Trigger Conditions
Activate this skill when the user:
- Asks whether more data, more labels or a longer history will improve the model, or how much data is needed
- Sees a large train/validation gap, or training and validation scores that are both mediocre
- Shares a learning-curve plot or
learning_curveoutput and asks what it means - Must choose between collecting data, regularising, adding capacity or engineering features
Curves over a hyperparameter or over boosting iterations (validation curves, training history): overfitting-underfitting-diagnoser. Splitter choice: cross-validation-strategy-designer.
Workflow
1. GENERATE -> python scripts/gen_learning_curve.py data.csv --target y --model hgb --scoring roc_auc -o lc.py
2. RUN -> python lc.py (learning_curve.csv + learning_curve.png)
3. DIAGNOSE -> python scripts/diagnose_curve.py learning_curve.csv --target 0.90
4. ACT -> the verdict table below; re-run the curve after the change
5. REPORT -> plot, verdict, extrapolation with its caveats, chosen actionReading the Curve
| Pattern | Verdict | Action |
|---|---|---|
| Large gap, validation still rising | HIGH VARIANCE - DATA-LIMITED | more data pays; regularise meanwhile |
| Large gap, validation flat | HIGH VARIANCE | regularise, simplify, remove noisy features; more data of the same kind adds little |
| Gap closed, score too low | HIGH BIAS | more capacity, better features, less regularisation; more data will not help |
| Gap closed, score meets the target | CONVERGED | stop; spend effort elsewhere |
| Validation drops as size grows | data problem | subsets not random (sorted data, shuffle=False), drift, or label noise in later rows |
| Validation above training | regulariser artefact | heavy dropout/augmentation, tiny folds, or a bug (swapped columns) |
| Training score 1.0 everywhere | memorisation | the gap is real, but the training curve cannot show the ceiling |
The key fact: as rows are added the training score falls and the validation score rises towards the same asymptote. Once the gap has closed, the training score is the best the model can reach, so the only way up is a better model or better features. Worked readings and shapes: reading-learning-curves.md.
Building a Trustworthy Curve
- Geometric sizes (e.g. 10%, 16%, 25%, 40%, 63%, 100% of the training fold): the curve bends at small n.
- Shuffle with a seed:
learning_curvetakes the first rows of each training fold; on sorted data the small sizes are a biased slice. Time-ordered data is the exception: keep the order and useTimeSeriesSplit. - Same splitter as model selection: grouped data needs
GroupKFold, otherwise the curve is optimistic. - Enough folds: compare the standard error of the validation mean with the gain from doubling; if the
noise is larger, use more folds or
RepeatedStratifiedKFold. - Fixed model settings: early stopping or tuning at each size changes two things at once. Keep the model fixed, or tune at each size deliberately and say so.
- Fit time comes for free (
return_times=True): it shows what doubling the data costs.
Extrapolating "How Much Data?"
diagnose_curve.py fits val(n) = a - b * n^-c to the largest four sizes, with the asymptote a capped at
the final training score, and reports predictions at 2x, 4x and 10x plus the rows needed for --target.
| Rule | Why |
|---|---|
| Trust 2x, treat 4x as a guess, 10x as a direction | power laws flatten in ways four points cannot show |
| Cap the asymptote at the training score | validation cannot overtake training on the same distribution |
| Target above the cap means "not with this model" | more data alone cannot get there |
| New data must match the old | extrapolation assumes the same distribution and label quality |
| Check R^2 >= 0.9 of the fit | otherwise the gain from doubling falls back to the measured slope, capped by the headroom |
Method, cost-benefit of labelling and alternatives (active learning, augmentation, transfer): data-size-extrapolation.md. Concrete fixes per verdict and model family: acting-on-the-diagnosis.md.
Output Format
When diagnosing a learning curve, deliver:
- Setup - model, metric, splitter, sizes, folds.
- Curve table and plot - mean train/validation, fold std and gap at each size.
- Verdict - variance, data-limited, bias or converged, with the numbers that decide it.
- Extrapolation - predicted score at 2x/4x data, rows for the target, ceiling, and the fit quality.
- Action - the next experiment, and what curve would confirm it worked.
Scripts
python scripts/gen_learning_curve.py data.csv --target churned --model hgb --scoring roc_auc -o lc.py
python scripts/gen_learning_curve.py data.csv --target price --model rf --scoring neg_root_mean_squared_error
python scripts/gen_learning_curve.py data.csv --target churned --group-col customer_id --sizes 8 --min-frac 0.05Models: logreg (Ridge for regression), rf, hgb, lgbm. Detects classification vs regression (override with
--task), switches binary scorers to their multiclass forms, drops --group-col/--time-col from the features,
and keeps time order (shuffle=False, TimeSeriesSplit) with --time-col. The generated script writes
learning_curve.csv (train_size, fold, train_score, val_score, fit_time) in scorer sign convention and
learning_curve.png. Exit codes: 0 written, 2 usage error.
python scripts/diagnose_curve.py learning_curve.csv
python scripts/diagnose_curve.py lc.csv --target 0.95
python scripts/diagnose_curve.py lc.csv --lower-better --gap-threshold 500 --jsonReads any CSV with size, train and validation columns (--size-col, --train-col, --val-col), one row per
fold or per size. The gap threshold defaults to 2% of max(1, |score|). Exit codes: 0 diagnosed, 2 usage or
read error.
Additional Resources
| File | Content |
|---|---|
| reading-learning-curves.md | the bias-variance reading, canonical shapes, metric conventions, common misreadings |
| data-size-extrapolation.md | power-law fitting, how far to trust it, labelling cost-benefit, alternatives to more data |
| acting-on-the-diagnosis.md | fixes for variance and bias per model family, and the curve that confirms each fix |
anomaly-detection-model-builder
Build and evaluate anomaly detection for tabular, sensor and transaction data with few or no labels: define the anomaly type (point, contextual, collective), choose detectors (robust z-score/MAD and IQR rules, Mahalanobis with robust covariance, k-NN distance, LOF, Isolation Forest, one-class SVM, PCA reconstruction / autoencoders, forecasting residuals for time series), combine them by rank, explain each alert by its deviating features, set thresholds from an alert budget or the score distribution, and evaluate with precision@k, PR-AUC and recall on known incidents, or detector agreement when no labels exist. Includes pure-Python detectors (robust z, Mahalanobis, kNN, Isolation Forest, ensemble) and an evaluation script.
catboost-model-builder
Build CatBoost models that use its strengths correctly: raw categorical columns as cat_features (ordered target statistics, no manual encoding), text_features, Pool construction with NaN-safe categories, ordered boosting and has_time for temporal data, symmetric (oblivious) trees, overfitting detector with eval_set and use_best_model, losses for classification, regression (Quantile, Poisson, Tweedie) and ranking (YetiRank), class weights, monotone constraints, feature importance (PredictionValuesChange, LossFunctionChange) and SHAP values, GPU training and model export. Plans cat/text/numeric columns from a CSV and generates a runnable training script, and checks parameter sets for the conflicts CatBoost rejects (iterations vs n_estimators, Bayesian bootstrap with subsample, multiple class-weight options, depth > 16, use_best_model without eval_set).
categorical-encoding-selector
Choose and implement the right encoding for every categorical column given the model family and the data: one-hot (with infrequent-level grouping and handle_unknown), ordinal with an explicit order, cross-fitted target encoding (scikit-learn TargetEncoder, CatBoost ordered statistics, category_encoders inside CV), frequency/count encoding, feature hashing, native categorical support in LightGBM, HistGradientBoosting, XGBoost and CatBoost, prefix levels for codes (zip3, NAICS-2), and embeddings. Measures cardinality, rare-level share, unseen-level rate on a time-ordered holdout and target signal per column, emits the ColumnTransformer, and quantifies target-encoding leakage (in-sample vs out-of-fold vs holdout AUC).
classification-model-selector
Choose the right classification algorithm for tabular, text or mixed data and prove the choice with a fair bake-off: logistic regression (L2, L1, elastic net), linear SVM, naive Bayes, k-NN, RBF SVM, decision trees, random forest, extra trees, HistGradientBoosting, LightGBM, XGBoost, CatBoost, explainable boosting machines (EBM/GAM), points scorecards and MLPs, matched to data size, width, categorical and high-cardinality share, missingness, class imbalance, text, and constraints such as interpretability, monotonic constraints, calibrated probabilities, latency budgets and tiny deployable models. Ranks candidates with starting hyperparameters and cautions, then generates a bake-off script running every candidate on identical CV folds with per-fold metrics, fit time and prediction latency.
clustering-algorithm-selector
Choose the right clustering algorithm and check that clustering makes sense at all: cluster tendency (Hopkins statistic with a correlated-features caveat, nearest-neighbour isolation), then k-means / MiniBatchKMeans, Gaussian mixtures with BIC, agglomerative (Ward, average, complete, single) with dendrograms, DBSCAN, HDBSCAN, OPTICS, spectral clustering, BIRCH, mean shift, k-prototypes and k-modes for mixed or categorical data, and Gower distance, matched to data size, expected shapes, noise, varying density, known k, soft memberships, hierarchy and streaming. Covers preprocessing (scaling, encoding, dimensionality, distance metrics), validation (internal indices, bootstrap stability, external labels, business profiling) and assigning new points.
collaborative-filtering-implementer
Implement collaborative filtering recommenders that beat popularity: item-based kNN with cosine, Jaccard or asymmetric similarity, shrinkage, neighbourhood size, positive-only or mean-centred rating signals and 'because you liked X' explanations; implicit ALS with confidence weighting, BPR pairwise ranking and the closed-form EASE model in plain NumPy, tuned on a temporal validation split by recall@k and NDCG@k and refit on all data; plus user-kNN, explicit matrix factorisation, the implicit/LightFM libraries, hyperparameter ranges, cold-start fallbacks, scaling with sparse matrices and approximate nearest neighbours. Produces top-k lists in the format of the recommendation evaluator.