Skip to content
Back to skills

Building Ml Models

ASecurity

Build, train and evaluate machine-learning models so their numbers can be trusted — frame the decision and its error costs, set baselines, split by patient/site/time with leakage checks, climb the adaptation ladder (zero-shot → frozen embeddings + logistic head → MLP → LoRA/fine-tuning) only when a measured gain beats its uncertainty, fit calibration and thresholds on validation data, test once with intervals, and validate on an independent site. Use whenever a task trains, evaluates, compare...

  • 5 stars
  • 0 votes
  • 0 copies
  • 0 views
  • Added December 4, 2026
ai-agentsrustgotestinggitperformance

Works with

  • cli

Security analysis

A100/100

Pro scans all 11 files and shows the line behind each finding

Scanned December 4, 2026

npx -y skills add Cristhianzl/claude-skills-czl --skill building-ml-models --agent claude-code

Installs into .claude/skills of the current project.

Are you the author of Building Ml Models?

Add the live security badge to your README. It updates with every re-scan.

Security grade badge for Building Ml Models
[![Security: A — Skills Directory](https://www.skillsdirectory.com/api/skills/cristhianzl-building-ml-models/badge)](https://www.skillsdirectory.com/skills/cristhianzl-building-ml-models)

More formats (shields.io, HTML) on the badges page. Keep it an A: scan every change in CI with Pro.

Download with Pro
SKILL.md
---
name: building-ml-models
description: Build, train and evaluate machine-learning models so their numbers can be trusted — frame the decision and its error costs, set baselines, split by patient/site/time with leakage checks, climb the adaptation ladder (zero-shot → frozen embeddings + logistic head → MLP → LoRA/fine-tuning) only when a measured gain beats its uncertainty, fit calibration and thresholds on validation data, test once with intervals, and validate on an independent site. Use whenever a task trains, evaluates, compares, thresholds or ships a classifier, regressor, embedding head, ranking or scoring model — scikit-learn, PyTorch, TensorFlow/Keras, Hugging Face, medical imaging — or the user asks to "improve the accuracy", "train on this dataset", "pick a cutoff", "probe these embeddings" or "is this model good?", even if they never say "machine learning". For LoRA/SFT/encoder fine-tuning recipes use fine-tuning-models; to audit finished ML work use reviewing-ml-experiments.
license: MIT
---

# Building ML models

A model is only as good as the evidence for it, and that evidence is trustworthy when **no test case influenced any decision**, the metric matches the decision the model supports, every number carries an interval sized to its sample, and the test population is the one the model will meet. Most published ML failures are evaluation failures — leakage, test reuse, the wrong operating point — not architecture failures, so this skill spends most of its effort there.

One question governs every step. For each artifact the pipeline learns from data — weights, hyperparameters, thresholds, calibrators, normalization statistics, prompts, label maps, phrase catalogs, and the choice among variants — ask **"which data chose this?"** The answer must be "training or validation data, recorded". It is never "the test set", and never "the cases we report on".

## Read first (always)

List `learnings/` and read anything relevant — the project's datasets, licences, label quirks, known shortcuts and accepted operating points belong there and override the defaults below.

## Workflow

### 1. Frame the decision before touching data

- Write the task **T**, the performance measure **P** and the experience **E** in one paragraph, plus the population the model will be used on. If you can't state P, you can't evaluate the model.
- Name the decision the output drives and the **cost of each error**. Screening and triage punish false negatives; interrupting alerts punish false positives. The costs pick the metric and the threshold rule (step 5).
- Fix the **unit of analysis** (image, study, patient, document) and the **reference standard** (who labels, how, with what agreement). A model can't be shown to beat its reference; with one reader, every number measures agreement with that reader.
- Write the **success criterion and stop rule** before experimenting — "adopt if AUROC improves by ≥ 0.02 on two external sets with no class worse", "stop after N variants". Unwritten criteria drift toward whatever the last run produced.
- List the **baselines** to beat on the same metric and cases: a dummy prior (majority / always-normal — for drafting systems, the normal template with no model at all), a heuristic or template, the zero-shot model if one exists, and a linear model on frozen features. A complex model that doesn't beat logistic regression with an interval is a finding, not a failure; a headline metric that "always normal" wins on is the wrong headline.

### 2. Data, splits and leakage

- Build a **provenance table** per source: origin, licence/terms, how labels were made (expert read of the data, report text, NLP rules), prevalence per class, sites, dates. Public datasets are often derived from each other, so an "external" set needs a provenance check, not just a different name.
- Use **three tiers**: train → validation (every choice) → test (touched once, logged). Split by the **unit of independence**: patient always; site when the claim is about new sites; time when the claim is about the future. `train_test_split` can't see groups — use `GroupKFold`, `StratifiedGroupKFold` or `GroupShuffleSplit`.
- Run the **leakage checks** before training: group-overlap assertions, exact duplicates by hash of the decoded data, near-duplicates by embedding cosine against the training set (calibrate the cutoff on known different-subject pairs), every fitted step inside a `Pipeline`, and a shuffled-label run that must score at chance.
- Treat labels mined from text as **weak supervision**: keep "not mentioned" distinct from "negative", mask labels a source never annotated instead of filling zeros, harmonize definitions across sources (a parent class is the union of its children), and audit a sample of each critical label against the raw data.
- Commit the split manifest (ids → split) and record its hash with every run. A test set you can't reproduce isn't a test set.

Details and code: `references/data-and-leakage.md`.

### 3. Climb the adaptation ladder one rung at a time

Start at the cheapest rung that can work. Climb only when the **measured gain exceeds its uncertainty and its cost**.

| Rung | Use when | Notes |
|---|---|---|
| Zero-shot / prompt scores | Fewer than ~20–50 positives per class | Scores are uncalibrated priors; fit at most 1–2 calibration parameters on local data |
| Frozen embeddings + L2 logistic regression | The default from ~50–100 positives per class | L2-normalize the embedding; choose `C` by grouped cross-validation |
| Small MLP head | Thousands of examples and a nonlinear gain shown on external data | Early stopping on a real validation split, several seeds |
| Partial unfreezing / LoRA on the encoder | Hundreds of positives, a diagnosed acquisition shift, or memory limits | Train the head first (LP-FT) — see `skills/fine-tuning-models` |
| Full fine-tuning | Tens of thousands of labeled examples | Gains in distribution, often loses out of distribution against a linear probe |

Diagnostic: when a linear and an MLP head agree and both perform well, the signal is linearly decodable; when both fail, the representation is the ceiling and no head tuning will fix it. Evidence and recipes: `references/adaptation-ladder.md`.

### 4. Train with hygiene

- Put every fitted transform (scaler, PCA, feature selection, imputation, calibrator) inside the pipeline so cross-validation refits it per fold.
- Tune with **grouped, nested** cross-validation when data is small, and select with a proper scoring rule (log loss, Brier) or the pre-registered primary metric — never the test score.
- Early-stop on the best validation checkpoint with a patience window, not at the first uptick.
- Handle imbalance with class weights or `pos_weight`, never by resampling the validation or test sets.
- Augment only with transforms that preserve the label. For radiographs that means no horizontal flips (laterality, heart position) and only small rotations; frozen-embedding heads usually need no augmentation.
- Record seeds, library versions, the data manifest hash, the encoder weights hash and the config of every run, and repeat stochastic training over several seeds **and** resplits before believing a difference.

### 5. Turn scores into decisions

- A threshold is a hyperparameter: choose it on validation data, per class, with a rule declared before testing — never on the test set, never on training predictions.
- Pick the rule by what must survive a new population:
  - **Sensitivity floor** (e.g. ≥ 0.90) for critical or rare classes; it does not encode prevalence.
  - **Cost ratio** — call positive when the calibrated `p > C_FP / (C_FP + C_FN)`; 0.5 is only the equal-cost case.
  - **No accuracy-optimal or fixed 0.5 cutoffs for rare classes.** They predict nearly everything negative at low prevalence; AUROC 0.99 with sensitivity 0 is the classic symptom. F1- and PPV-optimal cutoffs move whenever prevalence moves.
  - A population z-score cut fixes the **flag rate**, not the error rate; validate it like any other threshold.
- Calibrate on data disjoint from training: Platt or temperature scaling for small samples, isotonic only beyond ~1,000. Record the validation prevalence beside every threshold; under pure label shift a new prevalence moves only the logit intercept, by the log ratio of the prior odds.
- Don't display an uncalibrated score as a probability or a "confidence". Show calibrated probabilities, or call it a score.

Depth and code: `references/calibration-and-thresholds.md`.

### 6. Test once, with intervals

- Run the locked test once and log it in a test-access ledger (date, commit, variant, why). Every look at a test set used to choose something wears it out; a 30-case set wears out in a few looks.
- Report every proportion with a **Wilson, Jeffreys or Clopper–Pearson** interval — statsmodels' `proportion_confint` defaults to Wald, so pass `method="wilson"` — AUROC with DeLong or a patient-level bootstrap, and other metrics with a patient-level bootstrap.
- Compare models with **paired** tests on the same cases: exact McNemar for right/wrong, DeLong for AUROC, a paired bootstrap for anything else. Overlapping intervals are not a test.
- Slice by site, device/view, sex, age and known hidden strata (e.g. pneumothorax with and without a chest drain). Aggregates hide failing subgroups.
- Know what small sets can say: 3 of 3 positives detected is an exact 95% CI of 0.29–1.00; on 30 paired cases a difference needs ≥ 6 unopposed wins to reach p < 0.05; the best of 10 equally good variants picked on 30 cases looks ~10–14 points better than it is. Small sets support estimation and qualitative review, never ranking.

Tables and code: `references/statistics.md`.

### 7. Validate where it will be used

- An external test needs a different site **and** no overlap with any training or pretraining source: read the model cards' data lists and scan for duplicates. Expect degradation — most radiology models lose performance at new sites.
- Adapt cheapest first: re-derive per-class thresholds on local labeled data → recalibrate (intercept, then intercept and slope once you have 100–200 events) → estimate local priors by EM on calibrated outputs → only then LP-FT or LoRA. Centering embeddings per source can delete real signal when sources differ in prevalence.
- Pre-register the pick (variant, threshold rule) before the external test; report unplanned comparisons as exploratory and confirm them on fresh data.

Depth: `references/generalization-and-shift.md`; clinical specifics: `references/medical-imaging.md`.

### 8. Diagnose before iterating

- Plot learning curves (does more data help?) and keep a **training-dev** split drawn from the training distribution: training-dev ≈ training while dev ≫ training-dev means data mismatch, which more of the same data won't fix.
- Read ~100 sampled failures and tally them by cause; the tally bounds what fixing each cause can gain. For pipelines, substitute a perfect output at each stage (error analysis by parts, oracle ceiling) to find the bottleneck.
- At a plateau, look for qualitatively new information — new labels, a new source, a new input — instead of refining the same signal.
- Keep a ledger of every variant tried, dead ends included. If many variants were scored on one evaluation set, it has become a development set; confirm on fresh data.

Depth: `references/diagnosis-and-iteration.md`.

### 9. Ship responsibly

- Pin the model: weights hash, preprocessing contract (resize, normalization), thresholds with their rule and validation prevalence, and the evaluation report.
- Add a training/serving parity test: the serving path must reproduce the research pipeline's features and scores on fixture inputs — including every step that alters the input on one path only (de-identification that masks burned-in text, windowing, resizing, padding). Measure the score shift such a step causes before trusting any research number in production.
- Write a model card once output reaches users, put new models behind a feature flag, monitor input and score distributions and flag rates, and keep a rollback path.
- Respect data licences (research-only data can't serve clinical use) and privacy. In medicine, software that analyzes images is a regulated device in most jurisdictions whatever its disclaimer says — see `references/medical-imaging.md`.

## Anti-patterns — stop and fix

- Reporting a number from the set used to pick the variant, threshold, epoch or prompt.
- Splitting by image or row when subjects contribute several; `train_test_split` on grouped data.
- Fitting a scaler, PCA, selector or normalization population on all data before splitting.
- Calling a derived dataset "external", or ignoring the encoder's pretraining data.
- Accuracy-optimal or 0.5 thresholds on rare classes; one global threshold for every class.
- A bare percentage with no interval; Wald intervals on small samples; unpaired tests on paired data.
- "Beats radiologists" from one reader, or without a multi-reader analysis.
- Text-mined labels treated as ground truth; zeros filled in for classes a source never labeled.
- Horizontal flips or large rotations on radiographs.
- Best seed against best seed; one run per arm for a stochastic method.
- Uncalibrated scores shown to users as probabilities.
- Results that live only in temp folders, without commit, config and data hashes.

## Results block — attach to every reported number

```text
Claim:       <metric> = <value> [<low>–<high>, <interval method>] on <dataset/split> (n=<cases>, positives=<k>)
Chosen by:   <which data chose the model, hyperparameters, threshold and calibrator> (validation only)
Baselines:   <dummy / heuristic / zero-shot / linear probe>, same cases, same metric
Comparison:  <paired test and p, or the interval of the difference>
Provenance:  commit <sha>, config <hash>, split manifest <hash>, encoder weights <hash>
Test access: <date>, ledger entry <id>, first look: <yes/no>
Limits:      <sites, strata, label source, prevalence — and what this does NOT show>
```

## References

| File | Read when |
|---|---|
| `references/evaluation-harness.md` | Starting a project or reporting results — split manifest, provenance block, results registry, test-access ledger, interval code |
| `references/data-and-leakage.md` | Designing splits, scanning for duplicates and group overlap, handling weak labels |
| `references/adaptation-ladder.md` | Choosing zero-shot, probe, MLP or fine-tuning; augmentation; multi-label heads |
| `references/calibration-and-thresholds.md` | Picking cutoffs, calibrating, correcting for prevalence shift, displaying scores |
| `references/statistics.md` | Intervals, paired comparisons, sample sizes, run-to-run variance, multiple comparisons |
| `references/generalization-and-shift.md` | External validation, provenance, site adaptation, monitoring |
| `references/diagnosis-and-iteration.md` | Learning curves, training-dev splits, error analysis, plateaus, stop rules |
| `references/medical-imaging.md` | Any clinical or imaging model — shortcuts, label noise, reference standards, CLAIM / TRIPOD+AI, regulation |
| `references/foundations.md` | The theory behind the rules (Mitchell's *Machine Learning*): inductive bias, overfitting, Bayes decisions, sample complexity, k-NN, prior knowledge, RL |

## Capture a learning

When you hit a dataset quirk, a shortcut, an operating point the team agreed on, or a check that caught a real bug, append a `learnings/YYYY-MM-DD-slug.md` (or use `/learn`).

## See also

- `skills/fine-tuning-models` — LoRA/QLoRA, SFT, encoder fine-tuning, alignment, hardware.
- `skills/reviewing-ml-experiments` — audit a finished experiment, result or claim.
- `skills/evaluating-ai-output` — evals for non-deterministic LLM output (pass@k / pass^k).
- `skills/writing-tests` — tests for the deterministic code around the model (data transforms, parity tests).

Files in this skill

  • SKILL.md15.7 KB
  • learnings/README.md789 B
  • references/adaptation-ladder.md7.5 KB
  • references/calibration-and-thresholds.md7.1 KB
  • references/data-and-leakage.md7.9 KB
  • references/diagnosis-and-iteration.md4.2 KB
  • references/evaluation-harness.md6.3 KB
  • references/foundations.md7.5 KB
  • references/generalization-and-shift.md4.7 KB
  • references/medical-imaging.md6.6 KB
  • references/statistics.md7.1 KB

Attribution

Is this your skill, or is something wrong with this listing? Request removal or report an issue. Author removals are honored within 72 hours.

View all in ai-agents →

Comments

Loading comments…

Newsletter

Get the weekly list of safe new skills, and the ones we pulled.