Sub topic 1
What Feature Engineering Is and Why It Matters
Prerequisites
This chapter assumes you know basic Python and pandas, and the core supervised learning ideas: features, labels, and training and test sets. You should also be comfortable with scikit-learn's fit and predict workflow, and with the mean, variance and distributions from basic statistics.
What a feature is
A feature is one input column that a model uses to predict the target. Raw data rarely arrives in a form a model can use. It has missing cells, text labels, timestamps and values on very different scales. Feature engineering is the work of turning that raw data into columns that a model can learn from. It covers cleaning, transforming, encoding, creating and selecting features.
Why it matters
A model can only learn patterns that its inputs make visible. Three examples show how.
- A timestamp such as
2024-03-02 23:40:00is not a useful number. The hour, the day of the week and a weekend flag may each carry signal. - A city name is a string. Most scikit-learn models need numbers, so the city must be encoded.
- Income may be skewed, with a few very large values. A log transform can make it easier for a linear model to use.
Good features often move quality as much as swapping one algorithm for another. A simple model with informative features can beat a complex model fed raw columns. Features also affect training speed, how easy the model is to interpret, and how well it holds up on new data.
Where it fits in the workflow
The order in this diagram matters. The split comes before any step that learns from the data. Later chapters explain why.
A first example
This example shows the effect of one engineered feature. The target depends on the ratio of two columns, which a linear model cannot form by itself.
import numpy as np
import pandas as pd
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score
rng = np.random.default_rng(0)
n = 2000
df = pd.DataFrame({
"debt": rng.uniform(1_000, 50_000, n),
"income": rng.uniform(10_000, 100_000, n),
})
y = (df["debt"] / df["income"] > 0.5).astype(int)
raw = cross_val_score(LogisticRegression(max_iter=1000), df, y, cv=5)
df["debt_to_income"] = df["debt"] / df["income"]
engineered = cross_val_score(LogisticRegression(max_iter=1000), df, y, cv=5)
print(f"raw columns: {raw.mean():.3f}")
print(f"with ratio feature: {engineered.mean():.3f}")The second score is clearly higher. The model and its settings did not change. Only the input did. The ratio is a feature created from domain knowledge: lenders care about debt relative to income.
Common errors
- Fitting on all the data. Computing a mean, a scaler or an encoding on the full dataset before splitting lets test information leak into training. Scores then look better than real performance.
- Treating every column the same. Numeric, categorical, date-time and text columns need different treatment.
- Adding features without measuring. Each change should be checked with cross-validation, not judged by feel.
- Different logic in training and serving. If production code computes a feature differently from training code, predictions degrade silently.
What comes next
The following chapters cover each kind of column and each technique in turn. They begin with column types, then data leakage, which shapes every later choice.
Exercise
A teammate standardizes all columns using the mean and standard deviation of the full dataset, then splits into train and test sets. What is wrong with this, and what should they do instead?
Show answer
The test rows influenced the mean and standard deviation, so information from the test set leaked into training and the test score will be optimistic. They should split first, fit the scaler on the training set only, and apply it to the test set. A Pipeline does this automatically.
Exercise
Name two reasons a timestamp column is not directly useful to most models, and one feature you could build from it.
Show answer
It is a string or an opaque number that does not expose patterns such as time of day or weekday, and a plain number does not show that hour 23 is close to hour 0. You could extract the hour, the day of the week or a weekend flag.