[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7CRRPCD3KCGSZRRPVVNVK3G":3,"skill-same:01M7CRRPCD3KCGSZRRPVVNVK3G":50},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":27,"commitSha":28,"skillDirectory":29,"forksCount":30,"repositoryHtmlUrl":31,"repositoryHomepageUrl":32,"ownerHtmlUrl":33,"ownerBlogUrl":6,"ownerDescription":34,"updatedAt":35,"install":36,"resources":49},"01M7CRRPCD3KCGSZRRPVVNVK3G","leakage-safe-feature-engineering",null,"Use when building or changing features, preprocessing, encoders, resampling or train\u002Fvalidation\u002Ftest splits — keep every fitted transform inside a Pipeline fitted on training folds only, and build time and group features without seeing the future or the same entity twice","makifbaysal\u002Ftasktrooper","makifbaysal","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F25031940?v=4","01M7CRG3ZCSYZSSEVDMW3DEYC8","Mehmet Akif Baysal","01M7CRG401FJ8YAXH5ER730XYV",122,"Apache-2.0","https:\u002F\u002Fgithub.com\u002Fmakifbaysal\u002Ftasktrooper\u002Fblob\u002Fmain\u002Fcatalog\u002Fagents\u002Fdata-scientist\u002Fskills\u002Fleakage-safe-feature-engineering\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: leakage-safe-feature-engineering\ncategory: ml\ndescription: Use when building or changing features, preprocessing, encoders, resampling or train\u002Fvalidation\u002Ftest splits — keep every fitted transform inside a Pipeline fitted on training folds only, and build time and group features without seeing the future or the same entity twice\ntech_stack: Python\nsource: original; informed by scikit-learn Common pitfalls and recommended practices and the cross-validation user guide (cited, not reproduced)\n---\n# Leakage-Safe Feature Engineering\n\n## Overview\n\nLeakage is information in training that will not exist at prediction time. It produces a great offline score and a model that fails in production — and no test fails, because the code does exactly what it was told. The three sources: transforms fitted on rows they later score, features computed from the future, and the same entity on both sides of a split.\n\n**Core principle:** split first; everything that learns from data (scalers, imputers, encoders, selectors, resamplers) is fitted inside the training fold only — in practice, inside one scikit-learn `Pipeline` that is cross-validated and shipped as a single artifact.\n\n## 1. Fit inside the Pipeline, never before the split\n\n```python\n# ❌ the scaler and the selector have seen the test rows\nX_scaled = StandardScaler().fit_transform(X)\nX_sel = SelectKBest(k=20).fit_transform(X_scaled, y)\nX_train, X_test, y_train, y_test = train_test_split(X_sel, y)\n\n# ✅ split once, then everything learned lives in the pipeline\nX_train, X_test, y_train, y_test = train_test_split(\n    X, y, test_size=0.2, stratify=y, random_state=seed\n)\npreprocess = ColumnTransformer([\n    (\"num\", make_pipeline(SimpleImputer(strategy=\"median\"), StandardScaler()), numeric_cols),\n    (\"cat\", OneHotEncoder(handle_unknown=\"ignore\", min_frequency=20), categorical_cols),\n])\nmodel = make_pipeline(preprocess, SelectKBest(k=20), LogisticRegression(max_iter=1000))\nscores = cross_validate(model, X_train, y_train, cv=cv, scoring=\"average_precision\")\n```\n\n`cross_validate` refits the whole pipeline per fold, so imputation medians, category vocabularies and selected features are learned from that fold's training part only. Use `set_output(transform=\"pandas\")` when you need column names downstream.\n\n## 2. Encoders and resampling\n\n- **Target encoding:** scikit-learn's `TargetEncoder.fit_transform` uses internal cross-fitting; `fit(X, y).transform(X)` on the same rows does not and leaks the target. Inside a `Pipeline`, `fit` calls `fit_transform`, which is the safe path. Never compute per-category target means with a `groupby` over the full table.\n- **Frequency\u002Fcount encoding, aggregates, PCA, clustering features:** fitted transforms like any other — inside the pipeline.\n- **Class imbalance:** prefer `class_weight=\"balanced\"` or threshold tuning. Oversampling (SMOTE) goes inside an `imblearn.pipeline.Pipeline` only if the repository already depends on imbalanced-learn; oversampling before the split copies near-identical rows into validation.\n\n## 3. Time: only what was known at prediction time\n\nWhen rows are ordered in time, the split, the features and the label each respect it.\n\n```python\ncv = TimeSeriesSplit(n_splits=5, gap=horizon_rows)\n```\n\nPoint-in-time joins: attach the latest feature value strictly before the prediction timestamp.\n\n```python\n# ❌ joins the customer's current tier, which may have changed after the snapshot\ndf = snapshots.merge(customers[[\"customer_id\", \"tier\"]], on=\"customer_id\")\n\n# ✅ as-of join against the tier history (both frames sorted by the `on` key)\ndf = pd.merge_asof(\n    snapshots.sort_values(\"snapshot_ts\"),\n    tier_history.sort_values(\"changed_at\"),\n    left_on=\"snapshot_ts\", right_on=\"changed_at\",\n    by=\"customer_id\", direction=\"backward\", allow_exact_matches=False,\n)\n```\n\nRolling features exclude the current row and anything after it:\n\n```python\ndef spend_7d(events: pd.DataFrame) -> pd.Series:\n    events = events.sort_values([\"user_id\", \"ts\"])\n    rolled = (\n        events.set_index(\"ts\")\n        .groupby(\"user_id\")[\"amount\"]\n        .rolling(\"7D\", closed=\"left\")\n        .sum()\n        .fillna(0.0)\n    )\n    return pd.Series(rolled.to_numpy(), index=events.index, name=\"spend_7d\")\n```\n\nThe feature window ends before the label window starts; a label that becomes final 60 days later means the last 60 days of snapshots cannot be training rows yet.\n\n## 4. Groups: one entity, one side\n\nIf a user, patient, device or store appears in many rows, a random split puts the same entity in train and validation and the model memorises it.\n\n```python\ncv = StratifiedGroupKFold(n_splits=5, shuffle=True, random_state=seed)\ncross_validate(model, X, y, groups=df[\"user_id\"], cv=cv, scoring=\"average_precision\")\n```\n\nAlso deduplicate exact and near-exact rows before the split; duplicates across the split are the same leak in a different form.\n\n## 5. Guard tests\n\nA future-rows test pins the time logic:\n\n```python\ndef test_spend_7d_ignores_rows_after_prediction_time() -> None:\n    events = pd.DataFrame({\n        \"user_id\": [\"a\", \"a\", \"a\"],\n        \"ts\": pd.to_datetime([\"2026-01-01\", \"2026-01-03\", \"2026-01-05\"]),\n        \"amount\": [10.0, 20.0, 30.0],\n    })\n    later = pd.DataFrame({\"user_id\": [\"a\"], \"ts\": pd.to_datetime([\"2026-01-06\"]), \"amount\": [1e6]})\n\n    before = spend_7d(events)\n    after = spend_7d(pd.concat([events, later], ignore_index=True))\n\n    assert before.tolist() == [0.0, 10.0, 30.0]\n    pd.testing.assert_series_equal(after.loc[before.index], before)\n```\n\nA shuffled-label test catches leaks you did not think of: train the real pipeline on permuted labels with the real CV; the score must fall to the baseline. If it does not, something in the features encodes the row order, an ID or the label.\n\n```python\ndef test_pipeline_cannot_learn_shuffled_labels(train_fixture) -> None:\n    X, y = train_fixture\n    y_shuffled = np.random.default_rng(0).permutation(y)\n    score = cross_val_score(build_model(seed=0), X, y_shuffled, cv=5, scoring=\"roc_auc\").mean()\n    assert score \u003C 0.6\n```\n\n## 6. Training-serving parity\n\nThe fitted pipeline is the artifact. Serving calls `pipeline.predict` on the same raw columns training used — it never re-implements the preprocessing in SQL or in the API handler. A test feeds one fixture row through the batch path and the serving path and asserts identical output (model-serving-and-monitoring).\n\n## Common Mistakes\n\n- `fit_transform` on the full dataset \"just for scaling\".\n- Feature selection or hyperparameter search run on all rows, then cross-validated.\n- Aggregates (`user_total_spend`) computed over the whole history, including after the snapshot.\n- Random `KFold` on time-ordered or repeated-entity data.\n- `train_test_split` without `random_state`, so the split differs every run.\n\n## Red Flags\n\n- Validation score far above what the domain suggests is possible, or above the production score of the current system by a wide margin.\n- A single feature with near-perfect importance.\n- Validation much better than the most recent out-of-time period.\n- Preprocessing code that exists twice — once for training, once for serving.\n","# Leakage-Safe Feature Engineering\n\n## Overview\n\nLeakage is information in training that will not exist at prediction time. It produces a great offline score and a model that fails in production — and no test fails, because the code does exactly what it was told. The three sources: transforms fitted on rows they later score, features computed from the future, and the same entity on both sides of a split.\n\n**Core principle:** split first; everything that learns from data (scalers, imputers, encoders, selectors, resamplers) is fitted inside the training fold only — in practice, inside one scikit-learn `Pipeline` that is cross-validated and shipped as a single artifact.\n\n## 1. Fit inside the Pipeline, never before the split\n\n```python\n# ❌ the scaler and the selector have seen the test rows\nX_scaled = StandardScaler().fit_transform(X)\nX_sel = SelectKBest(k=20).fit_transform(X_scaled, y)\nX_train, X_test, y_train, y_test = train_test_split(X_sel, y)\n\n# ✅ split once, then everything learned lives in the pipeline\nX_train, X_test, y_train, y_test = train_test_split(\n    X, y, test_size=0.2, stratify=y, random_state=seed\n)\npreprocess = ColumnTransformer([\n    (\"num\", make_pipeline(SimpleImputer(strategy=\"median\"), StandardScaler()), numeric_cols),\n    (\"cat\", OneHotEncoder(handle_unknown=\"ignore\", min_frequency=20), categorical_cols),\n])\nmodel = make_pipeline(preprocess, SelectKBest(k=20), LogisticRegression(max_iter=1000))\nscores = cross_validate(model, X_train, y_train, cv=cv, scoring=\"average_precision\")\n```\n\n`cross_validate` refits the whole pipeline per fold, so imputation medians, category vocabularies and selected features are learned from that fold's training part only. Use `set_output(transform=\"pandas\")` when you need column names downstream.\n\n## 2. Encoders and resampling\n\n- **Target encoding:** scikit-learn's `TargetEncoder.fit_transform` uses internal cross-fitting; `fit(X, y).transform(X)` on the same rows does not and leaks the target. Inside a `Pipeline`, `fit` calls `fit_transform`, which is the safe path. Never compute per-category target means with a `groupby` over the full table.\n- **Frequency\u002Fcount encoding, aggregates, PCA, clustering features:** fitted transforms like any other — inside the pipeline.\n- **Class imbalance:** prefer `class_weight=\"balanced\"` or threshold tuning. Oversampling (SMOTE) goes inside an `imblearn.pipeline.Pipeline` only if the repository already depends on imbalanced-learn; oversampling before the split copies near-identical rows into validation.\n\n## 3. Time: only what was known at prediction time\n\nWhen rows are ordered in time, the split, the features and the label each respect it.\n\n```python\ncv = TimeSeriesSplit(n_splits=5, gap=horizon_rows)\n```\n\nPoint-in-time joins: attach the latest feature value strictly before the prediction timestamp.\n\n```python\n# ❌ joins the customer's current tier, which may have changed after the snapshot\ndf = snapshots.merge(customers[[\"customer_id\", \"tier\"]], on=\"customer_id\")\n\n# ✅ as-of join against the tier history (both frames sorted by the `on` key)\ndf = pd.merge_asof(\n    snapshots.sort_values(\"snapshot_ts\"),\n    tier_history.sort_values(\"changed_at\"),\n    left_on=\"snapshot_ts\", right_on=\"changed_at\",\n    by=\"customer_id\", direction=\"backward\", allow_exact_matches=False,\n)\n```\n\nRolling features exclude the current row and anything after it:\n\n```python\ndef spend_7d(events: pd.DataFrame) -> pd.Series:\n    events = events.sort_values([\"user_id\", \"ts\"])\n    rolled = (\n        events.set_index(\"ts\")\n        .groupby(\"user_id\")[\"amount\"]\n        .rolling(\"7D\", closed=\"left\")\n        .sum()\n        .fillna(0.0)\n    )\n    return pd.Series(rolled.to_numpy(), index=events.index, name=\"spend_7d\")\n```\n\nThe feature window ends before the label window starts; a label that becomes final 60 days later means the last 60 days of snapshots cannot be training rows yet.\n\n## 4. Groups: one entity, one side\n\nIf a user, patient, device or store appears in many rows, a random split puts the same entity in train and validation and the model memorises it.\n\n```python\ncv = StratifiedGroupKFold(n_splits=5, shuffle=True, random_state=seed)\ncross_validate(model, X, y, groups=df[\"user_id\"], cv=cv, scoring=\"average_precision\")\n```\n\nAlso deduplicate exact and near-exact rows before the split; duplicates across the split are the same leak in a different form.\n\n## 5. Guard tests\n\nA future-rows test pins the time logic:\n\n```python\ndef test_spend_7d_ignores_rows_after_prediction_time() -> None:\n    events = pd.DataFrame({\n        \"user_id\": [\"a\", \"a\", \"a\"],\n        \"ts\": pd.to_datetime([\"2026-01-01\", \"2026-01-03\", \"2026-01-05\"]),\n        \"amount\": [10.0, 20.0, 30.0],\n    })\n    later = pd.DataFrame({\"user_id\": [\"a\"], \"ts\": pd.to_datetime([\"2026-01-06\"]), \"amount\": [1e6]})\n\n    before = spend_7d(events)\n    after = spend_7d(pd.concat([events, later], ignore_index=True))\n\n    assert before.tolist() == [0.0, 10.0, 30.0]\n    pd.testing.assert_series_equal(after.loc[before.index], before)\n```\n\nA shuffled-label test catches leaks you did not think of: train the real pipeline on permuted labels with the real CV; the score must fall to the baseline. If it does not, something in the features encodes the row order, an ID or the label.\n\n```python\ndef test_pipeline_cannot_learn_shuffled_labels(train_fixture) -> None:\n    X, y = train_fixture\n    y_shuffled = np.random.default_rng(0).permutation(y)\n    score = cross_val_score(build_model(seed=0), X, y_shuffled, cv=5, scoring=\"roc_auc\").mean()\n    assert score \u003C 0.6\n```\n\n## 6. Training-serving parity\n\nThe fitted pipeline is the artifact. Serving calls `pipeline.predict` on the same raw columns training used — it never re-implements the preprocessing in SQL or in the API handler. A test feeds one fixture row through the batch path and the serving path and asserts identical output (model-serving-and-monitoring).\n\n## Common Mistakes\n\n- `fit_transform` on the full dataset \"just for scaling\".\n- Feature selection or hyperparameter search run on all rows, then cross-validated.\n- Aggregates (`user_total_spend`) computed over the whole history, including after the snapshot.\n- Random `KFold` on time-ordered or repeated-entity data.\n- `train_test_split` without `random_state`, so the split differs every run.\n\n## Red Flags\n\n- Validation score far above what the domain suggests is possible, or above the production score of the current system by a wide margin.\n- A single feature with near-perfect importance.\n- Validation much better than the most recent out-of-time period.\n- Preprocessing code that exists twice — once for training, once for serving.\n",{"name":5,"source":24,"category":25,"tech_stack":26,"description":7},"original; informed by scikit-learn Common pitfalls and recommended practices and the cross-validation user guide (cited, not reproduced)","ml","Python","main","910394a0b6db9fc8c9a8f36328ec421d3ebd8b38","catalog\u002Fagents\u002Fdata-scientist\u002Fskills\u002Fleakage-safe-feature-engineering",18,"https:\u002F\u002Fgithub.com\u002Fmakifbaysal\u002Ftasktrooper","https:\u002F\u002Ftasktrooper.ai","https:\u002F\u002Fgithub.com\u002Fmakifbaysal","Senior Software Developer","2026-11-15 04:50:29",{"source":8,"skillName":5,"commands":37,"prompt":47,"zipAvailable":48},[38,41,44],{"tool":39,"command":40},"npx","npx skills add makifbaysal\u002Ftasktrooper --skill leakage-safe-feature-engineering",{"tool":42,"command":43},"bunx","bunx skills add makifbaysal\u002Ftasktrooper --skill leakage-safe-feature-engineering",{"tool":45,"command":46},"pnpm","pnpm dlx skills add makifbaysal\u002Ftasktrooper --skill leakage-safe-feature-engineering","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fmakifbaysal\u002Ftasktrooper\u002Fblob\u002Fmain\u002Fcatalog\u002Fagents\u002Fdata-scientist\u002Fskills\u002Fleakage-safe-feature-engineering\u002FSKILL.md",true,[],[51,57,64,71,78,85],{"skillNo":52,"name":53,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":54,"categories":55,"keywords":56,"publishedAt":19},"01M7CSVEPQW6J6TD6CS2T5FPNZ","visual-craft","https:\u002F\u002Fgithub.com\u002Fmakifbaysal\u002Ftasktrooper\u002Fblob\u002Fmain\u002Fcatalog\u002Fagents\u002Fui-designer\u002Fskills\u002Fvisual-craft\u002FSKILL.md",[],[],{"skillNo":58,"name":59,"nameZh":6,"description":60,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":61,"categories":62,"keywords":63,"publishedAt":19},"01M7CSVAQG91ETHQ0HBNZDG5FR","ux-copy","Use when you write any words a user reads in a mockup or a hand-off - content language and voice, buttons, labels, errors, empty states, confirmations, numbers and dates, and the longest-string check","https:\u002F\u002Fgithub.com\u002Fmakifbaysal\u002Ftasktrooper\u002Fblob\u002Fmain\u002Fcatalog\u002Fagents\u002Fui-designer\u002Fskills\u002Fux-copy\u002FSKILL.md",[],[],{"skillNo":65,"name":66,"nameZh":6,"description":67,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":68,"categories":69,"keywords":70,"publishedAt":19},"01M7CSV6H0J38659NDXHJQ8396","screen-mockup-html","Use when you draw screens as the design task's HTML mockup - ONE canvas document holding every screen and every variant side by side, the sanitizer-safe recipe, phone and wide frames, the states grid, static control states, and the loopback self-check with screenshots at 375, 768 and 1440 attached to the task","https:\u002F\u002Fgithub.com\u002Fmakifbaysal\u002Ftasktrooper\u002Fblob\u002Fmain\u002Fcatalog\u002Fagents\u002Fui-designer\u002Fskills\u002Fscreen-mockup-html\u002FSKILL.md",[],[],{"skillNo":72,"name":73,"nameZh":6,"description":74,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":75,"categories":76,"keywords":77,"publishedAt":19},"01M7CSV3JFRF3BM3XK52M7YEYR","performance-awareness","How the performance score moves for your role. Use when the score context shows a declining trend, or before handing off work you have not self-checked against every criterion.","https:\u002F\u002Fgithub.com\u002Fmakifbaysal\u002Ftasktrooper\u002Fblob\u002Fmain\u002Fcatalog\u002Fagents\u002Fui-designer\u002Fskills\u002Fperformance-awareness\u002FSKILL.md",[],[],{"skillNo":79,"name":80,"nameZh":6,"description":81,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":82,"categories":83,"keywords":84,"publishedAt":19},"01M7CSTZDH00YRF5SCT7BRT9QD","design-variants","Use when a screen design needs variants - how many, variants as side-by-side rows on the one canvas, what makes two variants genuinely different, recommending one, how the human's choice is read, and narrowing to the chosen one in revision","https:\u002F\u002Fgithub.com\u002Fmakifbaysal\u002Ftasktrooper\u002Fblob\u002Fmain\u002Fcatalog\u002Fagents\u002Fui-designer\u002Fskills\u002Fdesign-variants\u002FSKILL.md",[],[],{"skillNo":86,"name":87,"nameZh":6,"description":88,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":89,"categories":90,"keywords":91,"publishedAt":19},"01M7CSTV6P3SM3PAE28DB0RF77","design-system-authoring","Use when you derive, change or extend a design system - where tokens live per stack, the DTCG token tree, role-based names for both themes, base vs layer vs drift, the DESIGN.md section order, the inventory format, the contrast check and the lint every proposal returns","https:\u002F\u002Fgithub.com\u002Fmakifbaysal\u002Ftasktrooper\u002Fblob\u002Fmain\u002Fcatalog\u002Fagents\u002Fui-designer\u002Fskills\u002Fdesign-system-authoring\u002FSKILL.md",[],[]]