Simple Algorithm
Machine Learning · Descent · 22 min

Feature Engineering & Messy Data

Scaling, encoding, missing values and imbalanced classes.

In applied machine learning, much of the accuracy comes from what you feed the model. This lesson turns raw columns into features a learner can use: it scales numbers, encodes categories, text and dates, handles missing values and outliers, copes with rare classes, chooses which features to keep, and wraps every step in a pipeline that cannot leak.

What you’ll learn

  • Decide which models need feature scaling, and derive how standardization changes the conditioning of gradient descent.
  • Encode categorical, text and date features with one-hot, target, hashed, TF-IDF and cyclical encodings, knowing the cost and the leakage risk of each.
  • Choose among deletion, imputation and missingness indicators, and quantify how mean imputation distorts variances and correlations.
  • Handle outliers and imbalanced classes with robust transforms, threshold moving, class weights and resampling, and correct probabilities after resampling.
  • Choose among filter, wrapper and embedded feature selection, and build pipelines that fit every data-dependent step, selection included, on the training folds only.

Scale: when units decide the answer

Standardization maps a feature to z=(x−μ^)/σ^z=(x-\hat\mu)/\hat\sigma, with the mean and standard deviation estimated on the training data. Alternatives are min–max scaling to [0,1][0,1], robust scaling by the median and interquartile range (which ignores a few extreme values), and a log transform for positive, right-skewed features such as incomes or counts.

Whether scaling matters depends on how the model uses the numbers:

  • Distances and kernels (k-nearest neighbors, k-means, an RBF SVM): a feature measured in large units dominates every distance.
  • Penalties (ridge, the lasso): λ∥w∥\lambda\norm{\mathbf w} charges coefficients in the units of their features, so rescaling a feature changes how hard it is shrunk.
  • Gradient-based training: badly scaled features make the loss surface a narrow valley.
  • PCA: variance is measured in the features' units.
  • Not: decision trees and their ensembles, whose splits depend only on the order of each feature's values, and unpenalized least squares, whose coefficients simply rescale.
DerivationScaling and the condition number of gradient descent
  1. ∇2f=1nX⊤X=Σ^\nabla^2f=\frac1nX^\top X=\hat\Sigma

    For least squares on centered features, f(w)=12n∥y−Xw∥2f(\mathbf w)=\frac1{2n}\norm{\mathbf y-X\mathbf w}^2, the Hessian is the sample covariance matrix of the features:

  2. κ=λmax⁡(Σ^)λmin⁡(Σ^)\kappa=\frac{\lambda_{\max}(\hat\Sigma)}{\lambda_{\min}(\hat\Sigma)}

    With step size 1/λmax⁡1/\lambda_{\max}, gradient descent shrinks the error along each eigenvector of Σ^\hat\Sigma by a factor 1−λk/λmax⁡1-\lambda_k/\lambda_{\max} per step, so the slowest direction needs about κln⁡(1/ε)\kappa\ln(1/\varepsilon) steps to reach accuracy ε\varepsilon, where κ\kappa is the condition number (Gradient Descent derives the rates):

  3. κstd=1+∣r∣1−∣r∣\kappa_{\text{std}}=\frac{1+\abs r}{1-\abs r}

    After standardization Σ^\hat\Sigma becomes the correlation matrix. For two features with correlation rr its eigenvalues are 1±r1\pm r:

  4. κraw=165.72.14≈77⟶κstd=1.740.26≈6.7\kappa_{\text{raw}}=\frac{165.7}{2.14}\approx77\qquad\longrightarrow\qquad\kappa_{\text{std}}=\frac{1.74}{0.26}\approx6.7

    For the income and education data the raw covariance has eigenvalues 165.7 and 2.14, so κ≈77\kappa\approx77; standardized, κ=1.74/0.26≈6.7\kappa=1.74/0.26\approx6.7. Gradient descent needs about eleven times fewer steps. Strong correlation still costs something, and no rescaling of individual features removes it.

Check your understanding

You switch the income column from thousands of dollars to dollars, multiplying it by 1,000. Whose predictions change?

  1. A decision tree's
  2. A random forest's
  3. A kk-nearest-neighbor classifier's on the raw features
  4. An unpenalized least-squares regression's
Show the answer

C. A kk-nearest-neighbor classifier's on the raw features

Multiplying income by 1,000 multiplies its contribution to every squared distance by a million, so the neighbors of a point are now decided almost by income alone. A tree only compares income with thresholds, which rescale with it, and least squares divides the income coefficient by 1,000, leaving every prediction unchanged.

Encoding categories, text and time

EncodingWhat it doesUse whenWatch out for
One-hotone 0/1 column per categoryfew categories; linear models, neural netswith an intercept and no penalty, drop one column (the columns sum to 1); thousands of categories mean thousands of sparse columns
Ordinal codescategories mapped to 0,1,2,…0,1,2,\dotsgenuinely ordered levels; treesinvents an order and distances for unordered categories
Target encodingeach category replaced by a smoothed mean of the targetmany categories (zip codes, product IDs)leaks the label unless computed out of fold
Feature hashingcategories hashed into mm bucketshuge or open-ended vocabularies, streaming datacollisions merge unrelated categories
Learned embeddingsa dense vector per category, trained with the modelneural networks with many categoriesneeds enough data per category
Unseen categories at prediction time need a rule too: an all-zero one-hot row, the global mean for target encoding, or a hash bucket like any other.

Target encoding replaces category cc, seen ncn_c times with mean target yˉc\bar y_c, by a value shrunk toward the global mean yˉ\bar y with strength a>0a>0,

x~c=nc yˉc+a yˉnc+a,\tilde x_c=\frac{n_c\,\bar y_c+a\,\bar y}{n_c+a},

so rare categories borrow strength from the whole dataset (Micci-Barreca, 2001, proposed this kind of blending). Computed on the same rows it encodes, it leaks: a category seen once encodes its own label. Compute each row's value from the other folds, or use ordered statistics as CatBoost does (XGBoost, LightGBM & CatBoost).

Text becomes a bag of words: one count per vocabulary term (or per nn-gram), giving a long, sparse vector. TF-IDF reweights the count tf(t,d)\mathrm{tf}(t,d) of term tt in document dd by how rare the term is across the NN documents, tfidf(t,d)=tf(t,d)⋅log⁡Ndf(t)\mathrm{tfidf}(t,d)=\mathrm{tf}(t,d)\cdot\log\frac{N}{\mathrm{df}(t)}, where df(t)\mathrm{df}(t) counts the documents containing tt (Spärck Jones, 1972; Salton & Buckley, 1988). In 1,000 support emails, "the" appears in all of them and gets weight 0; "refund" appears in 10 and gets ln⁡100≈4.6\ln100\approx4.6 per occurrence, so an email that says "refund" three times scores 13.8 on it. Libraries use smoothed variants, such as scikit-learn's ln⁡1+N1+df+1\ln\frac{1+N}{1+\mathrm{df}}+1.

Dates and times become parts (hour, weekday, month), elapsed times ("days since last purchase"), flags (holiday, payday) and, for cyclic quantities, points on a circle: (sin⁡2πh24,cos⁡2πh24)\big(\sin\frac{2\pi h}{24},\cos\frac{2\pi h}{24}\big) for the hour hh.

Predict before you look

With the hour encoded as (sin⁡2πh24,cos⁡2πh24)\big(\sin\frac{2\pi h}{24},\cos\frac{2\pi h}{24}\big), what is the Euclidean distance between 23:00 and 01:00?

Show the answer

0.52

The two angles differ by 2⋅2π24=π62\cdot\frac{2\pi}{24}=\frac{\pi}{6}, and a chord of the unit circle spanning angle θ\theta has length 2sin⁡(θ/2)=2sin⁡(π/12)≈0.522\sin(\theta/2)=2\sin(\pi/12)\approx0.52: exactly the distance between 11:00 and 13:00. Noon and midnight are 2 apart, the diameter. As plain numbers, 23 and 1 would be 22 apart, nearly as far apart as two hours can be.

Missing values and outliers

Why a value is missing matters as much as that it is missing. Missing data are MCAR (missing completely at random: unrelated to anything, like a sample lost in the post), MAR (missing at random: dependent only on values you observe, like older patients skipping a questionnaire item when age is recorded) or MNAR (missing not at random: dependent on the missing value itself, like high earners declining to state their income).

The usual responses:

  • Delete incomplete rows (complete-case analysis). Simple and unbiased under MCAR, but it wastes data and, under MAR or MNAR, can skew the sample.
  • Impute: fill each gap with the mean, median or most frequent value, or with a prediction from the other features (imputation).
  • Flag: add a 0/1 "was missing" column, so the model can learn from the pattern of missingness itself, which is often predictive (a test not ordered because the doctor saw no need).
  • Let the model handle it: gradient-boosted trees such as XGBoost learn, at every split, which side missing values should go to (Chen & Guestrin, 2016).
DerivationWhat mean imputation does to the data
  1. Var⁡^(xfilled)=1n∑i observed(xi−xˉ)2 ≈ (1−m) Var⁡(x)\widehat{\Var}(x_{\text{filled}})=\frac1n\sum_{i\ \text{observed}}(x_i-\bar x)^2\ \approx\ (1-m)\,\Var(x)

    Let a fraction mm of a feature's values be missing completely at random, and fill them with the observed mean xˉ\bar x. Imputed values sit exactly at the mean, so they add nothing to the sum of squares, and the variance of the completed column shrinks:

  2. Cov⁡^(xfilled,y)≈(1−m) Cov⁡(x,y)\widehat{\Cov}(x_{\text{filled}},y)\approx(1-m)\,\Cov(x,y)

    Its covariance with a fully observed feature yy shrinks the same way, since imputed rows contribute (xˉ−xˉ)(yi−yˉ)=0(\bar x-\bar x)(y_i-\bar y)=0:

  3. Corr^(xfilled,y)≈(1−m)Cov⁡(x,y)(1−m)Var⁡(x)Var⁡(y)=1−m  Corr(x,y)\widehat{\mathrm{Corr}}(x_{\text{filled}},y)\approx\frac{(1-m)\Cov(x,y)}{\sqrt{(1-m)\Var(x)\Var(y)}}=\sqrt{1-m}\;\mathrm{Corr}(x,y)

    So the correlation is attenuated by 1−m\sqrt{1-m}, and anything built on correlations (PCA, clustering, feature selection) sees weaker structure than exists. Regression imputation errs the other way: imputed points lie exactly on the fitted line, which inflates correlations. And any single imputation treats guesses as data, so standard errors come out too small. Missing Data derives the fix, multiple imputation.

Predict before you look

Two features have correlation 0.5. Then 36% of the first feature's values go missing completely at random and are filled with its mean. What is the correlation of the filled-in feature with the second?

Show the answer

0.4

0.5×1−0.36=0.5×0.8=0.400.5\times\sqrt{1-0.36}=0.5\times0.8=0.40. A simulation with 200,000 rows gives 0.40. The missing values did not weaken the relationship; the imputation did.

Outliers. Flag values far from the bulk with robust rules, such as a median-based zz-score ∣x−med∣/(1.4826⋅MAD)\abs{x-\mathrm{med}}/(1.4826\cdot\mathrm{MAD}) above about 3.5, or points beyond 1.5 interquartile ranges from the quartiles. Then decide what they are. Errors (a height of 1,750 cm, a unit mix-up) get fixed or removed; genuine extremes get kept, perhaps on a log scale, clipped at a high percentile (winsorized), or handled by a model with a robust loss such as the Huber loss (Robust Regression). Never delete inconvenient points just because they are extreme: in fraud or failure detection, the extremes may be the signal.

Imbalanced classes

With class imbalance, say one fraudulent payment per thousand, the default threshold of 0.5 and the accuracy score both mislead. Four remedies, from cheapest to most invasive:

  1. Move the threshold. With calibrated probabilities the cost-optimal rule is p≥cFP/(cFP+cFN)p\ge c_{\mathrm{FP}}/(c_{\mathrm{FP}}+c_{\mathrm{FN}}); otherwise tune the threshold on validation data. No retraining.
  2. Weight the classes in the loss, ∑iwyi ℓ(f(xi),yi)\sum_iw_{y_i}\,\ell(f(\mathbf x_i),y_i), with larger weights on the rare class (cost-sensitive learning).
  3. Resample the training set: drop majority examples (undersampling), repeat minority ones (oversampling), or synthesize new minority points. SMOTE (Chawla et al., 2002) places each synthetic point at random on the segment between a minority example and one of its nearest minority neighbors.
  4. Change the model or loss, for instance with losses that focus on hard examples (Imbalanced Data & Cost-Sensitive Learning).

Weights and resampling change the base rate the model learns from, so its probabilities no longer refer to the real population. They can be corrected exactly.

DerivationUndoing undersampling
  1. ps(x)1−ps(x)=1β⋅p(x)1−p(x)\frac{p_s(\mathbf x)}{1-p_s(\mathbf x)}=\frac1\beta\cdot\frac{p(\mathbf x)}{1-p(\mathbf x)}

    Keep every positive and each negative independently with probability β\beta. For any input, the positives near it survive with probability 1 and the negatives with probability β\beta, so the posterior odds in the training sample are inflated by 1/β1/\beta:

  2. p(x)=β ps(x)β ps(x)−ps(x)+1p(\mathbf x)=\frac{\beta\,p_s(\mathbf x)}{\beta\,p_s(\mathbf x)-p_s(\mathbf x)+1}

    Solve for the probability in the original population (Dal Pozzolo, Caelen, Johnson & Bontempi, 2015). Class weights with ratio 1/β1/\beta have the same effect in expectation, so the same correction applies:

  3. logit⁡p(x)=logit⁡ps(x)+log⁡β\operatorname{logit}p(\mathbf x)=\operatorname{logit}p_s(\mathbf x)+\log\beta

    For a logistic model the correction is a shift of the intercept by log⁡β\log\beta, since the log-odds simply move by that constant. The ranking of cases, and so the AUC, is unchanged; only the probabilities, and any threshold read off them, move.

Predict before you look

Fraud is 2% of payments. A model is trained on a balanced sample built by keeping all frauds and undersampling legitimate payments to the same number. It outputs 0.8 for a new payment. What is the corrected probability of fraud, in percent?

Show the answer

7.5 %

Balancing 2% against 98% keeps legitimate payments with probability β=0.02/0.98≈0.0204\beta=0.02/0.98\approx0.0204. Then p=0.0204⋅0.80.0204⋅0.8−0.8+1=0.01630.2163≈0.075p=\frac{0.0204\cdot0.8}{0.0204\cdot0.8-0.8+1}=\frac{0.0163}{0.2163}\approx0.075. The "80%" payment has a 7.5% chance of being fraud: still 3.8 times the base rate, but nowhere near 80%. Acting on the raw output would flood investigators with false alarms.

Feature selection and pipelines that cannot leak

Feature selection keeps a subset of the columns, to make a model cheaper, easier to explain or, when many features are pure noise, more accurate. Three families:

  • Filters score each feature on its own, for instance by its correlation or mutual information with the target, and keep the best. They are fast but blind to features that matter only together.
  • Wrappers search over subsets, scoring each by the validated performance of the model itself: forward selection, backward elimination, recursive feature elimination. They see interactions but cost many fits.
  • Embedded methods select while fitting: the lasso sets coefficients exactly to zero, and tree ensembles report how much each feature was used.

A selector that looks at the labels is a learned step like any other, so it belongs inside the pipeline (Feature Selection & Encoding compares the families in depth).

Every step that learns something from data, such as a scaler's means, an imputer's fill values, an encoder's category statistics, a feature selector's choices, a resampler's synthetic points or PCA's axes, is part of the model. It must be fitted on training data only: inside each training fold during cross-validation, and once on the full training set before deployment, where the same fitted transform is applied to new data. Otherwise information from the held-out rows leaks into training (data leakage; Kaufman, Rosset, Perlich & Stitelman, 2012, catalog the forms it takes).

Leaks differ in size. Standardizing with means and deviations computed on all rows leaks a little. Target encoding or supervised feature selection on all rows can leak enormously, enough to make pure noise look predictive. Oversampling before splitting puts copies, or synthetic neighbors, of the same minority example on both sides of the split, so the model is tested on near-duplicates of its training data.

python
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import make_pipeline
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import StandardScaler, OneHotEncoder
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import StratifiedKFold, cross_val_score

numeric = make_pipeline(SimpleImputer(strategy="median", add_indicator=True), StandardScaler())
categorical = make_pipeline(SimpleImputer(strategy="most_frequent"),
                            OneHotEncoder(handle_unknown="ignore"))
prep = ColumnTransformer([("num", numeric, num_cols), ("cat", categorical, cat_cols)])
model = make_pipeline(prep, LogisticRegression(C=1.0, max_iter=1000))

folds = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)
scores = cross_val_score(model, X, y, cv=folds, scoring="average_precision")

Because the imputer, scaler and encoder sit inside the pipeline, cross_val_score refits them on each training fold and only applies them to the held-out fold. add_indicator=True appends the missingness flags; handle_unknown="ignore" encodes unseen categories as all zeros. For many categories, scikit-learn's TargetEncoder (version 1.3 and later) cross-fits its encodings during fit_transform.

Check your understanding

Which step, done on the full dataset before splitting into folds, biases a cross-validation estimate the most?

  1. Converting a column from grams to kilograms
  2. Standardizing each feature with the full-data mean and standard deviation
  3. Listing the possible categories of a feature from the full data before one-hot encoding
  4. Keeping the 50 features most correlated with the label
Show the answer

D. Keeping the 50 features most correlated with the label

Supervised selection on all rows uses the held-out labels to choose features, so it can make noise look predictive: among thousands of noise features, the best few correlate with any labels by chance. A unit conversion learns nothing from data; full-data standardization and a full-data category list leak only slight, label-free information.

Key takeaways

  • Scale for distances, kernels, penalties, PCA and gradient-based training, not for trees. Standardization turns the Hessian of least squares into a correlation matrix, cutting the condition number (77 to 6.7 in the example).
  • One-hot for few categories, out-of-fold target encoding or hashing for many, TF-IDF for text, sine and cosine for cyclic time.
  • Deletion, imputation and missingness flags answer different needs; mean imputation shrinks variances by 1−m1-m and correlations by 1−m\sqrt{1-m}, and single imputation understates uncertainty.
  • For rare classes, move the threshold first; resampling and class weights change the base rate the model sees, so correct its probabilities afterwards.
  • Fit every data-dependent step, feature selection included, inside the training folds, and apply the same fitted pipeline at deployment.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

Why do decision trees not need feature scaling?

  1. Because trees standardize every feature internally before splitting
  2. Because each split compares one feature with a threshold, and a strictly increasing transformation of that feature preserves the order of its values and so the set of possible partitions
  3. Because trees only work with categorical features
  4. Because trees ignore features with large values
Show the answer

B. Because each split compares one feature with a threshold, and a strictly increasing transformation of that feature preserves the order of its values and so the set of possible partitions

A split "xj≤tx_j\le t" divides the points by the order of xjx_j. Any strictly increasing transformation keeps that order, so every partition available before is available after, with a transformed threshold. Distances, penalties and gradient steps have no such invariance.

Question 2

An unpenalized linear regression with an intercept also gets one 0/1 column for each of the 4 colors of a product. What goes wrong?

  1. Nothing: one-hot encoding always works
  2. The model becomes nonlinear
  3. The predictions depend on which color is listed first
  4. The four columns sum to the intercept column, so X⊤XX^\top X is singular and the coefficients are not identifiable
Show the answer

D. The four columns sum to the intercept column, so X⊤XX^\top X is singular and the coefficients are not identifiable

Every row has exactly one color, so the four columns add up to a column of ones, which duplicates the intercept: the design matrix loses rank, and infinitely many coefficient vectors give the same fit. Drop one color (it becomes the baseline absorbed by the intercept) or add a penalty, which picks a unique solution.

Question 3

A customer-ID feature with 50,000 levels is target-encoded with category means computed on the whole training set. Training accuracy is near perfect, and test accuracy is poor. Why?

  1. Each row's encoding contains its own label, so the encoded feature memorizes the training labels; it must be computed out of fold
  2. Target encoding cannot handle more than 1,000 categories
  3. The global mean used for smoothing was wrong
  4. The test set has a different class balance
Show the answer

A. Each row's encoding contains its own label, so the encoded feature memorizes the training labels; it must be computed out of fold

For a customer seen once, the in-sample encoding is essentially that customer's label, so a model can read the answer off the feature. At test time new customers get the prior mean and the feature is useless. Out-of-fold encoding, where each row's value comes from the other folds, or ordered statistics remove the leak.

Question 4

Half of a feature's values are missing completely at random and are replaced by the feature's mean. Its correlation with another, complete feature was ρ\rho. What is it now, approximately?

  1. ρ\rho, unchanged
  2. 0.5ρ0.5\rho
  3. 0.71ρ0.71\rho
  4. 0
Show the answer

C. 0.71ρ0.71\rho

The covariance and the variance both shrink by 1−m=0.51-m=0.5, so the correlation shrinks by 0.5≈0.71\sqrt{0.5}\approx0.71. The relationship in the observed half is intact; the imputed half sits at the mean and contributes nothing.

Go deeper

Further reading

  • M. Kuhn & K. Johnson, Feature Engineering and Selection: A Practical Approach for Predictive Models (CRC Press, 2019).
  • D. Micci-Barreca, "A preprocessing scheme for high-cardinality categorical attributes in classification and prediction problems," ACM SIGKDD Explorations 3(1), 27–32 (2001).
  • S. Kaufman, S. Rosset, C. Perlich & O. Stitelman, "Leakage in data mining: formulation, detection, and avoidance," ACM Transactions on Knowledge Discovery from Data 6(4) (2012).
  • N. V. Chawla, K. W. Bowyer, L. O. Hall & W. P. Kegelmeyer, "SMOTE: synthetic minority over-sampling technique," Journal of Artificial Intelligence Research 16, 321–357 (2002).