К основному содержанию
скилл CX Codex

ml-experiment-standards — скилл для Claude Code

Заставляет агента проверять утечки, выбирать сплиты и метрики до обучения модели. Пригодится, когда результат нужно воспроизвести, а не просто получить цифру.

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add muend/geoai-skills --skill ml-experiment-standards -a claude-code
Открыть на GitHub

Что делает ml-experiment-standards

Скилл подключается, когда вы обучаете, валидируете, тюните или бенчмаркаете предиктивную модель. Он требует сначала показать распределения, пропуски, выбросы и баланс целевой переменной: без этого выбор метрики и лосса превращается в угадывание.

Дальше идёт аудит утечек. На каждом сплите агент отвечает на вопрос, нет ли в обучающей выборке косвенной информации о тестовых объектах, и записывает ответ комментарием в коде. Для пространственных данных он берёт spatial block CV, для групп — GroupKFold, для временных рядов — TimeSeriesSplit. Масштабирование и кодирование допускаются только на train, через sklearn.pipeline.Pipeline.

Метрику нельзя выбрать по умолчанию: нужна одна фраза обоснования, а к каждой оценке — доверительный интервал или разброс по фолдам. Скрипт обучения строится по шаблону с dataclass-конфигом, фиксированным seed и записью runs/run_meta.json. Пропустите аудит утечек — и uplift-выводы по модели не будут ничего стоить, потому что пост-сплит препроцессинг и неучтённая зависимость тестовых объектов ломают их первыми.

Какие задачи решает

  • проверить, не протекает ли тестовая выборка в обучение
  • выбрать сплит для пространственных или сгруппированных данных
  • обосновать метрику вместо accuracy по умолчанию
  • добавить доверительные интервалы к метрикам модели
  • собрать воспроизводимый скрипт обучения с фиксированным seed

Примеры запросов агенту

  • Обучи модель на этих данных и сначала покажи аудит утечек и обоснование сплита
  • Проверь, что препроцессинг фитится только на train, и переделай пайплайн
  • Сравни baseline и модель по фолдам и скажи, есть ли вообще разница

Как установить ml-experiment-standards

1Через Skills CLI (Vercel)

npx skills add muend/geoai-skills --skill ml-experiment-standards -a claude-code

2Вручную: положить файлы

~/.claude/skills/ml-experiment-standards/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/ml-experiment-standards/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Вопросы о ml-experiment-standards

Как установить ml-experiment-standards в Claude Code?

Выполните npx skills add muend/geoai-skills --skill ml-experiment-standards -a claude-code. Файл скилла окажется по пути ~/.claude/skills/ml-experiment-standards/SKILL.md.

Что делает ml-experiment-standards?

Задаёт стандарт ML-эксперимента: EDA до модели, аудит утечек, корректные сплиты, обоснованные метрики с оценкой неопределённости, воспроизводимый скрипт и честный отчёт.

Для каких задач скилл не срабатывает?

Он не предназначен для описательного EDA и статистического вывода без предсказания. Для пространственной статистики и геостатистики берите другие инструменты.

Исходный текст

SKILL.md · MIT
---
name: ml-experiment-standards
description: >-
  Always invoke for training, validating, tuning, benchmarking, or claiming
  readiness of a predictive model. Covers leakage audits, spatial and grouped
  splits, metrics, reproducibility, and honest reporting. Invoke especially
  when spatial dependence, split design, or deployment geography is unknown;
  uncertainty is a reason to use this skill. Do not trigger for descriptive
  EDA or non-predictive statistical inference.
license: MIT
metadata:
  author: Muhammed Enes Duran
---

# ML Experiment Standards

Purpose: every ML job (quick prototypes included) is reproducible,
leakage-free, and metric-justified. These are not optional polish; every
skipped item typically returns as "the model collapsed in production" or
"the result didn't replicate".

## 1. EDA comes first

Before any model, produce and show: distributions, missingness rates,
outliers, target balance, salient correlations. Metric and loss choice
depend on this information; a model recommendation without EDA is a guess.

## 2. Leakage audit

At every split decision, answer explicitly (and write the answer as a code
comment): "Does the training set contain indirect information about any
test sample?"

| Data type | Correct split | Why |
|---|---|---|
| Independent samples | Stratified k-fold | Preserves class ratios |
| Time series | TimeSeriesSplit / walk-forward | Future must not leak into past |
| **Spatial data** | Spatial block CV — see `references/spatial-cv-protocol.md` | Neighbors are near-duplicates |
| Grouped data (patient, parcel, scene) | GroupKFold | A group must not straddle the split |

- Scalers/encoders/imputers are **fit on train only**; the clean path is
  `sklearn.pipeline.Pipeline` — CV then fits correctly by construction.
- Target-derived features (target encoding etc.) must be computed
  out-of-fold, and shown to be.

The spatial protocol in `references/spatial-cv-protocol.md` is the single
canonical source for this repo — other skills link here; do not restate it.

## 3. Metric selection — justified

Never choose a metric by default; write a one-sentence rationale:

- Imbalanced classes → **F1 / AUC-PR**, not accuracy (accuracy rewards
  majority-class memorization).
- Segmentation → **IoU/Dice** (pixel accuracy is inflated by background).
- Regression → RMSE (sensitive to large errors) vs MAE (robust) vs R²
  (variance explained) — justify from the use case.
- Every point estimate gets uncertainty: bootstrap CI or mean ± std across
  CV folds. A single number hides whether a difference is signal or noise.

## 4. Reproducibility skeleton

Every training script follows this shape (script-first; no notebook magic):

```python
"""Experiment: <name>. Goal and success criterion: <one sentence>."""
from dataclasses import dataclass, asdict
import json, random
import numpy as np

@dataclass
class Config:
    seed: int = 42
    lr: float = 1e-3
    batch_size: int = 32
    epochs: int = 100
    patience: int = 10  # early stopping

def set_seed(seed: int) -> None:
    random.seed(seed)
    np.random.seed(seed)
    # if torch: torch.manual_seed(seed); torch.cuda.manual_seed_all(seed)

def main(cfg: Config) -> None:
    set_seed(cfg.seed)
    ...  # data -> split -> pipeline -> train -> evaluate
    with open("runs/run_meta.json", "w", encoding="utf-8") as f:
        json.dump({"config": asdict(cfg), "metrics": metrics}, f, indent=2)

if __name__ == "__main__":
    main(Config())
```

- Config lives in a dataclass/YAML, never hardcoded — sweeps and run
  comparison depend on it.
- Pin library versions (`pip freeze > requirements.txt`).
- Use MLflow/W&B when available; the JSON log above is the minimum.

## 5. Deep learning extras

- **Loss rationale**: Dice/Dice+CE for imbalanced segmentation; write why.
  Focal only after comparison — not a free win.
- **Augmentation rationale**: state which transforms respect the physics
  of the problem (orientation-dependent tasks forbid some rotations;
  multispectral forbids naive color jitter).
- **Overfitting control**: early stopping with patience + a train/val
  curve in the report; no curve, no "the model is good".
- **Capacity order**: small model + simple baseline first (logistic
  regression, RF); a deep model that can't beat the baseline is a data
  problem, not an architecture problem.
- EO-specific chipping/inference details → `geo-deep-learning`.

## 6. System context (MLOps)

Position every model in its chain in one paragraph: data source →
cleaning → features/versioning → training → evaluation → deployment
(batch/real-time) → monitoring (data/model drift). Even for a prototype,
note "what this step becomes in production".

## 7. Report format

```
## Experiment: <name>
- Data: n=<>, split: <strategy + rationale>
- Baseline: <model> → <metric ± CI>
- Model: <model> → <metric ± CI>
- Leakage audit: <what was checked>
- Next step: <single recommendation>
```

When reporting differences, respect statistical honesty: if the gap
doesn't exceed the across-fold std, say "no clear difference" — no
p-hacking, no selective reporting.

## Execution contract

- **Workflow:** define prediction target and decision use; establish a baseline; audit leakage; create spatially valid splits; train reproducibly; quantify uncertainty; inspect errors and deployment fit.
- **Decision rules:** apply this skill only to predictive model experiments; use spatial statistics for inference, geostatistics for sampled-surface estimation, and descriptive analysis without forcing a model.
- **Verification protocol:** reproduce from a clean environment, compare against baseline across folds or seeds, inspect spatial residuals, verify split independence, and test the final decision threshold.
- **Failure modes:** invalidate uplift claims for leakage, post-split preprocessing, inappropriate metrics, non-independent test units, selective runs, or train-serving skew.
- **Deliverables:** experiment configuration, split and seed manifest, baseline and model metrics with uncertainty, leakage audit, error analysis, artifacts, and deployment caveats.
- **Source freshness:** consult [the authoritative source registry](references/authoritative-sources.md) before using version-sensitive split, metric, or reproducibility APIs.

© Muhammed Enes Duran · MIT · muend/geoai-skills

Похожие скиллы

Все скиллы по теме «ИИ и ML» →
minimal-run-and-audit lllllllama Фиксирует результаты тестовых прогонов и инференса при воспроизведении ML-репозиториев. Создаёт стандартизированные отчёты и патчи в папке repro_outputs/. CX Codex +1 476 200установок ai-research-explore lllllllama Управляет исследовательскими экспериментами в deep learning на базе зафиксированного бейзлайна. Помогает проверять гипотезы без потери воспроизводимости. CX Codex +1 337 400установок experiment-code lingzhi227 Пишет и дорабатывает код ML-экспериментов для научной статьи: обучение, оценка, отладка, графики. Пригодится, когда нужно прогнать серию запусков и сравнить результаты. CX Codex +1 1 600установок experiment-craft EvoScientist Скилл для Claude Code, который находит причины сбоев в экспериментах ML и ведёт журнал гипотез. Помогает при расхождении обучения или нестабильных результатах. CX Codex +1 373установок measure-experiment-design product-on-purpose Собирает документ с параметрами эксперимента: варианты, метрики, размер выборки и срок. Нужен, когда гипотеза уже сформулирована, а тест ещё не запущен. CX Codex +1 754установок run-experiment wanshuiyin Скилл разворачивает и запускает ML-эксперименты на локальном GPU, удалённом сервере, Vast.ai или Modal. Пригодится, когда обучение надо стартовать, а не настраивать вручную. CX Codex +1 523установок

Из того же набора6

spatial-statistics Скилл для пространственного анализа: проверяет кластеризацию, горячие точки и зависимость в геоданных, а потом помогает с диагностикой регрессии. CX Codex +1 ★ 35звёзд репо point-cloud-lidar Скилл для работы с LAS, LAZ и COPC: классификация земли, DTM/DSM/CHM, метрики леса и зданий, вертикальные датумы. Нужен, когда на входе сырое облако точек. CX Codex +1 ★ 35звёзд репо geostatistics-interpolation Скилл для пространственной интерполяции: строит поверхность по редким замерам и отдельно считает карту неопределённости. Полезен, когда нужно оценить значения между станциями, скважинами или зондированиями. CX Codex +1 ★ 35звёзд репо geo-data-engineering Помогает агенту собрать геоданные из OSM, STAC или Overture, привести их в рабочий вид и не потерять строки по дороге. CX Codex +1 ★ 35звёзд репо arcgis-pro-automation Скилл для управления локальными проектами ArcGIS Pro и ArcPy через arcgis-mcp-bridge: геообработка, проекции, растры, сети, экспорт компоновок. CX Codex +1 ★ 35звёзд репо

Спонсоры проекта

Компании, которые помогают держать аналитику открытой