agentleFS
G1JoshiG1Joshi/Agent-Skills/skills/ai-ml/scikit-learn/SKILL.md

scikit-learn

Skill15 starsChanged 43 days agoMITView on GitHub

Expert Scikit-Learn assistance covering classification, regression, clustering, pipelines, cross-validation, and preprocessing. Use when building classical machine learning models and feature engineering pipelines.

15 other projects use a version of this.

Adopted by

Most recently taken up by

Used with

Projects with it also use statsmodels and literature-review.

Other files people use alongside this one.

Files found in the same public projects as a version of this one, more often than they turn up anywhere else. Each project counts once, large collections count for less, and this file's own repository is left out.
  • tondevrelSkill

    statsmodels

    Advanced statistical modeling and hypothesis testing. Complementary to SciPy's stats module, it provides classes and functions for the estimation of many different statistical models, as well as for conducting statistical tests and statistical data exploration. Use for linear regression, GLM, time series analysis, ANOVA, survival analysis, causal inference, and statistical hypothesis testing. Load when working with OLS, WLS, logistic regression, Poisson regression, ARIMA, SARIMAX, statistical diagnostics, p-values, confidence intervals, or R-style statistical analysis.

    Also in 4 projects that use this

  • JDerekLomasSkill

    literature-review

    Conduct comprehensive, systematic literature reviews using multiple academic databases (PubMed, arXiv, bioRxiv, Semantic Scholar, etc.). This skill should be used when conducting systematic literature reviews, meta-analyses, research synthesis, or comprehensive literature searches across biomedical, scientific, and technical domains. Creates professionally formatted markdown documents and PDFs with verified citations in multiple citation styles (APA, Nature, Vancouver, etc.).

    Also in 3 projects that use this

The file

We split this skill into the rules it gives an agent

4 rules. 0 are common, 0 are distinctive, and 4 are very specific to this project.

  • 0

    Common

    Most of the 15 edited versions we read keep these.

  • 0

    Distinctive

    This author's own choices. Worth a look.

  • 4

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Very specific:

    Always use Pipeline and ColumnTransformer to prevent data leakage between training and validation sets.

    line 157
  2. Very specific:

    Use HistGradientBoostingClassifier / Regressor for tabular data.

    line 158
  3. Very specific:

    Use standard GridSearchCV on massive parameter grids.

    line 165
  4. Very specific:

    Use StandardScaler on sparse data without with_mean=False.

    line 166

“Common” is measured: kept by at least 6 in 10 of the 15 edited versions of this file we could read. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

Scikit-learn

Scikit-learn is the foundational Python library for classical machine learning, providing robust implementations of regression, classification, clustering, dimensionality reduction, and pipelines.

When to Use

  • Classical Machine Learning Algorithms: Linear models, decision trees, random forests, clustering, and dimensionality reduction.
  • End-to-End ML Pipelines: Constructing robust pipelines combining imputers, encoders, scalers, and estimators.
  • Cross-Validation & Hyperparameter Tuning: Stratified K-fold validation, GridSearchCV, and RandomizedSearchCV.
  • Model Evaluation & Diagnostic Metrics: Confusion matrices, ROC-AUC curves, precision-recall tradeoffs, and classification reports.

Quick Start

from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.datasets import load_breast_cancer

X, y = load_breast_cancer(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# Type-safe, leakage-free ML pipeline
pipe = Pipeline([
    ('scaler', StandardScaler()),
    ('classifier', LogisticRegression())
])

pipe.fit(X_train, y_train)
score = pipe.score(X_test, y_test)
print(f"Test Accuracy: {score:.4f}")

Core Concepts

Robust Pipeline with ColumnTransformer

Handling heterogeneous numeric and categorical columns without data leakage:

import numpy as np
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import Pipeline
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import StandardScaler, OneHotEncoder
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.model_selection import train_test_split

# Sample dataset
df = pd.DataFrame({
    'age': [25, 45, np.nan, 35, 52, 23],
    'income': [50000, 120000, 85000, 75000, np.nan, 42000],
    'department': ['sales', 'tech', 'marketing', 'tech', 'sales', 'tech'],
    'promoted': [0, 1, 1, 0, 1, 0]
})

X = df.drop(columns=['promoted'])
y = df['promoted']

numeric_features = ['age', 'income']
categorical_features = ['department']

numeric_transformer = Pipeline(steps=[
    ('imputer', SimpleImputer(strategy='median')),
    ('scaler', StandardScaler())
])

categorical_transformer = Pipeline(steps=[
    ('imputer', SimpleImputer(strategy='constant', fill_value='missing')),
    ('encoder', OneHotEncoder(handle_unknown='ignore', sparse_output=False))
])

preprocessor = ColumnTransformer(transformers=[
    ('num', numeric_transformer, numeric_features),
    ('cat', categorical_transformer, categorical_features)
])

# Full model pipeline
model_pipeline = Pipeline(steps=[
    ('preprocessor', preprocessor),
    ('classifier', HistGradientBoostingClassifier(random_state=42))
])

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=42)
model_pipeline.fit(X_train, y_train)
print("Test Score:", model_pipeline.score(X_test, y_test))

Cross-Validation & Metric Evaluation

Evaluating classification performance comprehensively:

from sklearn.model_selection import cross_val_score, StratifiedKFold
from sklearn.metrics import classification_report

cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
scores = cross_val_score(model_pipeline, X, y, cv=cv, scoring='accuracy')

print(f"5-Fold CV Accuracy: {scores.mean():.4f} (+/- {scores.std():.4f})")

Hyperparameter Search with HalvingGridSearchCV

Fast successive halving parameter search:

from sklearn.model_selection import HalvingGridSearchCV

param_grid = {
    'classifier__learning_rate': [0.01, 0.05, 0.1],
    'classifier__max_iter': [50, 100, 200]
}

search = HalvingGridSearchCV(model_pipeline, param_grid, cv=3, factor=2, random_state=42)
search.fit(X, y)
print("Best Parameters:", search.best_params_)

Common Patterns

ColumnTransformer for Heterogeneous Feature Types

Problem: Applying separate preprocessing (scaling to numericals, one-hot encoding to categoricals) without data leakage.

Solution: Use ColumnTransformer:

from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import OneHotEncoder, StandardScaler

preprocessor = ColumnTransformer(
    transformers=[
        ('num', StandardScaler(), ['age', 'income', 'balance']),
        ('cat', OneHotEncoder(handle_unknown='ignore'), ['occupation', 'city'])
    ]
)

pipeline = Pipeline([
    ('prep', preprocessor),
    ('model', LogisticRegression())
])

Best Practices

Do:

  • Always use Pipeline and ColumnTransformer to prevent data leakage between training and validation sets.
  • Use HistGradientBoostingClassifier / Regressor for tabular data; it is much faster than GradientBoostingClassifier.
  • Set sparse_output=False in OneHotEncoder when piping into estimators that expect dense NumPy arrays.
  • Evaluate models using appropriate metrics (e.g. roc_auc, f1_weighted, brier_score_loss) for imbalanced datasets.

Don't:

  • Fit transformers on the entire dataset before splitting into train/test; always fit only on X_train.
  • Use standard GridSearchCV on massive parameter grids; use HalvingGridSearchCV or Optuna.
  • Use StandardScaler on sparse data without with_mean=False.

Troubleshooting

ErrorCauseSolution
ValueError: Input contains NaN, infinity or a value too largeMissing values in features array before model training.Add SimpleImputer() step to pipeline before modeling.
DataConversionWarning: A column-vector y was passedTarget label passed with shape (n, 1) instead of 1D (n,).Call .ravel() on target array: y.ravel().
Data leakage during cross-validationScaler fit on entire dataset before train/test splitting.Always fit transformers inside an sklearn.pipeline.Pipeline.

References

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.