Semester 1 · Week 11
Feature engineering and feature selection
- Ch 14 Feature Engineering
- Ch 15 Feature Selection & Dimensionality Reduction
+ Research challenge starts
Chapter 14: Feature engineering
What information is hiding in this column that the model can't see?
Notes · slide 2
Time: 50 minutes for two chapters. About 20 on Chapter 14, 22 on Chapter 15, 3 to launch the research challenge, and 5 to check understanding.
Say: Cross-validation is set up. Several algorithms are tried. Accuracy is stuck. Often the bottleneck isn't the model. It's the features. A model can only use the signal it's given.
Key line: ask of every column: what information is hiding here that the model can't see?
Next: what a feature is.
What a feature is
- A measurable property of an observation that a model uses to predict.
- Feature engineering makes patterns easier to learn.
- A datetime hides day of week, hour, holidays, and recency.
- An address hides a city, a region, a distance.
The model can only use what you make visible.
Notes · slide 3
Say: A feature is a measurable property a model uses to predict. Feature engineering makes patterns easier to learn.
Say: One datetime column hides day of week, time of day, holidays, and how recent something was. An address hides a city, a region, and a distance. The model sees an opaque value unless you pull these out.
Ask: "What's hiding in an email address?" Listen for: the domain, a work or personal account, maybe a company.
Next: transforming numbers.
Numeric transformations
| Transform | When |
|---|---|
StandardScaler |
Linear and distance-based models. The default |
MinMaxScaler |
Bounded inputs, e.g. neural networks |
RobustScaler |
Real outliers present |
| Log | Right-skewed values: income, fares, counts |
| Binning, polynomials | Thresholds, curves for linear models |
Trees split on thresholds. They need no scaling.
Notes · slide 4
Say: Scaling matters for linear and distance-based models. Income in thousands drowns out age in tens. StandardScaler is the default. MinMax suits bounded inputs. RobustScaler uses the median and IQR, so it suits real outliers.
Say: Log transforms tame right-skewed values: income, prices, counts. Polynomial terms let a linear model bend. Binning suits step-like effects, such as age bands.
Key line: trees split on thresholds, so they need no scaling. Don't waste time scaling for a forest.
Next: what a log transform does.
A log transform

A long right tail becomes close to symmetric. Linear models fit it better.
Notes · slide 5
Say: 2,000 synthetic incomes. Raw, the mean of 44,543 sits well above the median of 37,302: a long right tail. After log1p, mean and median are both 10.527. Close to symmetric.
Say: Use log1p, not log, when the column can be zero. log(0) is minus infinity.
Ask: "Which of your capstone columns would you log?" Listen for: anything money- or count-like with a long tail.
Next: encoding categories.
Encoding categories
| Encoding | Use for | Watch out |
|---|---|---|
| One-hot | Nominal, under ~20 values | Width explodes with cardinality |
| Ordinal | Real order: poor < fair < good | False order misleads linear models |
| Target | High cardinality | Leaks the label unless done per fold |
| Frequency | High cardinality, no target needed | Ties between equal counts |
Notes · slide 6
Say: One-hot gives a column per category. Best for unordered categories with under about 20 values. Ordinal gives integers. Only safe with a real order, or for trees. A linear model treats category 2 as twice category 1.
Say: Target encoding replaces each category with its average label. It handles postcodes or product IDs, but leaks unless computed out-of-fold. Frequency encoding uses how often a category appears. It never sees the label, so it can't leak.
Ask: "10,000 product IDs. One-hot?" Listen for: no. Too many columns. Target or frequency encoding.
Next: datetimes.
Datetimes and cycles
- Extract hour, day of week, month, weekend, holiday, days since.
- Raw hours get distance wrong: 23 and 0 are one hour apart, not 23.
- Map cycles onto a circle:
xsin=sin(242πh)xcos=cos(242πh)
Notes · slide 7
Say: Pull out hour, day of week, month, weekend, holiday, and days since an event. Then fix cycles. As a raw number, hour 23 is 23 away from hour 0. In reality it's one hour.
Say: Map the cycle onto a circle with sine and cosine. You need both. Sine alone gives two hours of the day the same value.
Next: the picture.
Hours on a circle

As raw numbers, 23 and 0 sit at opposite ends. As sine and cosine, they sit side by side.
Notes · slide 8
Say: Left: raw hours in a row, so 23 and 0 sit at opposite ends. Right: the same hours as sine and cosine coordinates. They form a clock face, and 23 sits next to 0.
Lab: the lab asks learners to check that hour 23 and hour 0 end up close together, not assume it. Cyclic encoding needs this picture. Put it on the board if anyone is stuck.
Next: combining features.
Interactions and domain features
- Interactions: products and ratios. A big house in an expensive area is worth more than the two premiums added.
- Domain features beat generic ones. For churn, RFM: recency, frequency, monetary value.
The best feature engineers talk to domain experts before they write code.
Notes · slide 9
Say: An interaction is a product or ratio of two features. A big house in an expensive area is worth more than the two premiums added. Trees build interactions through their splits. Linear models need them written out.
Say: Domain features usually beat generic ones. For churn, RFM: recency, frequency, and monetary value. Direct-mail marketers used it by hand for decades before machine learning.
Key line: the best feature engineers talk to domain experts before they write code.
Next: keeping it leak-free.
Leakage-safe pipelines
- Every transform that learns from data (scalers, imputers, encoders) must be fit on training folds only.
- Wrap them in a
ColumnTransformerinside aPipeline. - Validate every new feature with cross-validation. More features means more room to overfit.
Notes · slide 10
Say: Anything that learns from data, such as a scaler, imputer, or encoder, is fit on training folds only. Wrap them in a ColumnTransformer inside a Pipeline, and cross-validate the whole thing.
Say: Every new feature adds room to overfit. Check each one with cross-validation, not by eye.
Lab: Bike Sharing's casual and registered add up to the target. The lab drops them. Ask learners why.
Next: measuring a leak.
Worked example: target-encoding a customer ID
4,000 orders. Encode customer_id two ways.
| Encoding | CV R2 | Test R2 |
|---|---|---|
| Leaky: mean over all data | 0.872 | 0.870 |
| Safe: fold-holdout | 0.870 | 0.867 |
| Dropped entirely | 0.870 | 0.867 |
The leak inflates scores in the predicted direction. Here the gap is small, because the ID carries little signal.
Notes · slide 11
Say: 4,000 orders. Encode customer ID with a mean over all the data and CV R² is 0.872. Encode it out-of-fold and it's 0.870. Drop the column entirely: 0.870.
Say: The leak inflates the score in the direction the warning predicts. Here only a little, because customer ID carries almost no signal. A column that indirectly encodes the label would leak far more.
Key line: leakage damage scales with how strongly the leaked column relates to the target. Measure the gap. Don't assume its size.
Next: the chapter in one idea.
Mental model
Features are the vocabulary a model uses to describe an observation.
Feature engineering is translation: from raw measurements into the numbers that carry signal.
Notes · slide 12
Say: Features are the vocabulary a model uses to describe an observation. Feature engineering is translation: from raw measurements into numbers that carry signal.
Next: Chapter 15, pruning what we made.
Chapter 15: Feature selection and dimensionality reduction
Generate too much, then prune.
Notes · slide 13
Time: about 22 minutes for this chapter.
Say: Feature engineering fills a table with columns. Past a point, more columns hurt. Models overfit, training slows, and distance-based methods stop behaving.
Key line: generate too much, then prune. Selection keeps original columns. Extraction builds new, blended ones.
Next: why prune.
Why prune?
- Chapter 14 deliberately makes more columns than a model needs.
- Hundreds of redundant or irrelevant features don't just slow training. They give the model more noise to fit.
- Goal: the smallest feature set that keeps everything useful.
- Select existing features, or extract new compact ones.
Notes · slide 14
Say: Chapter 14 makes more columns than a model needs on purpose. It's safer to generate too much and prune than to miss a signal.
Say: Hundreds of redundant columns don't just slow training. They give the model more noise to fit.
Key line: the goal is the smallest feature set that keeps everything useful.
Next: what goes wrong in high dimensions.
The curse of dimensionality
As features grow:
- Distances stop meaning much. Nearest and farthest neighbours end up almost equally far.
- Data gets sparse. Keeping density needs exponentially more rows.
- Overfitting gets easier. More dimensions, more room for noise.
KNN and k-means suffer first.
Notes · slide 15
Say: Picture a million points in a unit cube. In 3 dimensions, neighbours are about 1/100 of the side apart. Same million points in 20 dimensions: about half the side apart. Matching the 3D density in 20D would need 10⁴⁰ points.
Say: So distances lose meaning, data gets sparse, and overfitting gets easier. KNN and k-means suffer first.
Key line: adding dimensions doesn't make data a little sparser. It makes it exponentially sparser.
Next: three ways to select.
Three ways to select
| Family | How | Example |
|---|---|---|
| Filter | Score each feature alone, keep the best | Variance threshold, correlation, mutual information |
| Wrapper | Search subsets with a real model | Recursive feature elimination (RFE) |
| Embedded | Selection happens during training | Lasso, tree importance |
Notes · slide 16
Say: Filters score each feature alone: variance, correlation, mutual information. Fast, but blind to how features work together. Wrappers search subsets with the real model, as RFE does. Thorough, slower, and tied to that model. Embedded methods select while training: Lasso zeroes coefficients, and trees rank features.
Key line: embedded methods are the best default for most tabular problems. Treat their scores as a hint.
Ask: "Which family would miss a U-shaped feature?" Listen for: a correlation filter.
Next: building new features instead.
PCA: build new features
- Find the direction of greatest variance: the first principal component.
- Then the next, orthogonal to it. And so on.
- The components are eigenvectors of the covariance matrix:
Σv=λv
- Keep enough components to explain, say, 95% of the variance.
Kernel PCA handles non-linear structure. It's a different tool, not an upgrade.
Notes · slide 17
Say: PCA finds the direction the data varies most along: the first component. Then the next, at right angles to it. These are eigenvectors of the covariance matrix, from week 2.
Say: Standardise first. Variance depends on units, so dollars would dominate years.
Say: The cost is meaning. Component 1 is a blend like 0.31 × income − 0.22 × age. Hard to explain to a regulator.
Next: methods for looking, not modelling.
t-SNE and UMAP
- Non-linear, for visualisation in 2 or 3 dimensions.
- Preserve local neighbourhoods, so clusters show up.
- Cluster sizes and gaps between clusters can mislead.
- Don't use them as model inputs.
Notes · slide 18
Say: Both are non-linear and squeeze data into 2 or 3 dimensions to look at. They keep local neighbourhoods, so clusters show up.
Say: Three cautions. Gaps between clusters and cluster sizes can mislead. Results change with the seed and settings. And classic t-SNE has no way to transform new data.
Key line: use them to look at data. Use PCA or selection when reduced features feed a model.
Next: the same data three ways.
PCA and UMAP on the same data

One noisy column dominates the variance. PCA chases it and merges two of the three clusters. UMAP recovers part of the structure, not all of it.
Notes · slide 19
Say: Three clusters, plus one noisy column with huge variance. PCA chases that column and merges two clusters. Silhouette 0.007. UMAP does better at 0.077, but it's partial.
Say: Default t-SNE scores 0.003, worse than PCA. With perplexity 12, it reaches 0.107, better than UMAP.
Key line: settings matter as much as the method. Look at the real picture with real numbers.
Next: choosing.
Selection or extraction?
- Selection keeps meaning: "we use income and tenure."
- Extraction removes more redundancy but loses interpretability.
- Tree ensembles already cope well with irrelevant features. Check you need this at all.
Notes · slide 20
Say: Selection keeps meaning. You can say "we use income and tenure". Extraction removes more redundancy but loses that.
Say: Check you need either. Tree ensembles cope well with irrelevant features. They won't split on what doesn't help. Selection matters most for linear and distance-based models, or when cost or explanation matters.
Next: the worked example.
Worked example: 50 features, 10 real
10 informative, 10 redundant, 30 noise. Random forest on each set:
| Method | Features | Test accuracy |
|---|---|---|
| Wrapper: RFECV | 26 | 0.928 |
| Embedded: RF importance | 25 | 0.922 |
| Baseline: all features | 50 | 0.912 |
| Filter: mutual information | 15 | 0.884 |
| Extraction: PCA | 37 | 0.868 |
Selection with a real model beats using everything, with half the columns.
Notes · slide 21
Say: A synthetic dataset: 10 informative features, 10 redundant blends of them, and 30 pure noise. Random forest on each selected set.
Say: RFECV and forest importance beat using all 50, with about half the columns. The mutual information filter and PCA fall below the baseline.
Key line: selection with a real model beat using everything.
Ask: "Why might the filter have lost?" Listen for: it scores each feature alone, and keeping only 15 may cut useful ones.
Next: why PCA struggled.
Worked example: why PCA struggled
- It needed 37 components to reach 95% variance.
- After scaling, every column has equal variance. The 30 noise columns hold about 60% of it.
- PCA ranks directions by variance alone. It can't tell noise from signal.
Notes · slide 22
Say: PCA needed 37 components to reach 95% of the variance. After scaling, every column has equal variance, so the 30 noise columns hold about 60% of the total.
Key line: PCA is unsupervised. It never looks at the target, so it can't prefer informative directions over noisy ones.
Next: next week's research challenge.
Next week: the research challenge
- In pairs, pick one metric the book doesn't cover. Each metric goes once.
- Build it from scratch, find where it misleads, write a one-page card.
- Teach it to the class in five minutes, in week 12.
The menu and the checklist are on the research challenge page.
Notes · slide 23
Say: In pairs, pick one metric the book doesn't cover. Build it from scratch in NumPy, find a case where it misleads, write a one-page card, and teach it to the class in five minutes next week. It's marked done or not yet.
Do: have pairs claim metrics before they leave, on a shared list. Each metric goes once. Fourteen are on the menu.
Say: If there are more pairs than metrics, two pairs can take the same metric on different data.
Next: back to this week's mental model.
Mental model
- Feature engineering fills the toolbox.
- Selection removes tools you won't use.
- Extraction welds overlapping tools into one.
- An overflowing toolbox slows everything down.
Notes · slide 24
Say: Feature engineering fills the toolbox. Selection removes the tools you won't use. Extraction welds overlapping tools into one. An overflowing toolbox slows everything down.
Next: check yourself.
Check yourself
- Why does one-hot encoding suit a linear model better than ordinal encoding for colours?
- How do you target-encode without leaking?
- Why might PCA throw away the most useful direction?
- Can you use a t-SNE plot to justify a claim about cluster sizes?
Notes · slide 25
Do: pairs, three minutes, then take answers.
Answers: 1. Ordinal encoding gives colours a false order. 2. Fit the encoding out-of-fold, inside the pipeline. 3. It maximises variance, and a low-variance direction can carry the signal. 4. No. t-SNE distorts sizes and distances.
Say: Remind pairs to confirm their metric for the research challenge before they leave.
This week
- Read Chapter 14: Feature Engineering.
- Read Chapter 15: Feature Selection & Dimensionality Reduction.
- Take the Chapter 14 quiz.
- Take the Chapter 15 quiz.
- Run the notebooks: Chapter 14 (opens in a new tab),Chapter 15 (opens in a new tab).
- Optional: the further reading for week 11.
Slide 1 of 26: Feature engineering and feature selection
Keys: → or Space next · ← back · Home/End · F full screen · N notes. Swipe on touch screens. "Save as PDF" opens the print dialog with one slide per page: choose "Save as PDF" as the printer. "Print handout" adds the speaker notes, in black on white.