Feature Engineering

Updated · 8 min read
mediumPython 3.13aimachine-learningfeature-engineeringpreprocessingpipelinesscikit-learn

Feature engineering is preparing and creating the inputs a model learns from. Real data arrives with text categories, missing values and numbers on very different scales, and models need clean numbers. Good features often matter more than the choice of algorithm.

Kinds of Feature Work

TaskDescriptionscikit-learn tool
EncodingIt is used to turn text categories into numbersOneHotEncoder, OrdinalEncoder
Filling missing valuesIt is used to replace gaps with a sensible valueSimpleImputer
ScalingIt is used to put numbers on similar scalesStandardScaler, MinMaxScaler
Creating featuresIt is used to add new columns that make patterns easier to learnpandas, FunctionTransformer
Combining it allIt is used to apply different steps to different columnsColumnTransformer in a pipeline

Creating Messy Data

Real school records are messier than the clean file used so far. This program turns payments_history.csv from "Supervised Learning" into a realistic version: the fee is a text name instead of an amount, and about 8% of months_enrolled values are missing.

Python
import numpy as np
import pandas as pd
 
rng = np.random.default_rng(5)
data = pd.read_csv("payments_history.csv")
fee_names = {15: "library", 30: "field trip", 45: "science lab", 60: "sports", 250: "tuition"}
data.insert(0, "fee_type", data.pop("amount").map(fee_names))          # text instead of a number
data.loc[rng.random(len(data)) < 0.08, "months_enrolled"] = np.nan     # about 8% missing, as in real records
data.to_csv("payments_raw.csv", index=False)
print(data.head(3))
print("Missing values:", data.isna().sum().to_dict())
Output
     fee_type  past_late  autopay  months_enrolled  opened_reminder  late
0  field trip          1        1             12.0                1     0
1  field trip          2        0             49.0                0     0
2      sports          0        1             38.0                1     0
Missing values: {'fee_type': 0, 'past_late': 0, 'autopay': 0, 'months_enrolled': 99, 'opened_reminder': 0, 'late': 0}

Example: Encoding, Missing Values and Scaling

Each column gets the preparation it needs, inside one pipeline

This program uses payments_raw.csv from the program above.

Python
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score, train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
 
data = pd.read_csv("payments_raw.csv")
X, y = data.drop(columns="late"), data["late"]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42, stratify=y)
 
numbers = ["past_late", "autopay", "months_enrolled", "opened_reminder"]
prepare = ColumnTransformer([
    ("text", OneHotEncoder(handle_unknown="ignore"), ["fee_type"]),           # one 0/1 column per fee type
    ("numbers", make_pipeline(SimpleImputer(strategy="median"), StandardScaler()), numbers),
])
model = make_pipeline(prepare, LogisticRegression())
print(f"Cross-validated accuracy: {cross_val_score(model, X_train, y_train, cv=5).mean():.1%}")
 
model.fit(X_train, y_train)
print(model[0].get_feature_names_out())
print(model[0].transform(X_train.head(1)).round(2))
Output
Cross-validated accuracy: 89.6%
['text__fee_type_field trip' 'text__fee_type_library'
 'text__fee_type_science lab' 'text__fee_type_sports'
 'text__fee_type_tuition' 'numbers__past_late' 'numbers__autopay'
 'numbers__months_enrolled' 'numbers__opened_reminder']
[[ 0.    0.    1.    0.    0.   -0.91  1.36 -0.03  0.84]]

Explanation: A ColumnTransformer applies different steps to different columns:

  • fee_type goes to OneHotEncoder, which makes one 0/1 column per fee type. The first training family's fee is a science lab, so only fee_type_science lab is 1. handle_unknown="ignore" means a fee type never seen in training becomes all zeros instead of an error.
  • The four number columns go through SimpleImputer(strategy="median"), which fills each missing months_enrolled with the training median, then StandardScaler.

The result is 9 clean numeric columns, and the pipeline scores 89.6%, the same as on the clean data, so the missing values and text cost nothing. Because everything is inside one pipeline, each cross-validation fold learns the median and scaling from its own training part.

Encoding Categories

EncoderDescriptionUse when
One-hotOne 0/1 column per categoryCategories have no order (fee type, city)
OrdinalOne column of 0, 1, 2, ...Categories have an order (small, medium, large)
Target encodingEach category becomes the average label for itMany categories, such as zip codes; needs care to avoid leakage

Handling Missing Values

ApproachDescriptionTrade-off
Drop rowsIt is used to remove incomplete examplesSimple, but wastes data and can bias it
Fill with median or meanIt is used to replace gaps with a typical valueSimple and robust; hides that the value was missing
Fill with most frequentIt is used for categoriesSame idea for text columns
Add a "was missing" flagIt is used to keep the fact of missingness as a featureSimpleImputer(add_indicator=True); useful when missing means something

Example: A New Feature

The best features often come from domain knowledge. School staff know that a large tuition bill is risky for families who pay by hand, so this program adds that combination as a feature and compares the model with and without it, using cross-validation. It uses payments_raw.csv.

Python
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_validate, train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
 
data = pd.read_csv("payments_raw.csv")
# A new feature from domain knowledge: a big tuition bill without autopay is a risky combination
data["tuition_no_autopay"] = ((data["fee_type"] == "tuition") & (data["autopay"] == 0)).astype(int)
X, y = data.drop(columns="late"), data["late"]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42, stratify=y)
 
def build(numbers):
    prepare = ColumnTransformer([
        ("text", OneHotEncoder(handle_unknown="ignore"), ["fee_type"]),
        ("numbers", make_pipeline(SimpleImputer(strategy="median"), StandardScaler()), numbers),
    ])
    return make_pipeline(prepare, LogisticRegression())
 
before = ["past_late", "autopay", "months_enrolled", "opened_reminder"]
for name, numbers in [("Without the new feature", before), ("With tuition_no_autopay", before + ["tuition_no_autopay"])]:
    scores = cross_validate(build(numbers), X_train, y_train, cv=5, scoring=["accuracy", "recall", "roc_auc"])
    print(f"{name:24} accuracy {scores['test_accuracy'].mean():.1%}  recall {scores['test_recall'].mean():.1%}"
          f"  ROC AUC {scores['test_roc_auc'].mean():.3f}")
Output
Without the new feature  accuracy 89.6%  recall 41.2%  ROC AUC 0.872
With tuition_no_autopay  accuracy 89.5%  recall 45.8%  ROC AUC 0.874

Explanation: tuition_no_autopay is 1 when the fee is tuition and the family is not on autopay. Logistic regression adds up features separately, so it can't easily learn "this combination is extra risky" by itself; the new column hands it that combination directly. Recall on late payers rises from 41.2% to 45.8%, ROC AUC rises a little, and accuracy stays about the same. It's a real but modest gain, and cross-validation is what tells you it's real rather than a lucky split.

Ideas for New Features

IdeaExample
CombinationsTuition without autopay; price per square foot
Ratios and differencesLate payments per month enrolled
DatesDay of week, month, days until the due date
Counts and totalsPayments in the last 90 days
TextLength of a message; embeddings (see "What Are Embeddings")

Common Mistakes

Encoding categories as 1, 2, 3 when they have no order. The model then assumes "tuition" is five times "library".

Filling missing values before splitting. The fill value then includes test data.

Using features you won't have at prediction time. "Number of reminder calls" is only known after a payment is late; that's leakage.

Adding features without checking. Compare with cross-validation; keep what helps.

Interview Corner

When would you use one-hot encoding instead of ordinal encoding?

One-hot for categories with no natural order, ordinal for ordered categories. Ordinal codes on unordered categories invent a false ranking.

How do you handle missing values?

Understand why they are missing, then drop, fill with a median, mean or most frequent value, or model them, often adding a "was missing" flag, with every fill learned from training data inside a pipeline.

Practice

Exercise: a missing flag. Change the imputer to SimpleImputer(strategy="median", add_indicator=True) and compare cross-validated scores. Does knowing that months_enrolled was missing help here? Why might it, or might it not?

Check your understanding:

  1. How many columns does one-hot encoding make from fee_type, and why?
  2. Why does the imputer live inside the pipeline?
  3. Why can a combination feature help logistic regression?

Quick check: feature engineering

4 questions
1What does OneHotEncoder make from five fee types?
2What does SimpleImputer(strategy="median") do?
3What did the new feature change?
4Which feature would be leakage?

Key Takeaways

Quick reference

NeedCode
One-hot encodingOneHotEncoder(handle_unknown="ignore")
Fill missing valuesSimpleImputer(strategy="median")
Different steps per columnColumnTransformer([("name", step, columns), ...])
Output column namesprepare.get_feature_names_out()
New feature in pandasdata["new"] = (data["a"] == x) & (data["b"] == 0)

Was this tutorial helpful?

Lesson 131 of 186