Skip to main content
rulesSource-backedReview first Safety · Privacy ·

Python Data Science Expert - CLAUDE.md Rules for Claude Code

scikit-learn ML modeling rule that audits for data leakage, enforces Pipeline-based preprocessing, and validates cross-validation rigor (StratifiedKFold, GroupKFold, TimeSeriesSplit) for defensible model evaluation

by JSONbored·added 2025-09-15·
HarnessClaude Code
Review first review before installing

Open the source and read safety notes before installing.

Citation facts

Source-backed facts for citing this resource, derived directly from the registry — also available as plain text for AI assistants.

Source URLs
https://scikit-learn.org/stable/common_pitfalls.html, https://github.com/JSONbored/awesome-claude/blob/main/content/rules/python-data-science-expert.mdx
Author
JSONbored
Claim status
unclaimed
Last verified
2025-09-15

Decision playbook

Review trust signals before you adopt

Signals are present but mixed. Use the checklist below to confirm the source and operational safety for your environment.

Required checks are still incomplete. Finish source and safety verification before adopting this resource.

Compare context
Selected

0

Current score

58

Baseline

Delta

No baseline selected

No major trust-signal divergence detected in the current selection.

Source and provenance checks

Complete

Confirm ownership and provenance before trusting install instructions.

  • Source link availableRequired

    Open the canonical repository and verify ownership.

    Done
  • Source provenance statusRequired

    Marked as source-backed.

    Done
  • Metadata reviewed

    Registry metadata indicates a reviewed listing.

    Done

Safety and privacy checks

Required checks missing

Validate risk disclosures before installation or API wiring.

  • Safety notes presentRequired

    No safety notes listed.

    Pending
  • Privacy notes presentRequired

    No privacy notes listed.

    Pending
  • Trust level risk gateRequired

    Trust level does not block evaluation.

    Done

Package and install checks

Needs review

Check package metadata and artifact integrity signals.

  • Install payload available

    Install or copy payload is available for review.

    Done
  • Package verification flag

    No package verification flag provided.

    Pending
  • Checksum metadata

    No checksum provided for downloaded artifact.

    Pending

Compare-driven decision checks

Needs review

Use compare context to validate trade-offs before adoption.

  • Compare tray has multiple entries

    Add at least one more entry to compare trust differences.

    Pending
  • Baseline comparison available

    No baseline peer selected yet.

    Pending
  • Diverging trust signals identified

    No major trust-signal divergence found.

    Pending

Setup at a glance

Copy & paste

Copy-ready — paste the snippet to get started.

Install command

Not provided

Config snippet

Not provided

Copy snippet

Provided

Prerequisites

None

Platforms

1 listed

Difficulty

4/100

Adoption plan

Balanced adoption plan

Current risk score 44/100. Use staged verification before broader rollout.

Risk 44
Adoption blockers
  • Safety notes are missing.
  • Privacy notes are missing.

Pre-adoption checks

Validate source and review signals before any execution.

  • Confirm source provenanceRequired

    Source URL/provenance metadata is present.

    Done
  • Confirm metadata review state

    Listing has review metadata.

    Done
  • Verify install payload

    Install/config payload exists and can be inspected.

    Done

Security checks

Confirm safety, privacy, and package integrity signals.

  • Review safety notesRequired

    Safety notes missing; review source code paths before execution.

    Pending
  • Review privacy notesRequired

    Privacy notes missing; inspect network/data behavior manually.

    Pending
  • Verify package integrity metadata

    No package verification/checksum metadata.

    Pending

Rollout

Adopt in controlled steps based on the selected plan.

  • Run in isolated sandbox firstRequired

    Use a constrained sandbox and observe behavior across multiple tasks.

    Pending
  • Roll out graduallyRequired

    Roll out to a small cohort before wider usage.

    Pending
  • Set monitoring and fallback

    Define rollback path and monitor errors after adoption.

    Pending

Evidence readiness

Evidence readiness matrix · balanced

Missing required evidence: Safety notes. Risk score 36.

Risk 36

Source provenance

Present

Source repository/provenance is listed.

Required in this preset

Metadata review

Present

Review metadata is present.

Required in this preset

Safety notes

Missing

Safety notes are missing.

Required in this preset

Privacy notes

Missing

Privacy notes are missing.

Optional in this preset

Package integrity

Missing

Package integrity metadata is missing.

Optional in this preset

Install payload

Present

Install payload is available.

Required in this preset

Required gaps: Safety notes

Decision timeline

Decision timeline · balanced

Blocking gaps: Review safety notes. Risk 32.

Risk 32

triage

Confirm source provenanceRequired

Source/provenance metadata is available.

Done

triage

Check metadata review statusRequired

Review metadata is available.

Done

verify

Review safety notesRequired

Safety notes are missing.

Pending

verify

Review privacy notes

Privacy notes are missing.

Pending

verify

Validate package integrity metadata

Package integrity metadata is missing.

Pending

rollout

Verify install payload and commandsRequired

Install payload is available.

Done

Blockers: Review safety notes

Schema details

Install type
copy
Reading time
2 min
Difficulty score
4
Troubleshooting
Yes
Breaking changes
No
Skill and platform metadata
Retrieval sources
https://scikit-learn.org/stable/common_pitfalls.htmlhttps://scikit-learn.org/stable/modules/cross_validation.htmlhttps://scikit-learn.org/stable/modules/generated/sklearn.pipeline.make_pipeline.html
Full copyable content
You are a rigorous scikit-learn ML modeling critic. For every estimator, preprocessing step, or evaluation: audit for data leakage, enforce Pipeline-based preprocessing, and validate that the cross-validation strategy matches the data structure. Never accept code that fits a transformer on the full dataset before splitting.

## The Cardinal Rule
- Never call fit or fit_transform on test data — only transform it
- Fit transformers (scalers, imputers, feature selectors) on the training set
  only

- Wrap preprocessing and the estimator in a single Pipeline so leakage cannot
  happen by accident


## Pipeline-First Preprocessing
- Use make_pipeline(StandardScaler(), SelectKBest(...), Estimator) instead of
  transforming data by hand

- Inside cross_val_score / cross_validate, a Pipeline refits every transformer
  per fold automatically

- Reject SelectKBest().fit_transform(X, y) or StandardScaler().fit(X) before
  train_test_split — both leak test information


## Cross-Validation Strategy
- Integer cv uses StratifiedKFold for classifiers (preserves class balance) and
  KFold otherwise

- Use GroupKFold / StratifiedGroupKFold when samples share a group that must not
  span train and test

- Use TimeSeriesSplit for temporal data so the model never trains on the future
- Report mean and standard deviation across folds, not a single holdout score
- Use cross_validate when you need multiple metrics or the fitted estimators

## Reproducibility
- Pass random_state explicitly to estimators, CV splitters, and train_test_split
- Pass an integer random_state to CV splitters so every estimator sees identical
  splits

- Prefer explicit random_state over np.random.seed(0)

About this resource

You are a rigorous scikit-learn ML modeling critic. For every estimator, preprocessing step, or evaluation you review: audit for data leakage, enforce Pipeline-based preprocessing, and validate that cross-validation matches the data structure. This rule covers ML modeling and evaluation with scikit-learn; for DataFrame cleaning and reshaping, see the pandas-focused python-data-science rule.

The Cardinal Rule

scikit-learn's own guidance is blunt: never call fit on the test data. Any transformer (scaler, feature selector, imputer) must learn its parameters from the training set only, then transform held-out data. Fitting on the full dataset before splitting leaks test information and produces optimistic scores.

Pipeline-First Preprocessing

Wrap preprocessing and the estimator in a single Pipeline so leakage cannot happen by accident. The pipeline refits every transformer on each cross-validation training fold automatically.

from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.feature_selection import SelectKBest
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.model_selection import train_test_split, cross_val_score

X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)

# Preprocessing lives INSIDE the pipeline — fit only on train, applied to test.
pipeline = make_pipeline(
    StandardScaler(),
    SelectKBest(k=25),
    HistGradientBoostingClassifier(random_state=1),
)
pipeline.fit(X_train, y_train)

# cross_val_score refits the whole pipeline per fold — no leakage across folds.
# An integer cv uses StratifiedKFold for classifiers (preserves class balance).
scores = cross_val_score(pipeline, X, y, cv=5)
print(f"Accuracy: {scores.mean():.2f} +/- {scores.std():.2f}")

Contrast with the leaky anti-pattern scikit-learn warns against: calling SelectKBest(k=25).fit_transform(X, y) or StandardScaler().fit(X) on the full matrix before train_test_split lets test rows influence feature selection and scaling, inflating the reported score.

Common Pitfalls and Fixes

Pitfall Wrong Fix
Inconsistent preprocessing scaler.fit_transform(X_train) then predict on raw X_test Call scaler.transform(X_test), or wrap in a Pipeline
Leakage during feature selection SelectKBest().fit_transform(X, y) before the split Split first, fit_transform on train, transform on test (or use a Pipeline)
Leakage in cross-validation Preprocessing fit on full X, then cross_val_score Put preprocessing in a Pipeline so it refits per fold
Wrong CV for classification Plain KFold on imbalanced classes StratifiedKFold (the default when cv is an int and the estimator is a classifier)
Grouped/dependent samples KFold leaks the same group across train/test GroupKFold / StratifiedGroupKFold so a group never spans both sides
Time-series ordering Shuffled KFold trains on the future TimeSeriesSplit — successive training sets are supersets of earlier ones
Non-comparable CV splits KFold(random_state=np.random.RandomState(0)) Pass an integer random_state so every estimator sees identical splits
Hidden reproducibility np.random.seed(0) Pass random_state explicitly to estimators, splitters, and train_test_split

Evaluation Rigor

  • Use cross_val_score for a single metric; use cross_validate when you need multiple metrics, fit/score times, or the fitted estimators back.
  • Report the mean and standard deviation across folds, not a single holdout number.
  • Choose the splitter to match the data's structure (stratified for class balance, grouped for dependent samples, time-ordered for temporal data) — the wrong splitter silently leaks and overstates performance.

Critical Analysis Stance

Use this rule when Claude should act as a critical reviewer of scikit-learn modeling code rather than a code generator — surfacing leakage risks, fixing the CV strategy, and demanding Pipeline-encapsulated preprocessing with explicit random_state reproducibility.

Source citations

Add this badge to your README

Show that Python Data Science Expert - CLAUDE.md Rules for Claude Code is listed on HeyClaude. Paste this Markdown into your README — it renders the badge and links back to this page.

Listed on HeyClaude
[![Listed on HeyClaude](https://heyclau.de/badge/rules/python-data-science-expert.svg)](https://heyclau.de/entry/rules/python-data-science-expert)

How it compares

Python Data Science Expert - CLAUDE.md Rules for Claude Code side by side with 3 alternatives on trust, install, platform support, and disclosed safety notes — all from reviewed registry metadata.

1 trust signal differ across this comparison (Submitter).

Field

scikit-learn ML modeling rule that audits for data leakage, enforces Pipeline-based preprocessing, and validates cross-validation rigor (StratifiedKFold, GroupKFold, TimeSeriesSplit) for defensible model evaluation

Open dossier

Turn Claude into a practical pandas data-wrangling partner for loading, cleaning, reshaping, and aggregating tabular data with the pandas DataFrame API

Open dossier

Comprehensive code review rules for thorough analysis and constructive feedback

Open dossier

Transform Claude into a Django specialist with deep knowledge of models, views, DRF serializers, migrations, middleware, and production deployment patterns.

Open dossier
Next steps
Trust
Review statusReviewedMaintainer reviewedReviewedMaintainer reviewedReviewedMaintainer reviewedReviewedMaintainer reviewed
Package trustPackage not verifiedPackage not verifiedPackage not verifiedPackage not verified
Source provenanceSource-backedSource-backedSource-backedSource-backed
SubmitterDiffersjaso0n0818
Install riskReview firstReview firstReview firstReview first
Notes Safety · Privacy · Safety Privacy · Safety · Privacy Safety Privacy
Brand
Categoryrulesrulesrulesrules
Sourcesource-backedsource-backedsource-backedsource-backed
AuthorJSONboredJSONboredJSONboredjaso0n0818
Added2025-09-152025-09-152025-09-162026-06-14
Platforms
Claude Code
Claude Code
Claude Code
Claude Code
Source repo
Safety notes— missingThese are advisory pandas data-wrangling rules applied to your code; review any data-loading or file-writing operations (read_csv/to_csv) against untrusted paths before running.— missingThese are advisory Django coding rules applied to your project; review migrations, ORM queries, and on_delete cascade choices before running them against a real database.
Privacy notes— missing— missingCode review reads source diffs that may contain secrets or proprietary code; keep credentials and sensitive snippets out of review comments and shared logs.Rules reference SECRET_KEY, database credentials, and API tokens; store them in environment variables, never in settings.py committed to git.
Prerequisites— none listed— none listed— none listed— none listed
Install
Config
Citations
ClaimUnclaimedUnclaimedUnclaimedUnclaimed
Open 4 picks in the interactive comparison tool

Related guides

Signals

Loading live community signals…

More like this, weekly

A short, calm digest of reviewed Claude resources. Unsubscribe any time.