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 , with the mean and standard deviation estimated on the training data. Alternatives are min–max scaling to , 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): 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.
For least squares on centered features, , the Hessian is the sample covariance matrix of the features:
With step size , gradient descent shrinks the error along each eigenvector of by a factor per step, so the slowest direction needs about steps to reach accuracy , where is the condition number (Gradient Descent derives the rates):
After standardization becomes the correlation matrix. For two features with correlation its eigenvalues are :
For the income and education data the raw covariance has eigenvalues 165.7 and 2.14, so ; standardized, . Gradient descent needs about eleven times fewer steps. Strong correlation still costs something, and no rescaling of individual features removes it.
You switch the income column from thousands of dollars to dollars, multiplying it by 1,000. Whose predictions change?
- A decision tree's
- A random forest's
- A -nearest-neighbor classifier's on the raw features
- An unpenalized least-squares regression's
Show the answer
C. A -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
| Encoding | What it does | Use when | Watch out for |
|---|---|---|---|
| One-hot | one 0/1 column per category | few categories; linear models, neural nets | with an intercept and no penalty, drop one column (the columns sum to 1); thousands of categories mean thousands of sparse columns |
| Ordinal codes | categories mapped to | genuinely ordered levels; trees | invents an order and distances for unordered categories |
| Target encoding | each category replaced by a smoothed mean of the target | many categories (zip codes, product IDs) | leaks the label unless computed out of fold |
| Feature hashing | categories hashed into buckets | huge or open-ended vocabularies, streaming data | collisions merge unrelated categories |
| Learned embeddings | a dense vector per category, trained with the model | neural networks with many categories | needs enough data per category |
Target encoding replaces category , seen times with mean target , by a value shrunk toward the global mean with strength ,
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 -gram), giving a long, sparse vector. TF-IDF reweights the count of term in document by how rare the term is across the documents, , where counts the documents containing (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 per occurrence, so an email that says "refund" three times scores 13.8 on it. Libraries use smoothed variants, such as scikit-learn's .
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: for the hour .
With the hour encoded as , what is the Euclidean distance between 23:00 and 01:00?
Show the answer
0.52
The two angles differ by , and a chord of the unit circle spanning angle has length : 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).
Let a fraction of a feature's values be missing completely at random, and fill them with the observed mean . Imputed values sit exactly at the mean, so they add nothing to the sum of squares, and the variance of the completed column shrinks:
Its covariance with a fully observed feature shrinks the same way, since imputed rows contribute :
So the correlation is attenuated by , 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.
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
. 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 -score 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:
- Move the threshold. With calibrated probabilities the cost-optimal rule is ; otherwise tune the threshold on validation data. No retraining.
- Weight the classes in the loss, , with larger weights on the rare class (cost-sensitive learning).
- 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.
- 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.
Keep every positive and each negative independently with probability . For any input, the positives near it survive with probability 1 and the negatives with probability , so the posterior odds in the training sample are inflated by :
Solve for the probability in the original population (Dal Pozzolo, Caelen, Johnson & Bontempi, 2015). Class weights with ratio have the same effect in expectation, so the same correction applies:
For a logistic model the correction is a shift of the intercept by , 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.
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 . Then . 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.
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.
Which step, done on the full dataset before splitting into folds, biases a cross-validation estimate the most?
- Converting a column from grams to kilograms
- Standardizing each feature with the full-data mean and standard deviation
- Listing the possible categories of a feature from the full data before one-hot encoding
- 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 and correlations by , 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.
Why do decision trees not need feature scaling?
- Because trees standardize every feature internally before splitting
- 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
- Because trees only work with categorical features
- 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 "" divides the points by the order of . 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.
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?
- Nothing: one-hot encoding always works
- The model becomes nonlinear
- The predictions depend on which color is listed first
- The four columns sum to the intercept column, so is singular and the coefficients are not identifiable
Show the answer
D. The four columns sum to the intercept column, so 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.
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?
- Each row's encoding contains its own label, so the encoded feature memorizes the training labels; it must be computed out of fold
- Target encoding cannot handle more than 1,000 categories
- The global mean used for smoothing was wrong
- 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.
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 . What is it now, approximately?
- , unchanged
- 0
Show the answer
C.
The covariance and the variance both shrink by , so the correlation shrinks by . The relationship in the observed half is intact; the imputed half sits at the mean and contributes nothing.
Go deeper
- Missing Data · MCAR, MAR, MNAR and principled imputation.
- Imbalanced Data & Cost-Sensitive Learning · Resampling, class weights and moving the threshold.
- Feature Selection & Encoding · Filters, wrappers, embedded methods, target encoding and hashing.
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).