Pulse Data Hub

Feature Engineering in Python: What Helps, Tested

Feature engineering in Python means building new columns from the ones you have so a model can see what matters. The advice online is often to add as many as possible. This guide tests that on the Titanic passenger list with cross-validation, and reports what helped, what did nothing and which model benefited. The honest result is that one feature did most of the work.

The data is the Titanic table (891 passengers, 38.4% survived). Our baseline has six columns: class, sex, age, siblings and spouses, parents and children, and fare. Each feature set is scored by 5-fold stratified cross-validation repeated 5 times (25 scores), for a logistic regression and a random forest. Code was run with pandas 3.0.5 and scikit-learn 1.9.1.

Bar chart of cross-validated accuracy for logistic regression: base features 79.3%, plus family size 80.2%, plus passenger title 82.4%, title and family 82.2%, all engineered features 82.0%.
Cross-validated accuracy of logistic regression as engineered features are added (5-fold, repeated 5 times).

Start with the baseline

import pandas as pd, numpy as np
from sklearn.model_selection import cross_val_score, RepeatedStratifiedKFold
from sklearn.ensemble import RandomForestClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import StandardScaler

url = "https://raw.githubusercontent.com/datasciencedojo/datasets/master/titanic.csv"
d = pd.read_csv(url)
cv = RepeatedStratifiedKFold(n_splits=5, n_repeats=5, random_state=0)
base = pd.DataFrame({"pclass": d.Pclass, "female": (d.Sex == "female").astype(int), "age": d.Age,
                     "sibsp": d.SibSp, "parch": d.Parch, "fare": d.Fare})

def score(X):
    lr = make_pipeline(SimpleImputer(strategy="median"), StandardScaler(), LogisticRegression(max_iter=2000))
    rf = make_pipeline(SimpleImputer(strategy="median"),
                       RandomForestClassifier(300, min_samples_leaf=3, random_state=0, n_jobs=2))
    return {n: round(float(cross_val_score(m, X, d.Survived, cv=cv).mean()), 4) for n, m in [("logistic", lr), ("forest", rf)]}

print("baseline:", score(base))

Output:

baseline: {'logistic': 0.793, 'forest': 0.8263}

The baseline is 0.793 for logistic regression and 0.826 for the forest. Every number below is compared with these, and since a forest with a different random seed moved by about 0.0025 in our checks, differences smaller than a quarter of a point should be read as noise. The imputer sits inside each pipeline, so the median age is learned only from the training fold; see train test split in Python for why that matters.

Feature 1: the title hidden in the name

The Name column looks useless, but it contains “Mr”, “Mrs”, “Miss” and “Master”. A regular expression pulls the title out.

d["title"] = d.Name.str.extract(r",\s*([^.]+)\.")[0].str.strip()
print(d.title.value_counts().head(6).to_dict())
print(d.groupby("title").agg(n=("Survived", "size"), survived=("Survived", "mean"),
                              age_missing=("Age", lambda x: x.isna().mean())).round(2)
        .sort_values("n", ascending=False).head(5))

Output:

{'Mr': 517, 'Miss': 182, 'Mrs': 125, 'Master': 40, 'Dr': 7, 'Rev': 6}
          n  survived  age_missing
title                             
Mr      517      0.16         0.23
Miss    182      0.70         0.20
Mrs     125      0.79         0.14
Master   40      0.57         0.10
Dr        7      0.43         0.14

There are 17 distinct titles, but four cover 864 of the 891 rows. Survival differs sharply: Mr 16%, Miss 70%, Mrs 79%, Master (boys aged 12 or under in this data) 57%. Sex already explains much of this, but “Master” separates boys from men, and age is missing for 23% of the Mr group. We keep the four common titles and group the rest as “Other”.

titles = pd.get_dummies(d.title.where(d.title.isin(["Mr", "Mrs", "Miss", "Master"]), "Other")).astype(int)
print("+ title:", score(pd.concat([base, titles], axis=1)))

Output:

+ title: {'logistic': 0.8242, 'forest': 0.8321}

Logistic regression jumps from 0.793 to 0.824, a gain of 3.1 points. The forest improves from 0.826 to 0.832, only 0.6 points. That gap is the lesson: a random forest could already find most of this structure from sex, age and class by itself, while a linear model needed it handed over. Feature engineering helps simple models far more than flexible ones.

Feature 2: family size

d["family"] = d.SibSp + d.Parch + 1
print(d.groupby("family").Survived.agg(["size", "mean"]).round(3).T)
fam = pd.DataFrame({"family": d.family, "alone": (d.family == 1).astype(int)})
print("+ family:", score(pd.concat([base, fam], axis=1)))

Output:

family       1        2        3       4     5       6       7    8    11
size    537.000  161.000  102.000  29.000  15.0  22.000  12.000  6.0  7.0
mean      0.304    0.553    0.578   0.724   0.2   0.136   0.333  0.0  0.0
+ family: {'logistic': 0.802, 'forest': 0.8245}

The survival table is not a straight line. Passengers alone (537 of them) survived at 30.4%, families of 2 to 4 at 55% to 72%, and families of five or more between 0% and 33% (none of the 13 passengers in families of 8 or 11 survived). That pattern is why a single “family size” number is only a rough summary. The score gain is small: logistic regression 0.793 to 0.802 (+0.9) and the forest 0.826 to 0.8245, which is no gain. Trees can already add SibSp and Parch on their own.

Feature 3: transforming a skewed column

print("fare skewness:", round(d.Fare.skew(), 2), "-> after log1p:", round(np.log1p(d.Fare).skew(), 2))
logfare = base.assign(fare=np.log1p(base.fare))
print("log fare:", score(logfare))

Output:

fare skewness: 4.79 -> after log1p: 0.39
log fare: {'logistic': 0.7953, 'forest': 0.8263}

Fare is strongly right-skewed (skewness 4.79, down to 0.39 after a log transform). Replacing fare with its log changes the logistic regression only from 0.793 to 0.795, and the forest score is identical to four decimals (0.8263). Trees split on order, not on size, so a monotonic transform cannot change them. A log transform matters more for models that use distances or linear coefficients on skewed data with outliers, and for plots; here it did not matter.

Feature 4: a missing-value flag, and a warning

d["has_cabin"] = d.Cabin.notna().astype(int)
print("cabin missing:", round(d.Cabin.isna().mean(), 3), "| survival with / without a cabin:",
      d.groupby("has_cabin").Survived.mean().round(3).to_dict())
print("+ has_cabin:", score(pd.concat([base, d[["has_cabin"]]], axis=1)))

Output:

cabin missing: 0.771 | survival with / without a cabin: {0: 0.3, 1: 0.667}
+ has_cabin: {'logistic': 0.798, 'forest': 0.8202}

Cabin is missing for 77.1% of passengers, and survival is 66.7% for those with a cabin recorded against 30.0% without. It looks like a strong feature, yet adding it scored 0.798 for logistic regression (+0.5) and lowered the forest to 0.820. It mostly repeats information that class already contains: a cabin is recorded for 81.5% of first-class passengers, 8.7% of second class and 2.4% of third. There is also a risk I could not test: records may have been completed after the event, so the flag could reflect who survived to be asked. Treat a missingness flag as a hypothesis about how the data was collected, not as a free feature.

Putting it together

allx = pd.concat([base, titles, fam, d[["has_cabin"]], pd.DataFrame({"logfare": np.log1p(d.Fare)})], axis=1)
print("all engineered features:", score(allx))

Output:

all engineered features: {'logistic': 0.8197, 'forest': 0.8303}

With everything added, logistic regression reaches 0.820 and the forest 0.830. Title and family together gave 0.822 and 0.831, so the extra columns on top of title did not help. In plain numbers: the title feature added about 3 points for the linear model and 0.6 for the forest, family size 0.9 and none, the log of fare and the cabin flag about nothing. If you have time for one feature, find the one that carries information the model cannot reconstruct. Five more columns did not make it better.

A checklist for feature engineering in Python

Add features one at a time and score each with cross-validation, as in cross-validation in Python, rather than all at once. Keep a note of the noise level: repeat with a different seed and ignore changes smaller than that. Build features inside the training fold when they use statistics, such as target encoding or medians. Check each feature for leakage, meaning it would not be available when the model is used. After the engineering, look for impossible values with outlier detection in Python, and for the first look at any new table use exploratory data analysis in Python.

The scikit-learn guide to preprocessing data covers scalers and encoders, and the data is from the datasciencedojo datasets repository. This is one dataset with 891 rows, so the sizes of the gains should not be copied to other problems. Not tested: target encoding, binning age, interaction terms, and gradient boosting.

FAQ

What is feature engineering in Python?

Creating new input columns from existing data, such as a title from a name or a family size from two counts, so that a model can use information it could not see before.

Does feature engineering always improve a model?

No. In our test the title feature added 3.1 points to logistic regression but 0.6 to a random forest, and a log transform and a cabin flag added about nothing.

Do tree models need scaling or log transforms?

No. Trees split on the order of values, so scaling and monotonic transforms do not change them. The forest scored 0.8263 with and without the log of fare.

How do I avoid leakage when engineering features?

Fit anything that learns from the data, such as imputers, scalers and encoders, inside a pipeline so it is computed on the training fold only, and ask whether each feature would exist at prediction time.

Newsletter Signup Form

Latest tutorials

Latest articles

On this page
Verified by MonsterInsights