Step 6 of 6

Feature engineering & the ML pipeline

Encoding, scaling, imputation, feature selection, and the end-to-end pipeline from raw data to deployed model - the work that actually determines performance.

14 min read

The best model in the world can't learn from garbage features. Feature engineering - transforming raw data into representations the model can use - is where domain knowledge meets machine learning. It's often the difference between a model that barely beats random and one that ships to production.

The ML pipeline#

A model doesn't operate in isolation. It sits inside a pipeline that handles everything from raw data to predictions:

  1. 01Collect and load raw data
  2. 02Clean: handle missing values, fix types, remove duplicates
  3. 03Transform: encode categoricals, scale numerics, engineer features
  4. 04Split: train / validation / test
  5. 05Train: fit the model on the training set
  6. 06Evaluate: measure on validation (tune hyperparameters), then test
  7. 07Deploy: serve predictions in production

Every step must be fit on the training set and applied consistently to validation, test, and production data. Data leakage - using information from the test set during training - is the most common and most dangerous mistake in applied ML.

Data leakage
When information from outside the training set (validation, test, or future data) sneaks into training - inflates metrics, fails in production.
Pipeline
A chain of preprocessing and modeling steps applied consistently - ensures the same transformations run during training and inference.

Handling missing values#

Real data has holes. Three strategies:

StrategyWhen to useMethod
DropFew missing values, random patternRemove rows or columns
ImputeMany missing values, statistical patternFill with mean, median, mode, or model-predicted values
IndicateMissingness itself is informativeAdd a binary "is_missing" column, then impute

For tree-based models, many libraries (XGBoost, LightGBM) handle missing values natively - they learn which branch to send missing values down. For linear models and neural networks, explicit imputation is required.

Encoding categorical features#

Models need numbers, not strings. How you encode categoricals matters:

EncodingDescriptionWhen to use
One-hotBinary column per categoryLow cardinality (< 20 categories)
OrdinalInteger per category (preserving order)Ordered categories (small/medium/large)
TargetReplace category with mean of targetHigh cardinality; regularize to avoid leakage
FrequencyReplace category with its countHigh cardinality, tree models
EmbeddingsLearned dense vectorsVery high cardinality, neural networks

Scaling numeric features#

Feature scales affect distance-based algorithms (k-NN, SVMs, PCA) and gradient descent convergence:

MethodFormulaUse
Standardization(x − μ) / σMost algorithms; assumes roughly normal distribution
Min-max scaling(x − min) / (max − min)When you need values in [0, 1]; sensitive to outliers
Robust scaling(x − median) / IQRWhen outliers are present
Log transformlog(x + 1)Right-skewed distributions (income, counts)

Tree-based models are scale-invariant - they split on thresholds, not distances - so scaling doesn't affect them. But it's good practice to scale anyway for consistency and to make feature importances more comparable.

Feature engineering techniques#

TechniqueExampleWhy it helps
Interaction featuresx₁ × x₂, x₁ / x₂Captures relationships between features
Polynomial featuresx², x³, x₁x₂Models nonlinear relationships
BinningAge → [0-18, 19-30, 31-50, 51+]Reduces noise, captures nonlinear effects
Date featuresDay of week, month, hour, is_weekendExtracts cyclical and calendar patterns
Text featuresTF-IDF, word count, sentimentRepresents text numerically
AggregationsMean, max, count per groupCreates features from related records

Domain knowledge is the secret weapon. A data scientist who understands the problem domain will engineer features that no automated method would discover: ratios that have physical meaning, indicators based on business rules, or temporal patterns specific to the industry.

Feature selection#

Not all features help. Irrelevant or redundant features add noise, slow training, and can hurt performance:

MethodApproach
FilterRank features by correlation, mutual information, or variance; drop the worst
WrapperTry subsets of features and keep the set that performs best (expensive)
EmbeddedUse model's built-in selection (L1 regularization drives weights to zero; tree importance)

L1 regularization (Lasso) is the most elegant approach: it simultaneously fits the model and selects features by shrinking unimportant weights to exactly zero. The regularization strength λ controls how many features survive.

One-hot encoding
Represents each category as a binary vector with a single 1 - simple but creates many columns for high-cardinality features.
Target encoding
Replaces each category with the mean of the target variable for that category - compact but risks leakage without regularization.
TF-IDF
Term Frequency-Inverse Document Frequency - weights words by how important they are to a document relative to the whole corpus.
L1 / Lasso
Adds the sum of absolute weight values as a penalty - drives unimportant weights to exactly zero, performing automatic feature selection.

The full pipeline in code#

A well-structured pipeline in scikit-learn chains all these steps:

from sklearn.pipeline import Pipeline
from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import StandardScaler, OneHotEncoder
from sklearn.impute import SimpleImputer

preprocessor = ColumnTransformer([
    ("num", Pipeline([
        ("impute", SimpleImputer(strategy="median")),
        ("scale", StandardScaler()),
    ]), numeric_features),
    ("cat", Pipeline([
        ("impute", SimpleImputer(strategy="most_frequent")),
        ("encode", OneHotEncoder(handle_unknown="ignore")),
    ]), categorical_features),
])

pipeline = Pipeline([
    ("preprocess", preprocessor),
    ("model", XGBClassifier()),
])

pipeline.fit(X_train, y_train)

The pipeline ensures the same transformations are applied consistently during training, validation, and inference - eliminating an entire class of bugs.

Where it shows up in ML#

Feature engineering > model complexity

A simple model with good features often beats a complex model with raw features. This is especially true for tabular data.

Pipelines prevent leakage

Scikit-learn pipelines ensure transformers are fit on training data only - no accidental peeking at validation or test statistics.

Embeddings replace manual encoding

Deep learning learns features directly from raw data, but feature engineering still helps for tabular data and domain-specific inputs.

AutoML automates the search

Tools like AutoGluon, FLAML, and H2O search over feature transformations, model types, and hyperparameters - but domain features still help.

Further reading

Search Data Science After Dark

Search across prompts, models, papers, guides, and library topics.