AGENT SKILL

ml-feature-engineering

Designs ML features with leakage-safe pipelines, correct categorical encoding by cardinality, numeric transforms, and validation that a feature earns its place. Use when someone asks "how should I encode this high-cardinality column", "why does my model score great offline and fail in production", "what features should I build from this table", or "should I scale these inputs". Do NOT use for building the serving infrastructure that stores and versions features across models - use feature-store-design instead; for detecting when live feature distributions shift after deployment - use data-drift-monitor instead; for initial dataset exploration and profiling - use eda-playbook instead.

License 许可
MIT
所属仓库
SkillMedev/skills
最近更新
2026-10-14
Stars
★ 25
Forks
3

01 前言 Front Matter

name
ml-feature-engineering
metadata
{ "title": "Feature Engineering" }
description
Designs ML features with leakage-safe pipelines, correct categorical encoding by cardinality, numeric transforms, and validation that a feature earns its place. Use when someone asks "how should I encode this high-cardinality column", "why does my model score great offline and fail in production", "what features should I build from this table", or "should I scale these inputs". Do NOT use for building the serving infrastructure that stores and versions features across models - use feature-store-design instead; for detecting when live feature distributions shift after deployment - use data-drift-monitor instead; for initial dataset exploration and profiling - use eda-playbook instead.

03 SKILL.md 正文

Feature Engineering

Most "amazing offline, useless in production" models are not modeling failures - they are leakage failures introduced during feature engineering. This skill builds features that improve cross-validated performance without smuggling the target into the inputs, and rejects features that only look good because they cheated.

Operating procedure

Leakage prevention comes first because every later step (encoding, aggregation, imputation) is a leakage opportunity; validation comes last because a feature that does not move the cross-validated metric does not ship.

Step 1: Gather inputs

Collect before writing transforms; label unknowns as guesses.

  1. Prediction task and the exact prediction time: what is known at the moment the model must predict? Everything else is off-limits.
  2. Target definition and how it was produced - features derived from the same process as the label are proxy-leakage suspects.
  3. Data shape: row count, column list with dtypes, entity keys, and whether rows have a time dimension.
  4. Model family (linear, tree ensemble, neural) - it determines which transforms are necessary and which are wasted work.
  5. Serving constraints: will these features be computable at inference time with the same code and latency budget?

Step 2: Lock the leakage rules

  1. Fit all transformers (scalers, encoders, imputers) on the training fold only, then apply to validation and test.
  2. Never use information from after the prediction time.
  3. Exclude features that are proxies for the label or only known after the outcome (e.g. "account_closed_reason" in a churn model).
  4. For time series, split by time and never shuffle.

Enforce mechanically with scikit-learn Pipelines and ColumnTransformer so fitting always happens inside cross-validation:

from sklearn.pipeline import Pipeline
from sklearn.compose import ColumnTransformer
pre = ColumnTransformer([
    ("num", StandardScaler(), num_cols),
    ("cat", OneHotEncoder(handle_unknown="ignore"), cat_cols),
])
model = Pipeline([("pre", pre), ("clf", GradientBoostingClassifier())])

If any transform lives outside the pipeline, assume it leaks until proven otherwise.

Step 3: Encode categoricals by cardinality

Pick the encoder from the category count - this is a lookup, not a debate:

  • Up to ~15 categories: one-hot. Safe for any model.
  • ~15-50 categories: one-hot still works for tree ensembles; for linear models watch the coefficient count.
  • 50+ categories: target/mean encoding, computed strictly with out-of-fold means - in-fold target encoding is the single most common leakage bug in tabular ML. Add smoothing toward the global mean for categories with fewer than ~20 rows.
  • 10,000+ categories (user IDs, URLs): hashing encoder when memory matters, or entity embeddings.
  • Ordinal encoding only when categories have a true order (S < M < L), never as a memory shortcut.

Step 4: Transform numerics

  • Scale (standardize or min-max) for distance- and gradient-based models; tree ensembles do not need it - skip the work.
  • Apply log or Box-Cox to skewed positive features; a rule of thumb trigger is |skewness| > 1.
  • Bin into quantiles when the relationship is non-monotonic and the model is linear.

Step 5: Build derived features

  • Ratios and differences encode domain meaning cheaply: price per unit, days since last event.
  • Polynomial or explicit interaction terms help linear models capture combined effects.
  • Group-by aggregations (mean, count, std per entity) are the highest-value tabular features - and must be computed out-of-fold or over past-only windows, or they leak.
  • Datetime: extract hour, day of week, month, is_weekend, plus cyclical sine/cosine encodings for periodic values, and elapsed-time features like days since signup.

Step 6: Handle missing values

  • Add a binary missing-indicator before imputing when the null rate exceeds ~5% - missingness is often informative.
  • Impute numerics with median, categoricals with a dedicated "missing" category.
  • Avoid mean imputation on skewed data.
  • A feature over ~60% missing rarely earns its place unless the missingness itself predicts; test the indicator alone first.

Step 7: Select and validate

  • Remove near-constant features (over ~99% a single value) and one of any pair with |correlation| > 0.95.
  • Use permutation importance or SHAP rather than raw model importances, which inflate high-cardinality features.
  • A feature ships only if it improves the cross-validated metric, not training fit. Suspicious rule: any single new feature that jumps AUC by more than ~0.05 is a leakage suspect first and a triumph second - audit its availability at prediction time before celebrating.
  • Keep a feature catalog documenting source, transformation, and refresh cadence; when features are shared across models, graduate to feature-store-design.

Worked artifact: leakage contrast pair

Bad - target encoding fit on the full dataset before the split:

means = df.groupby("merchant_id")["is_fraud"].mean()   # sees test-set labels
df["merchant_te"] = df["merchant_id"].map(means)
X_train, X_test = train_test_split(df)                  # too late: already leaked

Good - out-of-fold target encoding, so each row's encoding never saw its own label:

from sklearn.model_selection import KFold
df["merchant_te"] = np.nan
for tr_idx, val_idx in KFold(5, shuffle=True, random_state=0).split(df):
    means = df.iloc[tr_idx].groupby("merchant_id")["is_fraud"].mean()
    global_mean = df.iloc[tr_idx]["is_fraud"].mean()
    df.loc[df.index[val_idx], "merchant_te"] = (
        df.iloc[val_idx]["merchant_id"].map(means).fillna(global_mean)
    )

The bad version typically shows a large offline lift that evaporates in production; the good version shows a smaller, honest lift that survives.

Deliverable

Produce a feature specification containing: the prediction-time definition, the feature list with source, transform, encoder choice and rationale, the leakage audit (how each feature is available at prediction time), imputation and indicator decisions, and the cross-validated before/after metric for each added feature group.

Do NOT

  • Do not fit any transformer outside the cross-validation loop; the pipeline is the guardrail, not a style preference.
  • Do not target-encode with in-fold means - it is leakage even when the code looks innocent.
  • Do not scale features for tree ensembles or skip scaling for linear/kNN/neural models; match transform to model family.
  • Do not trust raw impurity-based importances; they overrate high-cardinality columns.
  • Do not keep a feature because it is clever; keep it because the cross-validated metric moved.

Quality bar

  • Every transform is inside a Pipeline/ColumnTransformer and fit on training folds only.
  • Every feature has a documented answer to "is this value knowable at prediction time?"
  • Encoder choices follow the cardinality ladder, with out-of-fold means for target encoding.
  • Time-dimensioned data uses time-based splits.
  • Each shipped feature shows a cross-validated improvement, and any outsized single-feature jump has been leakage-audited.

04 同仓库更多 Skills

SkillMedev
SkillMedev/skills

有氧运动计划

zone-2-cardio-plan

当有人要求制定稳态有氧训练计划、进行有氧基础训练或达到第二区间、安排轻松或耐力型的每周有氧训练、按心率区间训练,或提高静息心率、最大摄氧量或耐力时,可以使用此方案。该方案构建了一个包含训练计划结构、训练方式选择和进度安排的心率区间有氧训练模块。本方案仅提供一般健身指导,不构成医疗建议。请勿用于设计力量或举重训练计划(请使用力量训练计划)、高强度间歇训练 (HIIT) 或循环训练(请使用体能训练和 HIIT 计划),或灵活性/柔韧性训练(请使用灵活性训练计划)。

★ 25
SkillMedev
SkillMedev/skills

youtube-script-writer

Writes retention-engineered long-form YouTube scripts on a hook/body/payoff architecture - a first-30-seconds hook that survives the retention cliff, a beat-sheet body with mini-hooks and bridges, timed pattern interrupts, and a payoff that over-delivers - with B-roll and editing cues marked inline. Use when someone says "script my next video", "my retention graph dies at the start", "tighten this draft", or "outline a video on X". Do NOT use for the 3-second opener of TikTok, Reels, or Shorts - use video-hook-writer instead; do NOT use for spoken voiceover synced to on-screen tutorial actions - use narration-script instead; do NOT use for a sales demo built on a buyer's discovery notes - use demo-script instead; do NOT use to design the thumbnail and title - use thumbnail-concept instead.

★ 25
SkillMedev
SkillMedev/skills

win-back-campaign

Designs segmented win-back email sequences for dormant users - dormancy tiers, a three-beat sequence with a single proportional incentive, and a suppression rule - and measures success by re-activation, not opens. Use when someone says "our users went quiet", "design a win-back campaign", "how do I re-engage lapsed customers", "should we email people who haven't logged in for months", or lifecycle messaging has stopped landing with a lapsed segment. Do NOT use for recovering an unfinished checkout - use abandoned-cart-sequence instead. Do NOT use for diagnosing and fixing why active customers cancel - use churn-reduction instead. Do NOT use for building always-on onboarding or nurture flows - use email-drip-builder instead.

★ 25
SkillMedev
SkillMedev/skills

wikipedia-style

Writes neutral, verifiable, encyclopedic prose following Wikipedia's core content policies and manual of style - NPOV, inline citations, notability-backed claims, and a strict ban on promotional language. Use when someone asks "write this like a Wikipedia article", "draft a Wikipedia page for this company or person", "make this neutral and encyclopedic", or "why does my article draft keep getting rejected". Do NOT use for persuasive or opinion writing - use op-ed-writer instead; for thesis-driven academic papers, use academic-essay; for verifying claims in existing text, use fact-checker.

★ 25
SkillMedev
SkillMedev/skills

whitepapers

Structures and writes authoritative B2B whitepapers - a standalone executive summary, a data-sized problem statement, methodology, evidence-driven findings, recommendations, and a soft call to action - flagging every claim that needs a real citation. Use when a marketer asks "write a whitepaper on this topic", "turn our research into a lead-gen asset", "make this credible enough for executives", or a draft reads like a product pitch instead of analysis. Do NOT use for customer-story-driven proof - use case-study-builder instead; for policy audiences, use policy-brief.

★ 25
SkillMedev
SkillMedev/skills

white-space-analysis

Finds unmet market gaps by ranking jobs-to-be-done on importance versus satisfaction, overlaying them against current solutions and workarounds, and validating that each gap is real, winnable, and worth winning. Use when someone asks "where are the gaps in this market", "what's underserved here", "where should we play next", or is hunting for product, feature, or market-entry opportunities. Do NOT use for profiling competitors and building battle cards - use competitive-intelligence instead; for putting a dollar figure on an identified opportunity - use market-sizing instead; for extracting jobs-to-be-done from raw customer interviews - use jtbd-extractor instead.

★ 25