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:
- 01Collect and load raw data
- 02Clean: handle missing values, fix types, remove duplicates
- 03Transform: encode categoricals, scale numerics, engineer features
- 04Split: train / validation / test
- 05Train: fit the model on the training set
- 06Evaluate: measure on validation (tune hyperparameters), then test
- 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:
| Strategy | When to use | Method |
|---|---|---|
| Drop | Few missing values, random pattern | Remove rows or columns |
| Impute | Many missing values, statistical pattern | Fill with mean, median, mode, or model-predicted values |
| Indicate | Missingness itself is informative | Add 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:
| Encoding | Description | When to use |
|---|---|---|
| One-hot | Binary column per category | Low cardinality (< 20 categories) |
| Ordinal | Integer per category (preserving order) | Ordered categories (small/medium/large) |
| Target | Replace category with mean of target | High cardinality; regularize to avoid leakage |
| Frequency | Replace category with its count | High cardinality, tree models |
| Embeddings | Learned dense vectors | Very high cardinality, neural networks |
Scaling numeric features#
Feature scales affect distance-based algorithms (k-NN, SVMs, PCA) and gradient descent convergence:
| Method | Formula | Use |
|---|---|---|
| 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) / IQR | When outliers are present |
| Log transform | log(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#
| Technique | Example | Why it helps |
|---|---|---|
| Interaction features | x₁ × x₂, x₁ / x₂ | Captures relationships between features |
| Polynomial features | x², x³, x₁x₂ | Models nonlinear relationships |
| Binning | Age → [0-18, 19-30, 31-50, 51+] | Reduces noise, captures nonlinear effects |
| Date features | Day of week, month, hour, is_weekend | Extracts cyclical and calendar patterns |
| Text features | TF-IDF, word count, sentiment | Represents text numerically |
| Aggregations | Mean, max, count per group | Creates 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:
| Method | Approach |
|---|---|
| Filter | Rank features by correlation, mutual information, or variance; drop the worst |
| Wrapper | Try subsets of features and keep the set that performs best (expensive) |
| Embedded | Use 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.