model-training-and-evaluation
БесплатноБез исполняемых скриптовНе проверенUse when training, tuning, comparing or evaluating a model — choosing the cross-validation scheme, baselines, tuning inside CV, thresholds and calibration…
от makifbaysal★ 123 звезды на GitHubОб этом скилле
Model Training and Evaluation
Overview
A model's score is an estimate, and its quality depends on how it was estimated: the split that matches the data's structure, the baseline it is compared with, the tuning kept away from the final test, and the spread around the number. Gradient-boosted trees on tabular data are the strong default; anything more complex has to beat them on the same folds.
Core principle: every number you report answers "compared with what, measured how, and how sure" — baseline, CV scheme, spread.
1. Pick the CV scheme from the data
| Data | Splitter |
|---|---|
| Independent rows, classification | StratifiedKFold(n_splits=5, shuffle=True, random_state=seed) |
| Independent rows, regression | KFold(n_splits=5, shuffle=True, random_state=seed) |
| Repeated entities (users, patients, stores) | GroupKFold / StratifiedGroupKFold with groups= |
| Time-ordered, forecasting or scoring the future | TimeSeriesSplit(n_splits=5, gap=horizon) or a rolling-origin split by date |
| Small data (< a few thousand rows) | RepeatedStratifiedKFold for a stabler mean and spread |
The scheme mirrors production: a model that scores next month is validated on a later month than it trained on. Leakage rules apply throughout (leakage-safe-feature-engineering).
2. Baselines on the same folds
scoring = "average_precision"
baseline = cross_validate(DummyClassifier(strategy="prior"), X_train, y_train, cv=cv, scoring=scoring)
linear = cross_validate(make_linear(seed), X_train, y_train, cv=cv, scoring=scoring)
gbm = cross_validate(make_gbm(seed), X_train, y_train, cv=cv, scoring=scoring)
Always include the dummy and the simple rule from ml-problem-framing. A complex model that beats the linear one by less than the fold-to-fold spread is not better.
3. Tune inside cross-validation
Hyperparameter search runs on the training data with the same CV; the test set is not involved (rule test-set-discipline).
def objective(trial: optuna.Trial) -> float:
params = {
"learning_rate": trial.suggest_float("learning_rate", 1e-3, 0.3, log=True),
"max_leaf_nodes": trial.suggest_int("max_leaf_nodes", 15, 255, log=True),
"l2_regularization": trial.suggest_float("l2_regularization", 1e-8, 10.0, log=True),
}
return cross_val_score(make_gbm(seed, **params), X_train, y_train, cv=cv, scoring=scoring).mean()
study = optuna.create_study(direction="maximize", sampler=optuna.samplers.TPESampler(seed=seed))
study.optimize(objective, n_trials=50)
- The best CV score of a search is optimistically biased; the honest estimate is the untouched test set, or nested CV when there is no test set.
- Early stopping takes its validation rows from the training fold (
HistGradientBoosting*(early_stopping=True, validation_fraction=0.1), or aneval_setcarved from the training fold for XGBoost/LightGBM) — never from the test set. - Keep search spaces small and log-scaled; 50 sensible trials beat 1,000 over nonsense ranges.
4. Report with spread
res = cross_validate(model, X_train, y_train, cv=cv, scoring=scoring)
print(f"{scoring}: {res['test_score'].mean():.3f} ± {res['test_score'].std():.3f} over {cv.get_n_splits()} folds")
For the final test set, a bootstrap interval:
def bootstrap_ci(y_true, y_score, metric, n=1000, seed=0, alpha=0.05):
rng = np.random.default_rng(seed)
stats = []
for _ in range(n):
i = rng.integers(0, len(y_true), len(y_true))
if np.unique(y_true[i]).size > 1:
stats.append(metric(y_true[i], y_score[i]))
return np.quantile(stats, [alpha / 2, 1 - alpha / 2])
Report baseline and model side by side, with the number of rows and positives (rule report-uncertainty).
5. Thresholds and calibration
- The decision threshold is tuned, not assumed:
TunedThresholdClassifierCV(model, scoring=..., cv=cv)optimises it on CV folds for the metric or cost the decision cares about. - When probabilities are consumed as probabilities (expected value, pricing, a risk shown to people), check calibration on held-out data:
calibration_curve, Brier score. Fix withCalibratedClassifierCV(model, method="isotonic" | "sigmoid", cv=5); isotonic needs plenty of data (roughly a thousand or more calibration rows), sigmoid otherwise. - Class weights or resampling change the predicted probabilities — calibrate after them.
6. Slices
An average hides the segment where the model fails. Report the metric per meaningful slice — plan, country, new vs tenured, device, most recent period — with n per slice:
def metrics_by_slice(df: pd.DataFrame, slice_col: str) -> pd.DataFrame:
rows = []
for value, g in df.groupby(slice_col, observed=True):
has_both = g["y"].nunique() > 1
rows.append({
slice_col: value,
"n": len(g),
"positive_rate": g["y"].mean(),
"pr_auc": average_precision_score(g["y"], g["score
Установить model-training-and-evaluation в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
FAQ
Что делает скилл model-training-and-evaluation?
Use when training, tuning, comparing or evaluating a model — choosing the cross-validation scheme, baselines, tuning inside CV, thresholds and calibration, per-slice metrics, feature importance and error analysis
Как установить скилл model-training-and-evaluation?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл model-training-and-evaluation запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
skill-creator
Create new skills, modify and improve existing skills, and measure skill performance. Use when users want to create a skill from scratch, edit, or optimize an…
от Anthropicdiscernment-nudge
After you give a substantive answer or draft that the user may act on — advice or recommendations, drafted artifacts such as goals, plans, pitches, proposals…
от Anthropicdata-consolidate
Joins the plant's scheduled exports and connector data into one working dataset — ERP items (NetSuite or Infor M3), sales orders, production work orders…
от Anthropicinspection-to-capa
Runs the quality chain end to end: writes the nonconformance against the requirement it violates, searches history at the moment of writing to say whether…
от Anthropic