S30 Logo
S30 AI Labwww.thes30.com
Back
#19

Feature Engineering Strategies

Medium🔍 Evaluation & DebuggingW5 D1

Before You Start

Required knowledge
Missing-value handling, pandas feature creation, pipelines, and cross-validation.
Libraries used
NumPy, pandas, scikit-learn
Dataset and source
Optional local Titanic CSV; otherwise a fixed 50-row synthetic passenger table with Name, Cabin, and missing Age values.
Expected output
Comparisons of missingness indicators, Title encoding, intentionally leaky target encoding, log Fare, and interaction features; accuracy need not improve each time.

Feature Engineering Strategies — Theory & Concepts

Read this before attempting the exercises. Feature engineering is the most impactful skill in applied ML. Better features > better models.


1. Why Feature Engineering Matters

Raw features + XGBoost:     AUC = 0.82
Engineered features + LR:   AUC = 0.87  < simpler model, better result

Andrew Ng: "Applied ML is basically feature engineering."


2. Numeric Transformations

# Log transform (right-skewed data like income, prices)
df['log_income'] = np.log1p(df['income'])  # log1p handles zeros

# Binning (convert continuous to categorical)
df['age_group'] = pd.cut(df['age'], bins=[0, 18, 35, 55, 100],
                         labels=['young', 'adult', 'middle', 'senior'])

# Polynomial features
df['age_squared'] = df['age'] ** 2

# Interactions
df['income_per_age'] = df['income'] / (df['age'] + 1)

3. Categorical Encoding

MethodWhen to UseExample
One-hotLow cardinality (<20 categories)country → [0,1,0,0]
Label encodingOrdinal categorieseducation: HS=0, BS=1, MS=2
Target encodingHigh cardinalityzip_code → mean(target) per zip
Frequency encodingWhen count matterscity → count of city in data
Hash encodingVery high cardinalityuser_id → hash bucket

FAANG Gotcha: Target encoding leaks information. Always compute on training folds only (use cross-validation).


4. DateTime Features

df['hour'] = df['timestamp'].dt.hour
df['day_of_week'] = df['timestamp'].dt.dayofweek
df['is_weekend'] = df['day_of_week'].isin([5, 6]).astype(int)
df['month'] = df['timestamp'].dt.month
df['days_since_signup'] = (df['event_time'] - df['signup_time']).dt.days

# Cyclical encoding (so hour 23 is close to hour 0)
df['hour_sin'] = np.sin(2 * np.pi * df['hour'] / 24)
df['hour_cos'] = np.cos(2 * np.pi * df['hour'] / 24)

5. Aggregation Features (GroupBy)

# User-level features from transaction data
user_features = transactions.groupby('user_id').agg(
    total_spend=('amount', 'sum'),
    avg_spend=('amount', 'mean'),
    n_transactions=('amount', 'count'),
    days_active=('date', lambda x: (x.max() - x.min()).days),
    n_unique_merchants=('merchant', 'nunique'),
)

6. Text Features

# Basic
df['text_length'] = df['text'].str.len()
df['word_count'] = df['text'].str.split().str.len()
df['has_url'] = df['text'].str.contains('http').astype(int)

# TF-IDF
from sklearn.feature_extraction.text import TfidfVectorizer
tfidf = TfidfVectorizer(max_features=5000, ngram_range=(1, 2))
X_text = tfidf.fit_transform(df['text'])

7. Feature Selection

# Correlation filter
high_corr = corr_matrix[abs(corr_matrix) > 0.95].stack()

# Mutual information
from sklearn.feature_selection import mutual_info_classif
mi = mutual_info_classif(X, y)

# Recursive Feature Elimination
from sklearn.feature_selection import RFECV
selector = RFECV(estimator, cv=5, scoring='roc_auc')

Now you're ready to attempt the exercises. Switch to the Exercise tab and start coding!

Ready to practice?

Python 3 — Notebook
0/7 solvedSubstack Notes
1
Dataset & Setup

Feature Engineering Strategies — Student Lab (Titanic)

Focus: missing data, encoding, nonlinear transforms, and interactions — leakage-safe.

Section 0 — Load Titanic (Kaggle) with fallback

Expected: data/titanic/train.csv

If missing, a tiny synthetic dataset is used so the notebook runs.

Loading editor...
1

Baseline pipeline

2
Train a baseline with leakage-safe preprocessing

Section 1 — Baseline pipeline

Task 1.1: Train a baseline with leakage-safe preprocessing

Use:

  • ●

    Numeric: Age, Fare, SibSp, Parch

  • ●

    Categorical: Pclass, Sex, Embarked

  • ●

    Create X/y

  • ●

    Build ColumnTransformer (impute + scale numeric, impute + one-hot categorical)

  • ●

    Evaluate LogisticRegression with StratifiedKFold CV

Checkpoint: Why is the pipeline necessary to avoid leakage in CV?

Loading editor...
2

Missing data: indicators

3
Add missingness indicator features

Section 2 — Missing data: indicators

Task 2.1: Add missingness indicator features

Add: Age_is_missing, Cabin_is_missing

  • ●Create these columns
  • ●Add them to numeric pipeline
  • ●Re-run CV and compare

Checkpoint: Why can missingness itself be predictive?

Loading editor...
3

Encoding: One-hot vs Target encoding

4
Extract Title from Name and one-hot encode

Section 3 — Encoding: One-hot vs Target encoding

Task 3.1: Extract Title from Name and one-hot encode

Example titles: Mr, Mrs, Miss, Master.

  • ●Extract Title with regex
  • ●Add it as categorical feature
  • ●Re-run CV
Loading editor...
5
Naive target encoding (demonstrate leakage)

Task 3.2: Naive target encoding (demonstrate leakage)

We will intentionally do something wrong: compute mean Survived per Title using the full dataset, then map it back.

  • ●Create Title_target_mean using full data (this is leakage)
  • ●Compare CV score and explain why it inflates

Checkpoint: How do you fix target encoding correctly?

Loading editor...
4

Nonlinear transforms + binning

6
Log-transform Fare

Section 4 — Nonlinear transforms + binning

Task 4.1: Log-transform Fare

Loading editor...
5

Interaction features

7
FamilySize and IsAlone

Section 5 — Interaction features

Task 5.1: FamilySize and IsAlone

FamilySize = SibSp + Parch + 1 IsAlone = FamilySize == 1

Task 5.2: Sex × Pclass cross

Create a categorical cross feature like Sex_Pclass.

Loading editor...

Need help? Share feedback