Skip to content
v0.1.3latest release121 skills4 categories6 sub-categories247 tested scripts397 reference docsContact us

feature-scaling-advisor

Decide whether and how to scale or transform numeric features for a given model: no scaling for trees and gradient boosting, StandardScaler, RobustScaler for outliers, MinMaxScaler and MaxAbsScaler (sparse data), log1p, Box-Cox and Yeo-Johnson PowerTransformer for skew, QuantileTransformer for heavy tails, clipping/winsorising, and target transforms (TransformedTargetRegressor) for skewed regression targets. Measures skew, robust outliers, zeros, negatives and bounds per column, shows how one wide column dominates raw distances, emits a leak-free ColumnTransformer, and measures the effect of each scaling on a k-NN model with cross-validation. Use when someone asks whether to normalise or standardise, which scaler to use, why k-NN / k-means / SVM / PCA / logistic regression behave oddly, how to handle skewed or outlier-heavy features, or whether scaling leaks information.

AI & Machine Learning / Classical Machine Learningv1.0.0Updated OCT 25 20264 references2 scripts

Scaling matters for any model that uses distances (k-NN, k-means, SVM with RBF, DBSCAN), penalties (ridge, lasso, elastic net, regularised logistic regression), gradients (neural nets, SGD) or variance (PCA). It does nothing for trees and gradient boosting, which split on thresholds and are invariant to monotone transforms. The choice of scaler follows the column's shape: symmetric -> standard; outliers -> robust; right-skewed -> log/Box-Cox/Yeo-Johnson; heavy tails -> quantile; sparse -> max-abs. scripts/scaling_plan.py recommends a transform per column and emits the ColumnTransformer; scripts/scale_impact.py shows the effect on a k-NN model with cross-validation.

Trigger Conditions

Activate this skill when the user:

  • Asks "should I normalise / standardise?", "which scaler?", "MinMax or Standard?"
  • Uses k-NN, k-means, SVM, PCA, regularised linear models or neural nets and gets odd results
  • Has skewed, heavy-tailed or outlier-heavy numeric features, or a skewed regression target
  • Wonders whether to scale for XGBoost / LightGBM / random forest (no)
  • Suspects scaling leakage (scaler fitted on the full dataset before CV)

Workflow

text
1. MODEL     -> tree-based? stop: no scaling (keep the raw units for interpretation)
2. MEASURE   -> python scripts/scaling_plan.py data.csv --model linear --target y --drop id
3. CHOOSE    -> per column: standard / robust / log1p+standard / power / quantile / passthrough
4. BUILD     -> python scripts/scaling_plan.py ... --code   (ColumnTransformer inside a Pipeline)
5. EVIDENCE  -> python scripts/scale_impact.py data.csv --target y   (raw vs scaled k-NN, CV)
6. TARGET    -> skewed regression target? TransformedTargetRegressor(log1p) or a Tweedie/Gamma loss
7. VERIFY    -> scaler fitted on training folds only; same transform at serving time

Which Models Need Scaling

ModelNeeds scaling?Why
Decision tree, random forest, extra treesnothreshold splits are invariant to monotone transforms
Gradient boosting (XGBoost, LightGBM, CatBoost, HistGBM)nosame; binning is rank-based
Linear / logistic regression, unregularisedfor interpretation and solver speed onlycoefficients rescale; predictions do not change
Ridge / lasso / elastic net / regularised logisticyesthe penalty treats all coefficients equally, so units decide which features get shrunk
SVM (RBF or linear)yesdistances and margins
k-NN, k-means, DBSCAN, hierarchical clusteringyesEuclidean distance is dominated by the widest column
PCA, factor analysisyes (or use correlation-based PCA)components chase the largest variance
Neural networks, SGD-based modelsyesgradient conditioning and activation ranges
Naive Bayes (Gaussian)no (per-feature distributions)-
UMAP, t-SNEusually yesdistance-based neighbourhoods

scale_impact.py on the churn fixture: raw 15-NN ROC-AUC 0.58 (total_charges holds 99.9% of raw distance variance) vs 0.76-0.78 scaled.

Scaler Selection by Column Shape

Column shapeTransformscikit-learn
Roughly symmetric, few outliersstandardiseStandardScaler()
Outliers you want to keep but not let dominaterobust scaling (median / IQR)RobustScaler()
Right-skewed, non-negative, has zeroslog1p then standardiseFunctionTransformer(np.log1p) + StandardScaler()
Right-skewed, strictly positiveBox-CoxPowerTransformer(method="box-cox")
Skewed with negative valuesYeo-JohnsonPowerTransformer(method="yeo-johnson")
Heavy tails, outliers, any shape (NN inputs)rank -> normal or uniformQuantileTransformer(output_distribution="normal")
Already in [0, 1] (proportions)none or standardise-
Bounded inputs required (some NN activations, images)min-maxMinMaxScaler()
Sparse matrix (TF-IDF, many one-hot)max-abs (keeps zeros)MaxAbsScaler()
Binary 0/1 indicatorsleave as is"passthrough"
Extreme errors / sentinel values (999999)fix the data, then clipnp.clip at train quantiles

PowerTransformer standardises its output by default (standardize=True). QuantileTransformer is non-linear and distorts distances between far-apart values; prefer it for heavy-tailed inputs to neural nets or linear models, not when relative magnitudes matter.

Transforms, formulas and their failure modes: transforms-and-outliers.md.

Scaling Without Leakage

python
from sklearn.pipeline import Pipeline
from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import StandardScaler, PowerTransformer
from sklearn.linear_model import LogisticRegression

prep = ColumnTransformer([
    ("std", StandardScaler(), ["tenure_months", "support_calls"]),
    ("pow", PowerTransformer(method="yeo-johnson"), ["total_charges"]),
], remainder="passthrough")
model = Pipeline([("prep", prep), ("clf", LogisticRegression(C=1.0, max_iter=2000))])
# cross_val_score(model, X, y, cv=cv) refits the scalers on every training fold.
  • Never scaler.fit(X_all) before splitting or before cross-validation: test-fold means and variances leak into training. The effect is usually small for standard scaling and larger for quantile transforms, target-dependent steps and small datasets, but it is always avoidable.
  • Fit once on training data, persist the fitted pipeline, apply the same object at serving time.
  • Time series: fit on the past window only; refit at each retrain.

More leakage cases and serving issues: scaling-pitfalls.md.

Regression Targets

Target shapeOption
Right-skewed positive (prices, durations)TransformedTargetRegressor(regressor=..., func=np.log1p, inverse_func=np.expm1)
Counts / zero-heavyPoisson or Tweedie loss instead of transforming
Symmetricno transform needed (scaling the target only matters for neural nets)

Log-target models predict something closer to the median; when sums matter (total revenue), correct the retransformation bias (smearing) or use a Gamma/Tweedie loss. Details: transforms-and-outliers.md.

Output Format

When advising on scaling, answer with:

  1. Does this model need scaling? - yes/no with the reason (distance, penalty, gradient, variance, or tree invariance).
  2. Per-column plan - the scaling_plan.py table: shape statistics and the chosen transform.
  3. Code - the ColumnTransformer inside a Pipeline.
  4. Evidence - scale_impact.py result (raw vs scaled), or CV comparison of two scalers.
  5. Target handling - for regression with a skewed target.
  6. Serving notes - persisted fitted transformer, behaviour on out-of-range values.

Scripts

bash
python scripts/scaling_plan.py data.csv --model linear --target price --drop house_id
python scripts/scaling_plan.py data.csv --model tree
python scripts/scaling_plan.py data.csv --model nn --target y --json
python scripts/scaling_plan.py data.csv --model linear --target y --code > prep.py

Models: tree, linear (also SVM, k-NN, k-means, PCA), nn, sparse. Per numeric column: min, max, mean, std, median, IQR, skew, robust outlier share (|x - median| / (1.4826 MAD) > 3.5), zero share, negatives, distinct count; the transform with the reason; and the largest/smallest standard-deviation ratio across columns. --code prints a ColumnTransformer of median imputation + scaler per group with unique step names. Exit codes: 0 printed, 2 usage error or no numeric columns.

bash
python scripts/scale_impact.py data.csv --target churned --drop customer_id
python scripts/scale_impact.py data.csv --target price --k 10 --folds 5 --max-rows 1500 --json

Pure-Python k-NN with K-fold CV on the numeric columns under raw, standard, robust, log1p+standard and min-max scaling (fitted on each training fold): ROC-AUC for binary targets, MAE for numeric ones; plus each column's share of raw squared-distance variance. Exit codes: 0 measured, 2 usage error or not enough numeric rows.

Additional Resources

FileContent
scaler-catalog.mdEvery scaler: formula, parameters, output range, sensitivity to outliers, sparse support, inverse transform
transforms-and-outliers.mdlog, Box-Cox, Yeo-Johnson, quantile, winsorising, binning; outlier detection; target transforms and retransformation bias
model-sensitivity.mdWhy each model family is or is not scale-sensitive, with small demonstrations (penalties, distances, PCA, gradients)
scaling-pitfalls.mdLeakage, fitting on all data, time series, serving drift, clipping at serving time, scaling one-hot columns, interpretation of scaled coefficients
More in Classical Machine Learning

anomaly-detection-model-builder

Build and evaluate anomaly detection for tabular, sensor and transaction data with few or no labels: define the anomaly type (point, contextual, collective), choose detectors (robust z-score/MAD and IQR rules, Mahalanobis with robust covariance, k-NN distance, LOF, Isolation Forest, one-class SVM, PCA reconstruction / autoencoders, forecasting residuals for time series), combine them by rank, explain each alert by its deviating features, set thresholds from an alert budget or the score distribution, and evaluate with precision@k, PR-AUC and recall on known incidents, or detector agreement when no labels exist. Includes pure-Python detectors (robust z, Mahalanobis, kNN, Isolation Forest, ensemble) and an evaluation script.

catboost-model-builder

Build CatBoost models that use its strengths correctly: raw categorical columns as cat_features (ordered target statistics, no manual encoding), text_features, Pool construction with NaN-safe categories, ordered boosting and has_time for temporal data, symmetric (oblivious) trees, overfitting detector with eval_set and use_best_model, losses for classification, regression (Quantile, Poisson, Tweedie) and ranking (YetiRank), class weights, monotone constraints, feature importance (PredictionValuesChange, LossFunctionChange) and SHAP values, GPU training and model export. Plans cat/text/numeric columns from a CSV and generates a runnable training script, and checks parameter sets for the conflicts CatBoost rejects (iterations vs n_estimators, Bayesian bootstrap with subsample, multiple class-weight options, depth > 16, use_best_model without eval_set).

categorical-encoding-selector

Choose and implement the right encoding for every categorical column given the model family and the data: one-hot (with infrequent-level grouping and handle_unknown), ordinal with an explicit order, cross-fitted target encoding (scikit-learn TargetEncoder, CatBoost ordered statistics, category_encoders inside CV), frequency/count encoding, feature hashing, native categorical support in LightGBM, HistGradientBoosting, XGBoost and CatBoost, prefix levels for codes (zip3, NAICS-2), and embeddings. Measures cardinality, rare-level share, unseen-level rate on a time-ordered holdout and target signal per column, emits the ColumnTransformer, and quantifies target-encoding leakage (in-sample vs out-of-fold vs holdout AUC).

classification-model-selector

Choose the right classification algorithm for tabular, text or mixed data and prove the choice with a fair bake-off: logistic regression (L2, L1, elastic net), linear SVM, naive Bayes, k-NN, RBF SVM, decision trees, random forest, extra trees, HistGradientBoosting, LightGBM, XGBoost, CatBoost, explainable boosting machines (EBM/GAM), points scorecards and MLPs, matched to data size, width, categorical and high-cardinality share, missingness, class imbalance, text, and constraints such as interpretability, monotonic constraints, calibrated probabilities, latency budgets and tiny deployable models. Ranks candidates with starting hyperparameters and cautions, then generates a bake-off script running every candidate on identical CV folds with per-fold metrics, fit time and prediction latency.

clustering-algorithm-selector

Choose the right clustering algorithm and check that clustering makes sense at all: cluster tendency (Hopkins statistic with a correlated-features caveat, nearest-neighbour isolation), then k-means / MiniBatchKMeans, Gaussian mixtures with BIC, agglomerative (Ward, average, complete, single) with dendrograms, DBSCAN, HDBSCAN, OPTICS, spectral clustering, BIRCH, mean shift, k-prototypes and k-modes for mixed or categorical data, and Gower distance, matched to data size, expected shapes, noise, varying density, known k, soft memberships, hierarchy and streaming. Covers preprocessing (scaling, encoding, dimensionality, distance metrics), validation (internal indices, bootstrap stability, external labels, business profiling) and assigning new points.

collaborative-filtering-implementer

Implement collaborative filtering recommenders that beat popularity: item-based kNN with cosine, Jaccard or asymmetric similarity, shrinkage, neighbourhood size, positive-only or mean-centred rating signals and 'because you liked X' explanations; implicit ALS with confidence weighting, BPR pairwise ranking and the closed-form EASE model in plain NumPy, tuned on a temporal validation split by recall@k and NDCG@k and refit on all data; plus user-kNN, explicit matrix factorisation, the implicit/LightFM libraries, hyperparameter ranges, cold-start fallbacks, scaling with sparse matrices and approximate nearest neighbours. Produces top-k lists in the format of the recommendation evaluator.