Claude Code for scikit-learn: Classical Machine Learning — Claude Skills 360 Blog
Blog / AI / Claude Code for scikit-learn: Classical Machine Learning
AI

Claude Code for scikit-learn: Classical Machine Learning

Published: November 3, 2027
Read time: 5 min read
By: Claude Skills 360

scikit-learn provides a complete, consistent API for classical machine learning. pip install scikit-learn. from sklearn.pipeline import Pipeline. Build: pipe = Pipeline([("scaler", StandardScaler()), ("clf", RandomForestClassifier())]). Fit: pipe.fit(X_train, y_train), predict: pipe.predict(X_test). ColumnTransformer: from sklearn.compose import ColumnTransformer, ct = ColumnTransformer([("num", StandardScaler(), num_cols), ("cat", OneHotEncoder(handle_unknown="ignore"), cat_cols)]). Impute: SimpleImputer(strategy="median") — “mean”, “most_frequent”, “constant”. Evaluate: cross_val_score(pipe, X, y, cv=5, scoring="roc_auc"). Tune: GridSearchCV(pipe, param_grid={"clf__n_estimators":[100,200]}, cv=5, n_jobs=-1), RandomizedSearchCV(pipe, param_distributions, n_iter=50, cv=5). Metrics: classification_report(y_test, y_pred), confusion_matrix, roc_auc_score(y_test, probs). Feature selection: SelectFromModel(RandomForestClassifier(), threshold="mean"), RFECV(estimator, cv=5, scoring="roc_auc"). Persist: joblib.dump(pipe, "model.pkl"), joblib.load("model.pkl"). Key estimators: LogisticRegression(C=1, max_iter=1000), SVC(C=1, kernel="rbf", probability=True), RandomForestClassifier(n_estimators=200), GradientBoostingClassifier(n_estimators=200, max_depth=3), KNeighborsClassifier(n_neighbors=5). Calibration: CalibratedClassifierCV(base_clf, cv=5) for reliable probabilities. VotingClassifier and StackingClassifier for ensembles. Claude Code generates sklearn pipelines, preprocessing workflows, hyperparameter search scripts, and model evaluation frameworks.

CLAUDE.md for scikit-learn

## scikit-learn Stack
- Version: scikit-learn >= 1.4
- Pipeline: Pipeline([("name", transform), ..., ("model", estimator)])
- Preprocessing: ColumnTransformer([("name", transformer, columns)])
- Numeric: StandardScaler | MinMaxScaler | RobustScaler | PowerTransformer
- Categorical: OneHotEncoder(handle_unknown="ignore") | OrdinalEncoder
- Impute: SimpleImputer(strategy="median") | KNNImputer(n_neighbors=5)
- Evaluate: cross_val_score(pipe, X, y, cv=5, scoring="roc_auc", n_jobs=-1)
- Tune: GridSearchCV | RandomizedSearchCV | HalvingRandomSearchCV
- Persist: joblib.dump(pipe, path) | joblib.load(path)

scikit-learn ML Pipeline

# ml/sklearn_pipeline.py — complete ML pipeline with scikit-learn
from __future__ import annotations
import warnings
import numpy as np
import pandas as pd
from pathlib import Path

import joblib
from sklearn.pipeline import Pipeline, FeatureUnion
from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import (
    StandardScaler, MinMaxScaler, RobustScaler,
    OneHotEncoder, OrdinalEncoder, LabelEncoder,
    PowerTransformer, PolynomialFeatures,
)
from sklearn.impute import SimpleImputer, KNNImputer
from sklearn.feature_selection import SelectFromModel, RFECV, VarianceThreshold
from sklearn.model_selection import (
    cross_val_score, cross_validate, GridSearchCV,
    RandomizedSearchCV, StratifiedKFold, train_test_split,
)
from sklearn.metrics import (
    classification_report, confusion_matrix,
    roc_auc_score, average_precision_score,
    mean_squared_error, mean_absolute_error, r2_score,
)
from sklearn.ensemble import (
    RandomForestClassifier, RandomForestRegressor,
    GradientBoostingClassifier, GradientBoostingRegressor,
    VotingClassifier, StackingClassifier,
)
from sklearn.linear_model import (
    LogisticRegression, Ridge, Lasso, ElasticNet,
)
from sklearn.svm import SVC, SVR
from sklearn.calibration import CalibratedClassifierCV


# ── 1. Preprocessing builder ──────────────────────────────────────────────────

def build_preprocessor(
    num_cols:         list[str],
    cat_cols:         list[str],
    strategy_numeric: str  = "median",
    scaler:           str  = "standard",      # "standard" | "robust" | "minmax" | "power"
    cat_strategy:     str  = "onehot",        # "onehot" | "ordinal"
    add_poly:         bool = False,
    poly_degree:      int  = 2,
) -> ColumnTransformer:
    """
    Build a ColumnTransformer that handles numeric and categorical columns separately.
    
    scaler choices:
    - standard: assumes Gaussian, zero-mean unit-variance
    - robust:   better for outlier-heavy features (uses IQR)
    - minmax:   preserves 0 range (e.g. for SVM, KNN)
    - power:    Box-Cox/Yeo-Johnson for skewed distributions
    """
    scaler_map = {
        "standard": StandardScaler(),
        "robust":   RobustScaler(),
        "minmax":   MinMaxScaler(),
        "power":    PowerTransformer(method="yeo-johnson"),
    }
    chosen_scaler = scaler_map[scaler]

    numeric_steps = [
        ("imputer", SimpleImputer(strategy=strategy_numeric)),
        ("scaler",  chosen_scaler),
    ]
    if add_poly:
        numeric_steps.append(("poly", PolynomialFeatures(degree=poly_degree, include_bias=False)))

    numeric_pipe = Pipeline(numeric_steps)

    if cat_strategy == "onehot":
        cat_encoder = OneHotEncoder(handle_unknown="ignore", sparse_output=False)
    else:
        cat_encoder = OrdinalEncoder(handle_unknown="use_encoded_value", unknown_value=-1)

    categorical_pipe = Pipeline([
        ("imputer", SimpleImputer(strategy="most_frequent")),
        ("encoder", cat_encoder),
    ])

    transformers = []
    if num_cols:
        transformers.append(("numeric", numeric_pipe, num_cols))
    if cat_cols:
        transformers.append(("categorical", categorical_pipe, cat_cols))

    return ColumnTransformer(transformers, remainder="drop")


# ── 2. Pipeline builder ───────────────────────────────────────────────────────

def build_pipeline(
    preprocessor,
    model_type:  str = "rf",      # "lr" | "rf" | "gbm" | "svm" | "knn"
    **model_kwargs,
) -> Pipeline:
    """
    Assemble a full preprocessing + model Pipeline.
    
    model_type:
    - lr:  LogisticRegression (baseline, fast)
    - rf:  RandomForestClassifier (strong default)
    - gbm: GradientBoostingClassifier (accurate, slow training)
    - svm: SVC with scaling (good for small datasets)
    """
    model_map = {
        "lr":  LogisticRegression(max_iter=1000, random_state=42, **model_kwargs),
        "rf":  RandomForestClassifier(n_estimators=200, random_state=42, **model_kwargs),
        "gbm": GradientBoostingClassifier(n_estimators=200, max_depth=4,
                                           learning_rate=0.05, random_state=42, **model_kwargs),
        "svm": CalibratedClassifierCV(SVC(kernel="rbf", probability=False), cv=3),
    }
    model = model_map.get(model_type, model_map["rf"])

    return Pipeline([
        ("preprocessor", preprocessor),
        ("model", model),
    ])


# ── 3. Model evaluation ───────────────────────────────────────────────────────

def evaluate(
    pipeline,
    X_test: pd.DataFrame | np.ndarray,
    y_test: np.ndarray,
    task:   str = "classification",
) -> dict:
    """Evaluate pipeline on held-out test data."""
    if task == "classification":
        y_pred = pipeline.predict(X_test)
        try:
            y_proba = pipeline.predict_proba(X_test)[:, 1]
        except AttributeError:
            y_proba = pipeline.decision_function(X_test)

        report = classification_report(y_test, y_pred, output_dict=True)
        return {
            "accuracy":  round(report["accuracy"], 4),
            "f1_macro":  round(report["macro avg"]["f1-score"], 4),
            "roc_auc":   round(roc_auc_score(y_test, y_proba), 4),
            "avg_prec":  round(average_precision_score(y_test, y_proba), 4),
        }
    else:
        y_pred = pipeline.predict(X_test)
        return {
            "rmse": round(np.sqrt(mean_squared_error(y_test, y_pred)), 4),
            "mae":  round(mean_absolute_error(y_test, y_pred), 4),
            "r2":   round(r2_score(y_test, y_pred), 4),
        }


def cross_validate_pipeline(
    pipeline,
    X:       pd.DataFrame | np.ndarray,
    y:       np.ndarray,
    cv:      int = 5,
    scoring: str = "roc_auc",
    n_jobs:  int = -1,
) -> dict:
    """Run stratified k-fold cross-validation."""
    scores = cross_val_score(pipeline, X, y, cv=cv, scoring=scoring, n_jobs=n_jobs)
    print(f"CV {scoring}: {scores.mean():.4f} ± {scores.std():.4f}")
    return {"mean": round(float(scores.mean()), 4), "std": round(float(scores.std()), 4)}


# ── 4. Hyperparameter search ──────────────────────────────────────────────────

def grid_search(
    pipeline,
    param_grid: dict,
    X_train: np.ndarray,
    y_train: np.ndarray,
    cv:      int = 5,
    scoring: str = "roc_auc",
    n_jobs:  int = -1,
    verbose: int = 1,
) -> GridSearchCV:
    """
    Exhaustive grid search over param_grid.
    param_grid keys use double underscore for nested params:
    {"model__n_estimators": [100, 200], "preprocessor__numeric__scaler__with_std": [True, False]}
    """
    gs = GridSearchCV(
        pipeline, param_grid, cv=cv, scoring=scoring,
        n_jobs=n_jobs, verbose=verbose, refit=True,
    )
    gs.fit(X_train, y_train)
    print(f"Best {scoring}: {gs.best_score_:.4f}")
    print(f"Best params: {gs.best_params_}")
    return gs


def random_search(
    pipeline,
    param_distributions: dict,
    X_train: np.ndarray,
    y_train: np.ndarray,
    n_iter:  int = 50,
    cv:      int = 5,
    scoring: str = "roc_auc",
    n_jobs:  int = -1,
) -> RandomizedSearchCV:
    """Randomized hyperparameter search — faster than GridSearch for large spaces."""
    rs = RandomizedSearchCV(
        pipeline, param_distributions,
        n_iter=n_iter, cv=cv, scoring=scoring,
        n_jobs=n_jobs, random_state=42, verbose=1, refit=True,
    )
    rs.fit(X_train, y_train)
    print(f"Best {scoring}: {rs.best_score_:.4f}")
    return rs


# ── 5. Feature selection ──────────────────────────────────────────────────────

def select_features_rfecv(
    X_train: np.ndarray,
    y_train: np.ndarray,
    estimator = None,
    cv:      int = 5,
    scoring: str = "roc_auc",
    min_features: int = 1,
) -> tuple[np.ndarray, list[int]]:
    """
    Recursive Feature Elimination with CV to find optimal feature count.
    Returns X_train with only selected features, and selected indices.
    """
    if estimator is None:
        estimator = RandomForestClassifier(n_estimators=100, random_state=42)

    selector = RFECV(estimator, cv=cv, scoring=scoring, min_features_to_select=min_features, n_jobs=-1)
    X_selected = selector.fit_transform(X_train, y_train)
    selected   = selector.get_support(indices=True).tolist()
    print(f"Features selected: {len(selected)} / {X_train.shape[1]}")
    return X_selected, selected


# ── 6. Ensemble methods ───────────────────────────────────────────────────────

def build_voting_ensemble(
    models: list[tuple[str, object]],
    voting: str = "soft",  # "hard" | "soft" (soft requires predict_proba)
) -> VotingClassifier:
    """Build a VotingClassifier from a list of (name, estimator) tuples."""
    return VotingClassifier(estimators=models, voting=voting, n_jobs=-1)


def build_stacking_ensemble(
    base_models:  list[tuple[str, object]],
    final_model = None,
    cv:           int = 5,
    stack_method: str = "predict_proba",
) -> StackingClassifier:
    """
    Stacking: base models generate out-of-fold predictions as features
    for the final estimator (meta-learner).
    """
    if final_model is None:
        final_model = LogisticRegression(max_iter=1000)
    return StackingClassifier(
        estimators=base_models,
        final_estimator=final_model,
        cv=cv,
        stack_method=stack_method,
        n_jobs=-1,
    )


# ── 7. Persistence ────────────────────────────────────────────────────────────

def save_pipeline(pipeline, path: str) -> None:
    joblib.dump(pipeline, path, compress=3)
    size = Path(path).stat().st_size / 1024
    print(f"Saved: {path} ({size:.0f} KB)")


def load_pipeline(path: str):
    return joblib.load(path)


# ── Demo ──────────────────────────────────────────────────────────────────────

if __name__ == "__main__":
    from sklearn.datasets import make_classification
    from scipy.stats import randint, uniform

    print("scikit-learn Pipeline Demo")
    print("="*50)

    # Create synthetic tabular data
    n = 5_000
    rng = np.random.default_rng(42)
    df = pd.DataFrame({
        "age":       rng.integers(18, 80, n).astype(float),
        "income":    rng.normal(50_000, 20_000, n),
        "score":     rng.uniform(0, 1, n),
        "city":      rng.choice(["NYC", "LA", "Chicago", "Miami"], n),
        "education": rng.choice(["high_school", "bachelor", "master", "phd"], n),
    })
    # Add some missing values
    for col in ["age", "income"]:
        mask = rng.random(n) < 0.05
        df.loc[mask, col] = np.nan

    y = (df["income"].fillna(50000) > 55000).astype(int).values
    X = df

    X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.2, stratify=y, random_state=42)

    num_cols = ["age", "income", "score"]
    cat_cols = ["city", "education"]

    # Build and train
    preprocessor = build_preprocessor(num_cols, cat_cols, scaler="robust")
    pipeline     = build_pipeline(preprocessor, model_type="rf")
    pipeline.fit(X_tr, y_tr)

    # Evaluate
    metrics = evaluate(pipeline, X_te, y_te)
    print(f"\nTest metrics: {metrics}")

    # Cross-validate
    cross_validate_pipeline(pipeline, X, y, cv=5, scoring="roc_auc")

    # Random search
    param_dist = {
        "model__n_estimators": randint(100, 400),
        "model__max_depth":    randint(3, 15),
        "model__min_samples_split": randint(2, 20),
    }
    rs = random_search(pipeline, param_dist, X_tr, y_tr, n_iter=10, cv=3)
    best_metrics = evaluate(rs.best_estimator_, X_te, y_te)
    print(f"\nTuned metrics: {best_metrics}")

    save_pipeline(rs.best_estimator_, "/tmp/sklearn_model.pkl")
    loaded = load_pipeline("/tmp/sklearn_model.pkl")
    print(f"Loaded model predicts: {loaded.predict(X_te[:3])}")

For the XGBoost/LightGBM alternative when optimizing for raw predictive performance on large tabular datasets — gradient boosting outperforms Random Forest on most tabular benchmarks while scikit-learn’s Pipeline + ColumnTransformer provides the gold-standard API for reproducible preprocessing that prevents data leakage (all transforms fitted on train, applied to test), and sklearn’s GridSearchCV with n_jobs=-1 and cross_validate with multiple scoring metrics give the complete model selection infrastructure that XGBoost’s native API lacks. For the statsmodels alternative when needing statistical inference with p-values, confidence intervals, and diagnostic plots for linear models — statsmodels excels at inference while sklearn’s consistent fit/predict/score API across 50+ estimators enables model comparison in a single for estimator in models loop, and the StackingClassifier meta-learner for combining heterogeneous models (RF + LR + SVM) consistently outperforms any single model on structured prediction tasks in production. The Claude Skills 360 bundle includes scikit-learn skill sets covering Pipeline and ColumnTransformer preprocessing, numeric and categorical transformers, imputation strategies, cross-validation, GridSearchCV and RandomizedSearchCV, feature selection with RFECV, VotingClassifier and StackingClassifier ensembles, and joblib persistence. Start with the free tier to try ML pipeline code generation.

Keep Reading

AI

Claude Code for email.contentmanager: Python Email Content Accessors

Read and write EmailMessage body content with Python's email.contentmanager module and Claude Code — email contentmanager ContentManager for the class that maps content types to get and set handler functions allowing EmailMessage to support get_content and set_content with type-specific behaviour, email contentmanager raw_data_manager for the ContentManager instance that handles raw bytes and str payloads without any conversion, email contentmanager content_manager for the standard ContentManager instance used by email.policy.default that intelligently handles text plain text html multipart and binary content types, email contentmanager get_content_text for the handler that returns the decoded text payload of a text-star message part as a str, email contentmanager get_content_binary for the handler that returns the raw decoded bytes payload of a non-text message part, email contentmanager get_data_manager for the get-handler lookup used by EmailMessage get_content to find the right reader function for the content type, email contentmanager set_content text for the handler that creates and sets a text part correctly choosing charset and transfer encoding, email contentmanager set_content bytes for the handler that creates and sets a binary part with base64 encoding and optional filename Content-Disposition, email contentmanager EmailMessage get_content for the method that reads the message body using the registered content manager handlers, email contentmanager EmailMessage set_content for the method that sets the message body and MIME headers in one call, email contentmanager EmailMessage make_alternative make_mixed make_related for the methods that convert a simple message into a multipart container, email contentmanager EmailMessage add_attachment for the method that attaches a file or bytes to a multipart message, and email contentmanager integration with email.message and email.policy and email.mime and io for building high-level email readers attachment extractors text body accessors HTML readers and policy-aware MIME construction pipelines.

5 min read Feb 12, 2029
AI

Claude Code for email.charset: Python Email Charset Encoding

Control header and body encoding for international email with Python's email.charset module and Claude Code — email charset Charset for the class that wraps a character set name with the encoding rules for header encoding and body encoding describing how to encode text for that charset in email messages, email charset Charset header_encoding for the attribute specifying whether headers using this charset should use QP quoted-printable encoding BASE64 encoding or no encoding, email charset Charset body_encoding for the attribute specifying the Content-Transfer-Encoding to use for message bodies in this charset such as QP or BASE64, email charset Charset output_codec for the attribute giving the Python codec name used to encode the string to bytes for the wire format, email charset Charset input_codec for the attribute giving the Python codec name used to decode incoming bytes to str, email charset Charset get_output_charset for returning the output charset name, email charset Charset header_encode for encoding a header string using the charset's header_encoding method, email charset Charset body_encode for encoding body content using the charset's body_encoding, email charset Charset convert for converting a string from the input_codec to the output_codec, email charset add_charset for registering a new charset with custom encoding rules in the global charset registry, email charset add_alias for adding an alias name that maps to an existing registered charset, email charset add_codec for registering a codec name mapping for use by the charset machinery, and email charset integration with email.message and email.mime and email.policy and email.encoders for building international email senders non-ASCII header encoders Content-Transfer-Encoding selectors charset-aware message constructors and MIME encoding pipelines.

5 min read Feb 11, 2029
AI

Claude Code for email.utils: Python Email Address and Header Utilities

Parse and format RFC 2822 email addresses and dates with Python's email.utils module and Claude Code — email utils parseaddr for splitting a display-name plus angle-bracket address string into a realname and email address tuple, email utils formataddr for combining a realname and address string into a properly quoted RFC 2822 address with angle brackets, email utils getaddresses for parsing a list of raw address header strings each potentially containing multiple comma-separated addresses into a list of realname address tuples, email utils parsedate for parsing an RFC 2822 date string into a nine-tuple compatible with time.mktime, email utils parsedate_tz for parsing an RFC 2822 date string into a ten-tuple that includes the UTC offset timezone in seconds, email utils parsedate_to_datetime for parsing an RFC 2822 date string into an aware datetime object with timezone, email utils formatdate for formatting a POSIX timestamp or the current time as an RFC 2822 date string with optional usegmt and localtime flags, email utils format_datetime for formatting a datetime object as an RFC 2822 date string, email utils make_msgid for generating a globally unique Message-ID string with optional idstring and domain components, email utils decode_rfc2231 for decoding an RFC 2231 encoded parameter value into a tuple of charset language and value, email utils encode_rfc2231 for encoding a string as an RFC 2231 encoded parameter value, email utils collapse_rfc2231_value for collapsing a decoded RFC 2231 tuple to a Unicode string, and email utils integration with email.message and email.headerregistry and datetime and time for building address parsers date formatters message-id generators header extractors and RFC-compliant email construction utilities.

5 min read Feb 10, 2029

Put these ideas into practice

Claude Skills 360 gives you production-ready skills for everything in this article — and 2,350+ more. Start free or go all-in.

Back to Blog

Get 360 skills free