Feature Engineering: Where Accuracy Actually Comes From

Feature Engineering: Where Accuracy Actually Comes From in Python: Practitioners repeat a line that sounds like false modesty but is measurably true: better…

Concept Explanation

Practitioners repeat a line that sounds like false modesty but is measurably true: better features beat better models. Swapping logistic regression for gradient boosting might buy you two points of accuracy. Adding one well-chosen feature can buy you fifteen.

Feature engineering is turning what you have into what the model can use. A raw timestamp is nearly useless to a linear model. hour_of_day, is_weekend, and days_since_signup extracted from that same timestamp are three genuinely predictive columns.

Encoding Categories

Models consume numbers. Text categories need converting, and the method matters:

TechniqueProducesUse for
One-hotOne 0/1 column per categoryNominal data, few categories (OneHotEncoder)
OrdinalA single integer per categoryGenuinely ordered data (small < medium < large)
Target encodingCategory → mean targetHigh-cardinality columns; leaks easily, use with care
FrequencyCategory → how often it appearsCheap signal from high-cardinality columns

The trap: OrdinalEncoder on unordered data invents an order. Encode {red: 0, green: 1, blue: 2} and you have told the model that green sits between red and blue and that blue is "twice" green. For nominal categories, one-hot.

Scaling

ScalerEffectUse when
StandardScalerMean 0, std 1Default; roughly normal data
MinMaxScalerSqueeze into [0, 1]Bounded inputs, neural nets
RobustScalerUses median and IQROutliers are present
PowerTransformerMakes skewed data more normalHeavy right skew (income, prices)

Trees and forests do not need scaling at all. Everything distance-based or gradient-based does.

Missing Values

Never drop rows reflexively — the fact that a value is missing is often itself predictive.

from sklearn.impute import SimpleImputer
num = SimpleImputer(strategy="median")            # robust to outliers
cat = SimpleImputer(strategy="most_frequent")

Add a was_missing indicator column (add_indicator=True) when missingness might carry information — an unfilled income field on a loan application usually does.

Creating Features

This is the part that requires thinking about the domain rather than the API.

SourceDerived features
Datetimehour, day of week, month, is_weekend, is_holiday, days_since_X
Two numericsratio, difference, product
Moneylog transform, per-unit price, percentage of total
Textlength, word count, has_digit, sentiment
Groupscount per group, rank within group, deviation from group mean

Ratios are underrated. price and square_metres are two columns; price_per_square_metre is the one that actually compares two houses. A linear model cannot construct that itself — division is not something it can learn.

ColumnTransformer: The Right Tool

Real data has mixed types, and each type needs different treatment. ColumnTransformer applies different pipelines to different columns and keeps it all inside one estimator, so fit never sees test data:

pre = ColumnTransformer([
    ("num", num_pipeline, numeric_cols),
    ("cat", cat_pipeline, categorical_cols),
])
model = Pipeline([("pre", pre), ("clf", RandomForestClassifier())])

That is the whole architecture of a professional scikit-learn project.


Code Example #1 (Basic)

Extracting real features out of a timestamp and two numbers.

import numpy as np
import pandas as pd

rng = np.random.default_rng(5)
n = 8

df = pd.DataFrame({
    "order_time": pd.to_datetime([
        "2024-03-04 08:15", "2024-03-09 21:40", "2024-03-11 12:05",
        "2024-03-16 19:30", "2024-03-18 07:50", "2024-03-23 23:10",
        "2024-03-25 13:25", "2024-03-30 17:00",
    ]),
    "signup_date": pd.to_datetime(["2023-11-02"] * 4 + ["2024-02-20"] * 4),
    "basket_value": [42.0, 118.5, 9.99, 340.0, 27.5, 61.0, 890.0, 15.25],
    "item_count": [3, 7, 1, 12, 2, 4, 9, 1],
    "city": ["Leeds", "Leeds", "Bath", "York", "Bath", "York", "Leeds", "Bath"],
})

# --- Datetime -> several usable columns ---
t = df["order_time"]
df["hour"] = t.dt.hour
df["day_of_week"] = t.dt.dayofweek                 # 0 = Monday
df["is_weekend"] = (t.dt.dayofweek >= 5).astype(int)
df["is_evening"] = t.dt.hour.between(18, 23).astype(int)
df["days_since_signup"] = (t - df["signup_date"]).dt.days

# --- Cyclical encoding: hour 23 and hour 0 are one hour apart, not 23 ---
df["hour_sin"] = np.sin(2 * np.pi * df["hour"] / 24).round(3)
df["hour_cos"] = np.cos(2 * np.pi * df["hour"] / 24).round(3)

# --- Ratios: the features a linear model cannot invent ---
df["avg_item_price"] = (df["basket_value"] / df["item_count"]).round(2)
df["log_value"] = np.log1p(df["basket_value"]).round(3)    # log1p handles 0 safely

# --- Frequency encoding for a categorical column ---
df["city_freq"] = df["city"].map(df["city"].value_counts(normalize=True)).round(3)

cols = ["hour", "is_weekend", "is_evening", "days_since_signup",
        "hour_sin", "hour_cos", "avg_item_price", "log_value", "city_freq"]
print(df[cols].to_string(index=False))

print("\nRaw basket_value skew:", round(df['basket_value'].skew(), 2))
print("After log1p:          ", round(df['log_value'].skew(), 2))

The cyclical pair deserves attention. As a plain integer, hour 23 and hour 0 look 23 units apart when they are adjacent. The sine/cosine pair puts them next to each other on a circle, which is what "late night" actually means.

Code Example #2 (Intermediate)

A complete mixed-type preprocessing pipeline with a custom transformer.

import numpy as np
import pandas as pd
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import Pipeline
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import StandardScaler, OneHotEncoder, OrdinalEncoder
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split, cross_val_score

rng = np.random.default_rng(21)
n = 1200

df = pd.DataFrame({
    "area_sqm": rng.normal(85, 30, n).clip(20).round(1),
    "price": rng.gamma(7, 42000, n).round(0),
    "rooms": rng.integers(1, 7, n),
    "age_years": rng.integers(0, 120, n),
    "city": rng.choice(["Leeds", "York", "Bath", "Hull"], n, p=[.4, .25, .2, .15]),
    "condition": rng.choice(["poor", "fair", "good", "excellent"], n),
    "epc_rating": rng.choice(["A", "B", "C", "D", "E"], n),
})
# Realistic missingness
df.loc[rng.choice(n, 90, replace=False), "area_sqm"] = np.nan
df.loc[rng.choice(n, 60, replace=False), "condition"] = np.nan

# Target with real signal, so improvements are measurable
score = (df["price"] / df["area_sqm"].fillna(85) / 900
         - df["age_years"] / 90
         + df["rooms"] * 0.25)
df["sold_fast"] = (score > score.median()).astype(int)

y = df.pop("sold_fast")


class RatioFeatures(BaseEstimator, TransformerMixin):
    """Adds domain ratios that no scaler or encoder can produce."""

    def fit(self, X, y=None):
        return self                                # stateless: nothing to learn

    def transform(self, X):
        X = X.copy()
        X["price_per_sqm"] = X["price"] / X["area_sqm"].replace(0, np.nan)
        X["sqm_per_room"] = X["area_sqm"] / X["rooms"].replace(0, np.nan)
        X["log_price"] = np.log1p(X["price"])
        X["is_new_build"] = (X["age_years"] < 5).astype(int)
        return X

    def get_feature_names_out(self, input_features=None):
        return np.asarray(list(input_features) +
                          ["price_per_sqm", "sqm_per_room", "log_price", "is_new_build"])


numeric = ["area_sqm", "price", "rooms", "age_years",
           "price_per_sqm", "sqm_per_room", "log_price", "is_new_build"]
nominal = ["city", "epc_rating"]                   # no natural order -> one-hot
ordinal = ["condition"]                            # genuinely ordered -> integers
CONDITION_ORDER = [["poor", "fair", "good", "excellent"]]

preprocess = ColumnTransformer([
    ("num", Pipeline([
        ("impute", SimpleImputer(strategy="median", add_indicator=True)),
        ("scale", StandardScaler()),
    ]), numeric),
    ("nom", Pipeline([
        ("impute", SimpleImputer(strategy="most_frequent")),
        ("onehot", OneHotEncoder(handle_unknown="ignore", sparse_output=False)),
    ]), nominal),
    ("ord", Pipeline([
        ("impute", SimpleImputer(strategy="most_frequent")),
        ("encode", OrdinalEncoder(categories=CONDITION_ORDER)),
    ]), ordinal),
], remainder="drop")

full = Pipeline([
    ("ratios", RatioFeatures()),
    ("prep", preprocess),
    ("clf", RandomForestClassifier(n_estimators=300, random_state=21)),
])

X_train, X_test, y_train, y_test = train_test_split(
    df, y, test_size=0.25, random_state=21, stratify=y
)

# --- Does the engineering actually pay? Measure it. ---
raw_only = Pipeline([
    ("prep", ColumnTransformer([
        ("num", Pipeline([("i", SimpleImputer(strategy="median")),
                          ("s", StandardScaler())]),
         ["area_sqm", "price", "rooms", "age_years"]),
        ("nom", Pipeline([("i", SimpleImputer(strategy="most_frequent")),
                          ("o", OneHotEncoder(handle_unknown="ignore", sparse_output=False))]),
         nominal + ordinal),
    ])),
    ("clf", RandomForestClassifier(n_estimators=300, random_state=21)),
])

for label, pipe in [("raw features", raw_only), ("engineered", full)]:
    cv = cross_val_score(pipe, X_train, y_train, cv=5, scoring="roc_auc")
    pipe.fit(X_train, y_train)
    print(f"{label:<14} cv roc_auc {cv.mean():.3f} +/- {cv.std():.3f}   "
          f"test {pipe.score(X_test, y_test):.3f}")

# --- Which engineered features earned their place? ---
full.fit(X_train, y_train)
names = full.named_steps["prep"].get_feature_names_out()
importances = full.named_steps["clf"].feature_importances_
top = sorted(zip(names, importances), key=lambda p: p[1], reverse=True)[:8]
print("\nTop features:")
for name, imp in top:
    print(f"  {name:<32} {imp:.4f}")

Two things make this production-grade. RatioFeatures lives inside the pipeline, so cross-validation folds it correctly and there is no path for leakage. And the raw-vs-engineered comparison means the claim "engineering helped" is backed by a measurement instead of a feeling — price_per_sqm should appear near the top of that importance list.


Common Mistakes

  1. Fitting a scaler or imputer on the full dataset: test-set statistics leak into training. Fit inside a Pipeline, always.
  2. Ordinal-encoding nominal categories: telling the model that York (1) sits between Leeds (0) and Bath (2) is inventing a fact.
  3. One-hot encoding a high-cardinality column: 40,000 postcodes become 40,000 columns. Use frequency or target encoding instead.
  4. Forgetting handle_unknown="ignore": a category that appears only in production crashes OneHotEncoder at predict time.
  5. Dropping rows with missing values: you may be discarding a third of your data and a genuine signal. Impute and add an indicator.
  6. Leaking the target into a feature: a column computed from y — like "total spend including this order" when predicting the order — gives near-perfect scores that collapse in production.
  7. Encoding hour as a plain integer: hour 23 and hour 0 are adjacent in reality and 23 apart numerically. Use sine/cosine.
  8. np.log() on data containing zero: gives -inf. Use np.log1p().
  9. Adding features without measuring: run cross-validation before and after. Some additions make things worse.
  10. Scaling the target as well as the features: possible for regression, but then your errors are in standard deviations and nobody can interpret them.

Best Practices

  • Put every transformation inside a Pipeline: it is the only way to make leakage structurally impossible.
  • Use ColumnTransformer for mixed types so numeric, nominal, and ordinal columns each get the right treatment.
  • Build ratios and differences deliberately — models cannot divide two columns for you.
  • Extract everything from datetimes: hour, weekday, month, is_weekend, and time-since. A raw timestamp is one of the most under-used columns in any dataset.
  • Impute with the median, not the mean, for anything skewed, and set add_indicator=True when missingness might mean something.
  • Log-transform heavily skewed money columns with np.log1p.
  • Encode ordinals with an explicit categories= list so the order is yours, not alphabetical.
  • Measure every feature batch with cross-validation, and delete the ones that do not pay.
  • Check feature_importances_ for something suspicious: a feature that dominates unreasonably is usually target leakage.
  • Write custom transformers as BaseEstimator/TransformerMixin classes so they compose with the rest of scikit-learn instead of sitting in a script above it.

Practice Exercises

  1. The Timestamp Miner: Take a DataFrame with one datetime column and derive at least six features from it, including a cyclical sine/cosine pair. Print the result and explain which two you expect to matter most.
  2. The Ratio Payoff: Build a dataset with price and area columns, train a model on the raw columns, then add price_per_area and retrain. Report the cross-validated change in score.
  3. The Mixed Pipeline: Construct a ColumnTransformer handling numeric (impute + scale), nominal (impute + one-hot), and ordinal (explicit category order) columns, drop it into a Pipeline with any classifier, and confirm it fits and predicts without ever touching the test set during training.