Feature Engineering
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
| Task | Description | scikit-learn tool |
|---|---|---|
| Encoding | It is used to turn text categories into numbers | OneHotEncoder, OrdinalEncoder |
| Filling missing values | It is used to replace gaps with a sensible value | SimpleImputer |
| Scaling | It is used to put numbers on similar scales | StandardScaler, MinMaxScaler |
| Creating features | It is used to add new columns that make patterns easier to learn | pandas, FunctionTransformer |
| Combining it all | It is used to apply different steps to different columns | ColumnTransformer 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.
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()) 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
This program uses payments_raw.csv from the program above.
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))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_typegoes toOneHotEncoder, which makes one 0/1 column per fee type. The first training family's fee is a science lab, so onlyfee_type_science labis 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 missingmonths_enrolledwith the training median, thenStandardScaler.
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
| Encoder | Description | Use when |
|---|---|---|
| One-hot | One 0/1 column per category | Categories have no order (fee type, city) |
| Ordinal | One column of 0, 1, 2, ... | Categories have an order (small, medium, large) |
| Target encoding | Each category becomes the average label for it | Many categories, such as zip codes; needs care to avoid leakage |
Handling Missing Values
| Approach | Description | Trade-off |
|---|---|---|
| Drop rows | It is used to remove incomplete examples | Simple, but wastes data and can bias it |
| Fill with median or mean | It is used to replace gaps with a typical value | Simple and robust; hides that the value was missing |
| Fill with most frequent | It is used for categories | Same idea for text columns |
| Add a "was missing" flag | It is used to keep the fact of missingness as a feature | SimpleImputer(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.
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}")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.874Explanation: 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
| Idea | Example |
|---|---|
| Combinations | Tuition without autopay; price per square foot |
| Ratios and differences | Late payments per month enrolled |
| Dates | Day of week, month, days until the due date |
| Counts and totals | Payments in the last 90 days |
| Text | Length 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:
- How many columns does one-hot encoding make from
fee_type, and why? - Why does the imputer live inside the pipeline?
- Why can a combination feature help logistic regression?
Key Takeaways
Quick reference
| Need | Code |
|---|---|
| One-hot encoding | OneHotEncoder(handle_unknown="ignore") |
| Fill missing values | SimpleImputer(strategy="median") |
| Different steps per column | ColumnTransformer([("name", step, columns), ...]) |
| Output column names | prepare.get_feature_names_out() |
| New feature in pandas | data["new"] = (data["a"] == x) & (data["b"] == 0) |
Was this tutorial helpful?