Skip to content
Classical machine learning Core 24 min read

Features and tabular data

A model can only learn what its inputs make learnable. Feature engineering is the craft of turning raw records (amounts, categories, timestamps, histories, free text) into columns whose relationship to the target is simple for your chosen model. On tables of business and scientific data it still decides more of the final accuracy than the choice of algorithm, and it is where most leakage is born.

10,000 ft

Most machine learning in industry runs on tables: transactions, customers, loans, sensor logs, clinical records. Deep learning's great achievement was to learn features from raw pixels, audio and text (embeddings and representation learning), but on heterogeneous tabular data gradient-boosted trees on well-designed features remain the default, and a careful 2022 benchmark found tree ensembles still ahead of deep networks on medium-sized tables (about 10,000 rows). The picture is moving: tabular foundation models such as TabPFN, a transformer pre-trained on millions of synthetic datasets, reported in Nature (2025) that they beat tuned baselines on datasets of up to 10,000 samples. Either way, the ideas on this page (scaling, encoding categories, handling missingness and time, building aggregates point-in-time, measuring importance honestly) are what separate a model that works in a notebook from one that works in production, and they feed directly into trees and ensembles, evaluation and data in production.

2,000 ft

Each raw column type has a small set of standard transformations, and each model family needs some of them and not others. Numbers get imputed, perhaps log-transformed, and scaled (for linear models, distance-based models and networks; trees do not care). Categories become one-hot columns, hashed buckets, smoothed target statistics or learned embeddings. Timestamps become cyclical components, elapsed times and lagged or rolling aggregates computed strictly from the past. Every transformation that learns anything from data (a mean, a vocabulary, a target statistic) is fitted on training data only and applied unchanged to validation, test and production rows.

A tabular feature pipeline
A tabular feature pipeline. Raw tables (events, entities, labels), Point-in-time join (only data known at prediction time), Numeric impute · log · scale · bin, Categorical one-hot · hash · target-encode, Time cyclical · elapsed · lags · windows, Text TF-IDF · embeddings, Feature matrix, Model (fitted on training folds)A tabular feature pipeline. Raw tables (events, entities, labels), Point-in-time join (only data known at prediction time), Numeric impute · log · scale · bin, Categorical one-hot · hash · target-encode, Time cyclical · elapsed · lags · windows, Text TF-IDF · embeddings, Feature matrix, Model (fitted on training folds)

Ground level

Representation decides what is learnable

The classic demonstration is XOR. Four points \((\pm1, \pm1)\) with label 1 when the two coordinates have the same sign: \((1,1)\) and \((-1,-1)\) are positive, \((1,-1)\) and \((-1,1)\) negative. No line separates them, so logistic regression on \((x_1, x_2)\) is stuck at 50% accuracy. Add one feature, \(x_3 = x_1x_2\), which is \(+1\) for both positives and \(-1\) for both negatives: now the rule "\(x_3 > 0\)" is linear and perfect. Nothing about the model changed; the representation did.

That is the entire game in miniature. A feature is a function of the raw record chosen so that the target becomes a simple function of the features, simple meaning "easy for this model family with this much data". Linear models need you to provide non-linearities and interactions; trees find interactions and thresholds themselves but cannot add two columns or extrapolate; distance-based models need comparable scales; networks learn features but need lots of data to do so. Good features encode domain knowledge the data are too small to rediscover: debt-to-income ratio rather than debt and income separately, days since last purchase rather than a raw date, price per square metre rather than price and area.

Numeric features

Scaling. Which models care?

Model family Needs scaling? Why
Linear / logistic regression, unpenalised no (for the fit) the weights rescale to compensate, but gradient-based solvers converge far faster on standardised inputs (linear regression)
Ridge, lasso, any penalised model yes the penalty treats all weights alike, so units decide who gets shrunk
k-NN, SVM with RBF kernel, k-means, PCA yes distances and variances are dominated by large-unit columns
Neural networks yes optimisation and initialisation assume inputs of order 1
Decision trees, random forests, gradient boosting no splits depend only on the order of values

Standardisation, \(z = (x - \mu)/\sigma\) with \(\mu\) and \(\sigma\) from the training set, is the default. Min–max scaling to \([0,1]\) is fragile to outliers; robust scaling uses the median and inter-quartile range.

Skew and log transforms. Incomes, prices, transaction amounts, populations and counts are typically right-skewed over several orders of magnitude. A linear model on raw income treats the jump from ₹1 lakh to ₹2 lakh as one-thousandth as important as the jump from ₹1 lakh to ₹101 lakh; on \(\log(\text{income})\) both are "doubling", which matches how most effects scale. Use \(\log(1 + x)\) for counts with zeros; Box–Cox and Yeo–Johnson transforms (PowerTransformer in scikit-learn) choose the power from data. Trees are invariant to any monotone transform, so this matters only for the other families.

Non-linear shape. To let a linear model bend, expand a column into several: polynomial terms, binning (one indicator per range: crude but robust), or splines (smooth piecewise polynomials, SplineTransformer). This is basis expansion again (linear in the parameters).

Outliers. Decide whether an extreme value is an error (fix or drop) or real (keep, maybe clip at a high percentile, or use a robust model). Clipping thresholds are learned from training data like everything else.

Categorical features

One-hot encoding makes one 0/1 column per category. With an intercept in a linear model, \(k\) categories need only \(k - 1\) columns: the \(k\) columns always sum to 1, duplicating the intercept and making \(X^\top X\) singular (the "dummy variable trap"; regularisation also resolves it). One-hot is ideal for a handful of categories and becomes wasteful and noisy for thousands: every rare category gets its own poorly estimated weight.

Ordinal encoding maps categories to integers. Right for genuinely ordered values (low < medium < high); for trees it is often fine even for unordered categories, since splits can carve the integer line; for linear models it imposes a fake order and spacing.

Feature hashing (the "hashing trick", Weinberger et al., 2009) maps each category string through a hash function into one of \(B\) buckets, with no vocabulary to store and no problem with categories never seen in training. The cost is collisions: with \(B = 2^{20} \approx 1.05\) million buckets and 100,000 distinct values, each value shares its bucket with at least one other with probability \(1 - e^{-99{,}999/2^{20}} \approx 9.1\%\). A signed hash (a second hash picks \(\pm1\)) makes collisions cancel in expectation. Ad-click models with billions of sparse features were built this way.

Target encoding replaces each category with a statistic of the target within that category, typically its mean. It compresses a 10,000-level column into one highly informative number. It is also the most dangerous common transformation, in two ways:

  1. Noise. A category seen three times, all positive, gets an encoding of 1.0, which is mostly luck. The fix is smoothing towards the global mean \(p_0\) with strength \(m\):

    \[ \text{enc}(c) = \frac{\sum_{i\in c} y_i + m\,p_0}{n_c + m}. \]

    With \(p_0 = 0.2\) and \(m = 10\): the three-for-three category gets \((3 + 2)/(3 + 10) = 0.385\), not 1.0; a category with 300 rows and mean 0.6 gets \((180 + 2)/310 = 0.587\), barely moved. Smoothing is exactly a Bayesian posterior mean (derived in The maths).

  2. Leakage. Each training row's encoding includes its own label. For rare categories this hands the model the answer: in the Build-it run below, an in-sample target encoding scores a training AUC of 0.844 against a test AUC of 0.691, and the model learns to over-trust the feature. The fix is out-of-fold encoding: compute each training row's encoding from the other folds only (scikit-learn's TargetEncoder does this "cross fitting" automatically in fit_transform; CatBoost uses an ordered variant, Prokhorenkova et al., 2017). Then training AUC (0.723) and test AUC (0.711) agree, and the test score is the best of the three variants.

Learned embeddings map each category to a dense vector trained with the model, the standard approach in neural recommenders and in tabular networks; the same idea as word embeddings.

Missing values

First ask why a value is missing; Rubin (1976) gave the vocabulary. MCAR (missing completely at random: a sensor dropped packets uniformly) is harmless apart from lost data. MAR (missing at random given other observed columns: older customers skip the email field) can be handled by imputing from those columns. MNAR (missingness depends on the missing value itself: high earners decline to state income) means the fact of missingness is informative.

Practical rules: impute with a training-set statistic (median for numbers, a "missing" category for categoricals) and add a binary indicator column so the model can learn that missingness itself predicts something; fit imputers inside each training fold; prefer models that handle missing values natively (LightGBM, XGBoost and scikit-learn's HistGradientBoosting* learn which branch missing values should follow). Never fill with a value that has meaning, such as 0 for a missing income.

Dates and time

A raw timestamp is almost never a good feature: it is unique, it only increases, and a model that uses it learns "when", which never recurs. Extract what does recur or what matters:

  • Components: hour, day of week, month, holiday flags, paydays, end of quarter.
  • Elapsed time: days since account opening, since last purchase, until contract end. These carry the real signal in churn, credit and maintenance problems.
  • Cyclical encoding for periodic components. Hour 23 and hour 0 are one hour apart but 23 units apart as integers. Map hour \(h\) to \((\sin\frac{2\pi h}{24}, \cos\frac{2\pi h}{24})\), a point on a circle: the distance between 23:00 and 00:00 becomes \(2\sin(\pi/24) = 0.261\), exactly the same as between 00:00 and 01:00. Trees can often split on the integer hour directly; linear and distance-based models need the circle.
02361218 (sin, cos) of hour 02323 units apartraw integer hour
Cyclical encoding. On the circle, 23:00 and 00:00 are neighbours (distance 0.261, the same as any adjacent pair of hours); as raw integers they are the furthest apart of any two hours.
  • Lags and rolling windows: last month's spend, the 7-day average, the trend over the last quarter. These are usually the strongest features in forecasting and risk, and the most leak-prone (next section).

Aggregates, joins and point-in-time correctness

The most predictive tabular features usually come from other tables: a customer's number of transactions in the last 30 days, the share of their payments that were late, the average claim size in their postcode. These are group-by aggregations joined onto the prediction row.

The rule that makes them safe: compute every feature as of the moment the prediction would have been made. If you predict on 1 March whether a loan will default by 1 June, then "number of late payments" must count late payments recorded before 1 March, not as of the day you built the dataset (which includes the very late payments that define the default). Getting this right requires event timestamps on every source row and an "as-of" join; feature stores exist largely to enforce it, and to guarantee that the code computing features for training is the same code serving them in production (a mismatch, called training–serving skew, is one of the commonest production failures; Sculley et al. 2015 catalogue it among ML's "hidden technical debt").

Text and other unstructured columns

A free-text column (a complaint, a product description, a merchant name) can be turned into features with bag-of-words or TF-IDF vectors (sparse, fast, strong baselines with a linear model), or with embeddings from a pre-trained language model (dense vectors that capture meaning; see embeddings and vector search). In 2026 the common pattern for messy categorical or text fields is to embed them with a pre-trained model and feed the vectors, or a few principal components of them, to a gradient-boosted tree alongside the numeric features.

Selecting features and measuring importance

More features are not free: each irrelevant one adds variance (and, for tree ensembles and networks, can actively hurt; Grinsztajn et al. found networks especially sensitive to uninformative features). Three families of selection methods:

  • Filter: rank features by a statistic with the target (correlation, mutual information) and keep the top \(k\). Fast; blind to interactions; must be done inside CV folds (the wrong way to do cross-validation).
  • Wrapper: search over subsets by refitting the model (forward selection, recursive feature elimination). Expensive and easy to overfit.
  • Embedded: the model selects as it fits: the lasso zeros weights; trees use some features and ignore others.

For importance, prefer permutation importance on held-out data: shuffle one column in the validation set, re-score the fitted model, and record how much the metric drops (Breiman introduced the idea for random forests in 2001). It measures what the model actually relies on for generalisation. Impurity-based importances from trees are computed on training data and are biased towards high-cardinality and continuous features. Both share a trap: if two features are strongly correlated, permuting one leaves the other to carry the signal and both look unimportant. Importance tells you about the model, not about causation in the world.

Trees versus networks on tables

Why have gradient-boosted trees (XGBoost, LightGBM, CatBoost) dominated tabular competitions and production systems for a decade, while networks won images and text? Grinsztajn, Oyallon and Varoquaux (2022) benchmarked 45 datasets and identified three inductive-bias reasons: target functions on tables are often irregular (sharp thresholds: an age limit, a tax bracket) while networks are biased towards smooth functions; tables contain many uninformative features, which hurt MLP-like networks more; and table columns have individual meanings, so the data are not rotation-invariant, while trees exploit axis-aligned splits that a rotation-invariant MLP cannot. McElfresh et al. (2023), comparing 19 algorithms on 176 datasets, found that for many datasets the GBDT-versus-network choice matters less than light tuning, with the exception of TabPFN, which outperformed the others on average on small datasets. Gorishniy et al. showed that better numeric embeddings (piecewise-linear and periodic) narrow the gap for networks. A practical 2026 default: start with gradient-boosted trees on carefully built features, keep a regularised linear model as a sanity baseline, and try a tabular foundation model when the dataset is small.

First principles

Features cannot create information; they expose it. The Bayes-optimal error for predicting \(y\) from a raw record \(r\) is fixed by the joint distribution of \((r, y)\); any feature map \(\phi(r)\) can at best preserve that information (the data-processing inequality: \(I(\phi(r); y) \le I(r; y)\)). What features change is how much data and model capacity are needed to reach that limit. A good feature performs, with zero data, a computation the model would otherwise have to learn from examples: the ratio, the elapsed time, the circle. So feature engineering is a way of lowering the estimation error by injecting knowledge: an inductive bias written by hand.

Each model family has a native vocabulary. Linear models natively represent weighted sums; trees represent axis-aligned thresholds and their conjunctions; k-NN represents "similar inputs have similar outputs" under a chosen distance; networks represent compositions of smooth functions. A feature is good for a model when it turns the target into something in that vocabulary. This is why the same feature set can be excellent for a GBDT and poor for logistic regression, and why "which features?" and "which model?" are one decision, not two.

Leakage lives here. Every feature is a claim that "this is known at prediction time". Most leakage enters as a feature computed with information from after the prediction moment or from the label itself, and it is invisible in the model's code. That is why point-in-time construction and out-of-fold statistics are principles, not niceties.

The maths

Standardisation. \(z_{ij} = (x_{ij} - \mu_j)/\sigma_j\) with \(\mu_j, \sigma_j\) computed on training rows; apply the same \(\mu_j, \sigma_j\) to every later row. For a linear model, standardising changes weights by \(w_j' = w_j\sigma_j\) and leaves predictions unchanged (OLS) or changes them (any penalised fit).

Box–Cox. For \(x > 0\), \(x^{(\lambda)} = (x^\lambda - 1)/\lambda\) for \(\lambda\ne0\) and \(\log x\) for \(\lambda = 0\); \(\lambda\) is chosen by maximum likelihood so that the transformed values are as close to Gaussian as possible. Yeo–Johnson extends it to zero and negative values.

Derivation: smoothed target encoding is a Beta–Binomial posterior mean

For a binary target, model each category's positive rate \(\theta_c\) with a prior \(\theta_c\sim\text{Beta}(\alpha, \beta)\) shared across categories. After observing \(s_c\) positives in \(n_c\) rows, the posterior is \(\text{Beta}(\alpha + s_c, \beta + n_c - s_c)\), with mean

\[ \mathbb{E}[\theta_c\mid\text{data}] = \frac{s_c + \alpha}{n_c + \alpha + \beta}. \]

Write \(m = \alpha + \beta\) (the prior's strength, in pseudo-observations) and \(p_0 = \alpha/m\) (the prior mean, usually the global rate). Then \(\alpha = m\,p_0\) and the posterior mean is \(\frac{s_c + m\,p_0}{n_c + m}\), the smoothed encoding. It is a weighted average of the category mean and the prior: \(\frac{n_c}{n_c+m}\bar y_c + \frac{m}{n_c+m}p_0\). Rare categories are pulled towards \(p_0\); common ones keep their own mean. Choosing \(m\) by maximising the marginal likelihood (or by cross-validation) is empirical Bayes, the same shrinkage idea as ridge regression and the James–Stein estimator.

Why in-sample target encoding leaks. Row \(i\) in category \(c\) has encoding \(\frac{s_c + m p_0}{n_c + m}\), where \(s_c\) includes \(y_i\). So \(\text{enc}_i\) moves by \(\frac{1}{n_c + m}\) when \(y_i\) flips from 0 to 1: for a category with \(n_c = 3\) and \(m = 0\), a third of the feature is the row's own label. Out-of-fold encoding computes \(s_c, n_c\) without row \(i\)'s fold, removing the dependence.

Hashing collisions. Hash \(n\) distinct values uniformly into \(B\) buckets. The probability that a given value shares its bucket with no other value is \((1 - 1/B)^{n-1}\approx e^{-(n-1)/B}\); the expected number of occupied buckets is \(B(1 - (1-1/B)^n)\). With signed hashing, a feature's hashed value is \(\sum_{j: h(j)=k}\xi(j)x_j\) with random signs \(\xi(j)\in\{\pm1\}\), so inner products are preserved in expectation: \(\mathbb{E}[\langle\phi(\mathbf{x}),\phi(\mathbf{x}')\rangle] = \langle\mathbf{x},\mathbf{x}'\rangle\) (Weinberger et al., 2009).

Cyclical encoding. For period \(T\), \(\phi(t) = (\sin\frac{2\pi t}{T}, \cos\frac{2\pi t}{T})\). Then \(\lVert\phi(t) - \phi(t')\rVert = 2\left|\sin\frac{\pi(t - t')}{T}\right|\), which depends only on the circular difference \(t - t'\) modulo \(T\).

Permutation importance. For a fitted model \(\hat f\), metric \(M\) (higher is better) and held-out data \(D\), \(\text{PI}_j = M(\hat f, D) - \mathbb{E}_\pi\big[M(\hat f, D^{(j,\pi)})\big]\), where \(D^{(j,\pi)}\) is \(D\) with column \(j\) permuted by \(\pi\); estimate the expectation by averaging several permutations, and report the spread.

In practice

  • Start from the prediction moment. Write down when the prediction happens and what is known then; build every feature as-of that time.
  • Use ColumnTransformer inside a Pipeline so each column type gets its transforms, and the whole thing is fitted inside cross-validation and shipped as one object.
  • Baseline ladder: a regularised linear model on standardised, one-hot, log-transformed features; then a gradient-boosted tree on minimally processed features with native categorical and missing-value handling; then feature work guided by error analysis. Feature ideas come from reading the examples the model gets wrong.
  • GBDT specifics: no scaling needed; one-hot is often worse than native categorical support or target encoding for high-cardinality columns; monotone constraints encode domain knowledge ("risk never falls as debt rises") and improve robustness.
  • Watch for proxies: a "customer service notes" field, a status column, or an ID that encodes signup order can leak or encode protected attributes (fairness).
  • Version and test features like code: unit tests for each transformation, checks on distributions between training and serving.

In Finny

Jarvis, Finny's assistant, does not feed raw financial records to a language model and hope. The FIRE planning engine computes the derived quantities that matter (the projected corpus year by year, the FIRE number, the year financial independence is reached) in ordinary code, and the model routes questions and explains those numbers. That is feature engineering as a design principle: compute what you can compute exactly, and give the learned component clean, meaningful inputs. See how Jarvis is built.

Common misconceptions

Deep learning made feature engineering obsolete

For images, audio and text, learned representations replaced hand-made features. For heterogeneous tables, engineered features plus tree ensembles remain strong defaults, and even tabular networks and foundation models benefit from point-in-time aggregates that no model can invent from a single row.

Target encoding is just a better one-hot

It is a supervised transformation that consumes labels, so it must be fitted out-of-fold and smoothed. Done naively it is one of the most effective ways to leak.

Feature importance tells you what drives the outcome

It tells you what the fitted model relies on. Correlated features share or steal importance, and a non-causal proxy can rank first. Causal questions need causal methods.

Build it

Target encoding three ways on a high-cardinality category (600 levels, about 7 training rows each) with a genuine per-category effect plus one numeric feature. NumPy only; logistic regression by Newton's method from the logistic regression page.

import numpy as np

rng = np.random.default_rng(7)
n, levels = 6000, 600                                   # ~7 training rows per category
effect = rng.normal(0, 1.0, levels)                     # true per-category log-odds shift
cat, x = rng.integers(0, levels, n), rng.normal(size=n)
y = (rng.random(n) < 1 / (1 + np.exp(-(-1 + effect[cat] + 0.8 * x)))).astype(float)
tr, te = np.arange(n) < 4000, np.arange(n) >= 4000

def target_encode(c_fit, y_fit, c_apply, m):            # smoothed mean: (sum + m*prior)/(count + m)
    prior = y_fit.mean()
    s, k = np.bincount(c_fit, y_fit, levels), np.bincount(c_fit, None, levels)
    enc, seen = np.full(len(c_apply), prior), k[c_apply] + m > 0   # unseen category -> prior
    enc[seen] = (s[c_apply][seen] + m * prior) / (k[c_apply][seen] + m)
    return enc

def out_of_fold(c, y, m, folds=5):                      # each row encoded without its own label
    enc, fold = np.empty(len(c)), np.arange(len(c)) % folds
    for f in range(folds):
        enc[fold == f] = target_encode(c[fold != f], y[fold != f], c[fold == f], m)
    return enc

def auc(y, s):
    r = np.argsort(np.argsort(s)) + 1; n1 = y.sum()
    return (r[y == 1].sum() - n1 * (n1 + 1) / 2) / (n1 * (len(y) - n1))

def fit_logreg(F, y, iters=25):                         # Newton / IRLS, tiny ridge for safety
    F = np.column_stack([np.ones(len(F)), F]); w = np.zeros(F.shape[1])
    for _ in range(iters):
        p = 1 / (1 + np.exp(-F @ w))
        H = F.T @ (F * (p * (1 - p))[:, None]) + 1e-6 * np.eye(len(w))
        w -= np.linalg.solve(H, F.T @ (p - y))
    return lambda G: np.column_stack([np.ones(len(G)), G]) @ w

for name, m, oof in [("naive in-sample mean (m=0)", 0, False),
                     ("smoothed in-sample (m=10)", 10, False),
                     ("smoothed out-of-fold (m=10)", 10, True)]:
    enc_tr = out_of_fold(cat[tr], y[tr], m) if oof else target_encode(cat[tr], y[tr], cat[tr], m)
    enc_te = target_encode(cat[tr], y[tr], cat[te], m)  # test rows: encoder fitted on all training rows
    model = fit_logreg(np.column_stack([enc_tr, x[tr]]), y[tr])
    print(f"{name:30s} train AUC {auc(y[tr], model(np.column_stack([enc_tr, x[tr]]))):.3f}"
          f"   test AUC {auc(y[te], model(np.column_stack([enc_te, x[te]]))):.3f}")
model = fit_logreg(x[tr, None], y[tr])
print(f"{'numeric feature only':30s} train AUC {auc(y[tr], model(x[tr, None])):.3f}"
      f"   test AUC {auc(y[te], model(x[te, None])):.3f}")

Output:

naive in-sample mean (m=0)     train AUC 0.844   test AUC 0.691
smoothed in-sample (m=10)      train AUC 0.838   test AUC 0.699
smoothed out-of-fold (m=10)    train AUC 0.723   test AUC 0.711
numeric feature only           train AUC 0.678   test AUC 0.661

The category carries real signal (every encoding beats the numeric feature alone on test). In-sample encodings report a training AUC about 0.15 too high and, because the model learned to trust a feature that contained its own labels, generalise worse. Smoothing alone barely helps; out-of-fold encoding makes the training score honest and gives the best test score.

Things to try

  • Set effect = np.zeros(levels) (the category is pure noise). The naive encoding still reports a high training AUC; the out-of-fold one correctly finds nothing.
  • Vary m over 0, 1, 10, 100 for the out-of-fold encoder and plot test AUC. Compare the best \(m\) with the empirical-Bayes value: the variance of the per-category rates relative to the sampling variance.
  • Replace the encoding with one-hot columns (600 of them) plus an L2 penalty in the Newton fit; compare test AUC and training time.
  • Hash the category into 64, 256 and 1,024 buckets before one-hot encoding and measure how collisions cost accuracy.
  • Add a feature that leaks, the label plus noise, and check that permutation importance on held-out data flags it as dominant.

Check yourself

Why don't decision trees need feature scaling or log transforms, and what transformation do they still need help with?

A split asks "is \(x_j \le t\)?"; any strictly increasing transform of \(x_j\) preserves the order of values, so the same partitions are available. Trees cannot natively compute sums, differences or ratios of columns (they approximate them with many axis-aligned steps), so features like debt-to-income still help. They also cannot extrapolate beyond the training range.

One-hot encode a column with 4 categories for a linear regression with an intercept. Why might the solver complain, and what are two fixes?

The 4 indicators sum to 1 in every row, equal to the intercept column, so \(X\) is rank-deficient and \(X^\top X\) is singular. Drop one category (it becomes the baseline absorbed by the intercept) or add a ridge penalty, which makes the solution unique.

A category has 2 rows, both positive; the global positive rate is 5%. Compute the smoothed target encoding with \(m = 20\), and say what it would be with \(m = 0\).

\((2 + 20\times0.05)/(2 + 20) = 3/22 \approx 0.136\). With \(m = 0\) it is \(1.0\), which is almost certainly noise.

You are predicting whether a customer will churn next month. Which of these features leak: (a) number of support tickets last month, (b) 'cancellation reason', © account age, (d) total spend this year computed on the day you built the dataset?

(b) leaks outright: it exists only for customers who churned. (d) leaks if the dataset is built after the prediction date, because "this year" includes the months after the prediction moment; compute it as of the prediction date. (a) and © are fine if computed as of the prediction date.

Why does a raw Unix timestamp make a poor feature, and what would you extract instead?

It is monotone in time, so a model using it learns time-period effects that never recur and cannot generalise to future timestamps outside the training range (trees will treat every future date like the latest training date). Extract recurring components (hour, weekday, month, holidays, encoded cyclically for non-tree models) and elapsed durations relative to meaningful events.

Permutation importance says neither 'income' nor 'monthly salary' matters, yet dropping both destroys accuracy. Explain.

They are nearly duplicates. Permuting one leaves the other to supply the same information, so each looks unimportant on its own. Permute correlated features together (grouped permutation importance) or cluster features before measuring importance.

Hard: argue from the data-processing inequality why feature engineering can still improve test accuracy even though it cannot increase the information about \(y\).

The inequality bounds what is achievable with infinite data and an unrestricted model. With finite data and a restricted model class, test error = approximation error + estimation error. A good feature map can make the Bayes-optimal predictor lie inside a simple class (reducing approximation error) and reduce the number of parameters needed (reducing estimation error), so the achievable error with \(n\) samples drops even though the infinite-data limit is unchanged.

Go deeper

Papers

Videos and lectures

Articles and courses

Code

Where this leads