🎓 A1Learner
🔍
0 of 50 lessons completed

Python ML Feature Selection and Feature Engineering

Feature engineering builds a new column from old ones. Feature selection keeps only the columns that help.

Build family size from two columns

Family size adds sibsp and parch, plus one for the passenger. The first five rows show the new column.

import seaborn as sns
df = sns.load_dataset("titanic")
df["family_size"] = df["sibsp"] + df["parch"] + 1
print(list(df["family_size"].head()))

Survival changes with family size

Families of one survive least often. Families of four survive most often in this table.

import seaborn as sns
df = sns.load_dataset("titanic")
df["family_size"] = df["sibsp"] + df["parch"] + 1
rates = df.groupby("family_size")["survived"].mean().round(2)
print("Family of 1:", rates.loc[1])
print("Family of 2:", rates.loc[2])
print("Family of 4:", rates.loc[4])

Keep only the columns you need

Selection drops sibsp and parch once family size exists. Four columns stay.

import seaborn as sns
df = sns.load_dataset("titanic")
df["family_size"] = df["sibsp"] + df["parch"] + 1
X = df[["age", "fare", "family_size", "sex"]]
print(X.shape)

Example

import numpy as np
import seaborn as sns
from sklearn.ensemble import RandomForestClassifier
from sklearn.impute import SimpleImputer
from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import OneHotEncoder, StandardScaler

df = sns.load_dataset("titanic")
df["family_size"] = df["sibsp"] + df["parch"] + 1
y = df["survived"]

def prep(numbers, X_train, X_test):
    imputer = SimpleImputer(strategy="median")
    scaler = StandardScaler()
    numbers_train = scaler.fit_transform(imputer.fit_transform(X_train[numbers]))
    numbers_test = scaler.transform(imputer.transform(X_test[numbers]))
    encoder = OneHotEncoder(handle_unknown="ignore", sparse_output=False)
    words_train = encoder.fit_transform(X_train[["sex"]])
    words_test = encoder.transform(X_test[["sex"]])
    return np.hstack([numbers_train, words_train]), np.hstack([numbers_test, words_test])

# Baseline: the two old columns, sibsp and parch.
X_base = df[["age", "fare", "pclass", "sibsp", "parch", "sex"]]
Xb_train, Xb_test, yb_train, yb_test = train_test_split(X_base, y, test_size=0.2, random_state=42)
Xb_train_ready, Xb_test_ready = prep(["age", "fare", "pclass", "sibsp", "parch"], Xb_train, Xb_test)
base = RandomForestClassifier(random_state=42)
base.fit(Xb_train_ready, yb_train)
base_score = accuracy_score(yb_test, base.predict(Xb_test_ready))

# New feature: one family_size column instead of the two old ones.
X_new = df[["age", "fare", "pclass", "family_size", "sex"]]
Xn_train, Xn_test, yn_train, yn_test = train_test_split(X_new, y, test_size=0.2, random_state=42)
Xn_train_ready, Xn_test_ready = prep(["age", "fare", "pclass", "family_size"], Xn_train, Xn_test)
new = RandomForestClassifier(random_state=42)
new.fit(Xn_train_ready, yn_train)
new_score = accuracy_score(yn_test, new.predict(Xn_test_ready))

rates = df.groupby("family_size")["survived"].mean().round(2)
print("Survival rate, family of 1:", rates.loc[1])
print("Survival rate, family of 4:", rates.loc[4])
print("Baseline score:", round(base_score, 4))
print("Family size score:", round(new_score, 4))

Key points

  • Feature engineering: building a new column from columns you already have
  • sibsp: the count of siblings and spouses on board
  • parch: the count of parents and children on board
  • Use family_size = sibsp + parch + 1 to count the whole family on board
  • Feature selection: keeping only the columns that help the model
  • Use a model score to judge a new column, because a helpful column raises the score

In this example, family size is built first from sibsp and parch, plus one for the passenger. A random forest trains on the two old columns and scores the test rows. Then a second forest trains on the single new column instead. The survival rates show why the new column helps: a family of one survives 0.3 of the time, while a family of four survives 0.72 of the time. The new column packs that pattern into one number, and the score rises. The old columns are dropped, so the model keeps fewer columns and still scores better.

Note

A new column can also hurt, so test it and keep only what helps.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Python Playground

Exercise

A passenger has sibsp 1 and parch 2. What is the family size?