Skip to the page
Tecyfy

Feature Engineering: The Key to Better Models

Learn the art and science of Feature Engineering with detailed explanations, examples, and tips to enhance your machine learning models. Explore techniques like encoding, scaling, and feature selection.

Tecyfy · Published · Updated · 9 min read

Introduction

In the realm of Machine Learning (ML), the quality of your features often determines the quality of your models. Feature Engineering is the process of creating, transforming, and optimizing features to maximize a model's predictive power.

This blog will provide an in-depth guide to Feature Engineering, discussing key techniques, practical examples with code snippets, and best practices to refine your features for better ML models.


What is Feature Engineering?

Feature Engineering involves transforming raw data into meaningful inputs that a machine learning algorithm can understand and leverage effectively. It includes creating new features, transforming existing ones, and selecting the most impactful features for the model.

Key Goals:

  1. Improve Model Accuracy: By providing high-quality, relevant features.
  2. Reduce Model Complexity: By eliminating irrelevant or redundant features.
  3. Enhance Interpretability: By using features that make sense in the real-world context.

The Importance of Feature Engineering

Well-engineered features can significantly improve model performance. Here’s why it matters:

AspectWithout Feature EngineeringWith Feature Engineering
Model AccuracyLimited due to poor feature representationHigh due to meaningful feature representation
Training TimeLonger due to irrelevant featuresShorter with optimized features
Overfitting RiskHigher with noisy dataReduced by selecting relevant features

Example:

Consider predicting house prices. Raw data may include columns like Address, Square Feet, Rooms and Year Built. Engineering Age (this year minus Year Built) and Square Feet per Room gives the model inputs that relate more directly to price. Be careful not to build a feature from the answer itself: Price per Square Foot uses the price, so it would leak the target into the inputs and look perfect in training and fail in use.


Techniques in Feature Engineering

1. Handling Missing Values

Most models cannot take empty cells. Fill a number with the column's median (less pulled by outliers than the mean), fill a category with its most common value or a separate Unknown, and add a yes or no column saying the value was missing when missingness itself may carry meaning. Dropping rows is an option only when few are missing and the dataset is large.

Code Example:

import pandas as pd

# Sample dataset
data = pd.DataFrame({
    'Age': [25, 30, None, 35, 40],
    'Salary': [50000, 60000, 55000, None, 70000]
})

# Mark what was missing, then fill with the median
data['Age_missing'] = data['Age'].isna()
data['Age'] = data['Age'].fillna(data['Age'].median())
data['Salary'] = data['Salary'].fillna(data['Salary'].median())

print(data)

2. Encoding Categorical Variables

Many models, notably linear models and SVMs, need categorical features turned into numbers first. Common methods include:

  • Label Encoding: Assigns a unique number to each category.
  • One-Hot Encoding: Creates binary columns for each category.

Example: One-Hot Encoding

from sklearn.preprocessing import OneHotEncoder
import pandas as pd

# Sample data
data = pd.DataFrame({'City': ['New York', 'Los Angeles', 'Chicago']})
encoder = OneHotEncoder(sparse_output=False, handle_unknown="ignore")

# Apply one-hot encoding
encoded = encoder.fit_transform(data[['City']])
print(encoded)

Pros and Cons:

Encoding TypeProsCons
Label EncodingSimple and efficientMay introduce ordinal relationships
One-HotAvoids ordinal relationshipsIncreases dimensionality

3. Feature Scaling

Models that compare distances or use gradient descent (k-nearest neighbours, SVMs, linear and logistic regression, neural networks) train better when numbers share a scale. Tree models do not need it. Fit the scaler on the training data only, then apply it to the test data.

Techniques:

  • Standardization: Scales features to have a mean of 0 and a standard deviation of 1.
  • Normalization: Scales features to a [0, 1] range.

Code Example:

from sklearn.preprocessing import StandardScaler

# Sample data
data = [[10, 100], [20, 200], [30, 300]]
scaler = StandardScaler()

# Apply scaling
scaled_data = scaler.fit_transform(data)
print(scaled_data)

4. Creating New Features

Creating new features can make hidden patterns more explicit.

Example:

From a Date column, derive features like Day, Month, and Year.

import pandas as pd

# Sample dataset
data = pd.DataFrame({'Date': ['2025-01-01', '2025-02-15']})
data['Date'] = pd.to_datetime(data['Date'])

# Create new features
data['Month'] = data['Date'].dt.month
data['Day'] = data['Date'].dt.day
data['Weekday'] = data['Date'].dt.dayofweek  # 0 is Monday
print(data)

5. Feature Selection

Feature selection removes irrelevant or redundant features, improving model performance and interpretability.

Methods:

  • Filter Methods: Use statistical tests like correlation.
  • Wrapper Methods: Evaluate model performance for different feature subsets.
  • Embedded Methods: Use algorithms like LASSO that incorporate feature selection.

Code Example:

from sklearn.feature_selection import SelectKBest, f_classif
import pandas as pd
from sklearn.datasets import make_classification

# Create dataset
X, y = make_classification(n_samples=100, n_features=10, random_state=42)

# Select top 5 features
selector = SelectKBest(score_func=f_classif, k=5)
X_selected = selector.fit_transform(X, y)
print(X_selected.shape)

Best Practices in Feature Engineering

  1. Understand the Domain: Collaborate with domain experts to create meaningful features.
  2. Experiment Iteratively: Test different features and evaluate their impact on model performance.
  3. Monitor Feature Importance: Use tools like SHAP or feature importance plots to understand which features drive predictions.

Real-World Applications of Feature Engineering

1. Fraud Detection

Features like transaction velocity or location anomalies can improve fraud detection systems.

2. Healthcare

Engineered features like BMI from weight and height enhance diagnostic models.

3. E-commerce

Creating features like customer lifetime value (CLV) helps optimize marketing strategies.


Conclusion

Feature Engineering is both an art and a science, requiring creativity, domain knowledge, and technical expertise. By handling missing data, encoding categories, scaling numbers and creating features that carry meaning (without leaking the target), you can significantly improve your ML models’ performance.

Take your time to experiment, iterate, and refine—because better features lead to better models.

Questions

What is feature engineering in machine learning?
Feature engineering turns raw data into inputs a model can use well: creating new features, transforming existing ones and selecting the ones that matter.
How should I handle missing values?
Fill a number with the column's median, which outliers pull less than the mean, and a category with its most common value or Unknown. Add a yes or no column marking the value as missing when missingness itself may mean something.
What is the difference between label encoding and one-hot encoding?
Label encoding gives each category a number, which is simple but can suggest an order that is not there. One-hot encoding makes a yes or no column per category, which avoids the false order but adds columns.
Do I need to scale features?
For models that compare distances or use gradient descent, such as k-nearest neighbours, linear and logistic regression and neural networks, yes. Tree models do not need it. Fit the scaler on the training data only, then apply it to the test data.
What is target leakage in feature engineering?
Leakage is a feature built from the answer itself, such as price per square foot when predicting price. The model looks perfect in training and fails in use, because the answer will not be known when it predicts.

Sources

Where each fact comes from

  1. 1OneHotEncoder
  2. 2pandas.Series.dt.month