Sitemap
Roman Karki

Roman Karki

Data Preprocessing in Machine Learning

6 min readFeb 18, 2025

--

Data PreProcessing

Data preprocessing is the crucial step in any machine learning pipeline. Ununiformed data or unsanitized data can lead a model to have poor predictions. So it is important for us to pre process the data before feeding to the model to improve the performance and reliability. This article outlines the key steps of data preprocessing, their importance and best practices for effective data cleaning and preparation.

Key Contents

  1. Handling Missing Data
  2. Encoding Categorical Data
  3. Feature Engineering
  4. Best Practices

1. Handling Missing Data

Handling missing data is essential to prevent the loss of information, and avoid biasness or errors that may get introduced while analyzing and evaluating a ml model. For numerical values, some of the widely used technique is to fill with the mean or median. However for categorical data mode is much preferred along with custom labels. Some tools to fill missing data from a dataset are:

  • SimpleImputer from scikit, and
  • fillna() from pandas

2. Encoding categorical data

Most machine learning algorithms can only interpret data in numerical format. So, categorical data needs to be encoded to numerical values. Some ways to convert categorical data to numerical are Binary encoding, Ordinal encoding, Frequency encodingm Target encoding, Feature hashing, and mostly used Label Encoding and One-Hot Encoding.

2.1. Label Encoding

Label encoding assigns a unique category to an integer.

[“Red”, “Blue”, “Green”] converts to [0, 1, 2]

It is best suited for ordinal data like education, and others having no inherent order.

Limitations: It can introduce false hierarchies and numerical relationships among categories that do not exist, which can mislead the model during training.

2.2. One-Hot Encoding

It is also known as dummy encoding which transforms each unique label in the categorical column to a separate binary column.

[“Red”, “Blue”, “Green”] converts to [1, 0, 0], [0, 1, 0], [0, 0, 1]

Where each label has separate columns, filled with binary values. (also addresses missing category by representing all new category column as 0's). It is based suited for nominal data like colors, brands, cities etc.

Limitations

It can lead to high dimensional feature in the dataset making computation and storage expensive.

Introduction to Muliticollinearity and Data Sparsity (all zeroes when there is large categories)

2.3. Binary Encoding

It is the combination of both label and one hot encoding while reducing the dimensionality.

[“Red”, “Blue”, “Green”] converts to [0, 0], [0, 1], [1, 1]

Where the categories are converted through label encoding making [0, 1, 2] and then converted with one hot encoding to get binary representation of all values as [0, 0], [0, 1], [1, 1].

It works best for high cardinality data like products, countries etc. The count of final added columns will be log2(N), as 2 power N can accomodate N number of categories.

2.4. Ordinal Encoding

Ordinal encoding assigns a unique integer to each category based on its natural order.

[“Low”, “Medium”, “High”] converts to [0, 1, 2]. 

It is either alphabetical ordered or custom mapped. It is best suited for ordinal data where the categories have a meaningful order (or inherent order) (e.g., education levels, rating scales).

Limitations: It may assume that the difference between adjacent categories is the same, which can be misleading if the actual differences are not equal.

2.5. Frequency Encoding

Frequency encoding assigns numerical values to categories based on their frequency of occurrence in the dataset.

[“Red”, “Blue”, “Blue”, “Green”, “Red”, “Red”] converts to [3, 2, 2, 1, 3, 3]

Where each category is replaced by the number of time they occur in the dataset. It is best suited for data where frequency of the categories has impact over the target column and we need to reduce the dimensions.

Limitations

It does not preserve the categorical identity.

Non linearity assumptions

Bias Introduction

2.6. Feature Hashing

Feature Hashing, also known as the Hashing Trick, transforms categorical data into numerical features by applying a hash function to each category. This function maps categories to a fixed number of columns using a modulo operation.

[“Red”, “Blue”, “Green”] will produce [1, 0, 0], [0, 1, 0], [0, 0, 1].

It is best suited for high cardinality data where memory and computational resources are limited. It is less interpretable than binary encoding.

Limitations

Hash Collision

Loss of interpretability

Limited use in small dataset

2.7. Target Encoding

Target encoding, also known as mean encoding, replaces each category in a categorical feature with the mean of the target variable for that category.

Get Roman Karki’s stories in your inbox

Join Medium for free to get updates from this writer.

It is best suited for high cardinality data and regression problems with continous variables to predict. Optimum technique to capture categorical feature and the target in place of OneHot encoding.

Smoothing techniques:

Limitations

Overfitting if there is not enough sample for each item.

Data Leakage if the mean calculated is based on the entire dataset instead of the training-valildation split.

3. Feature Engineering

3.1. Split into Training and Testing sets

Before applying any transformations, we need to split the dataset into training and testing sets. This ensures that the model is evaluated on data it hasn’t seen during training, preventing data leakage. Typically, a 70–80% split for training and 20–30% for testing is used.

from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

Same random state makes test data same across multiple run of same model.

3.2. Feature Scaling

Feature Scaling adjusts the range of features in a dataset to bring them into alignment, typically using techniques like normalization or standardization. It is important because many machine learning algorithms (e.g., gradient descent-based models, SVMs) are sensitive to feature magnitudes. Without scaling, features with larger ranges can dominate the model, leading to biased results and slower convergence.

Features Scaling is performed after splitting the dataset to prevent data leakage.

3.2.1. Normalization

Normalization, also known as Min-Max Scaling, rescales the data so that it lies within a specific range, typically [0, 1]. This scaling technique is useful when we want all features to have the same scale, especially when the model relies on the magnitude of the input features (like in distance-based algorithms such as k-NN).

Formula for Min-Max Normalization:

x normalized = (x − x min) / (x max​ − x min)

The transformed values are guaranteed to fall within the specified range (typically [0, 1]) and the relationships between values are preserved, which can be important when analyzing data for certain machine learning models.

Limitations: It is sensitive to outliers which may distort the range of the datapoints and it is not roboust to frequent changes in data and needs to get calculated frequently.

3.2.2. Standardization

Standardization, or Z-Score Scaling, rescales the data by transforming it to have a mean of 0 and a standard deviation of 1. This technique is particularly effective when the data is normally distributed, and it’s widely used for machine learning algorithms that assume the data follows a Gaussian distribution (such as linear regression, logistic regression, and neural networks).

Formula for Standardization (Z-Score Scaling): z = x−μ / σ

This is the most effective scaling technique which works almost all the time because of the following reasons:

  • The values are bounded within a specific range.
  • It is less sensative to outliers than the normalization.
  • It performs well with ml models that assumes the dataset to be normally distributed.

Limitations: Assumptions of a normal distribution

While Normalization is ideal for ml models that uses distance based metrics like (k-NN), Standardization is suitable for normally distributed dataset, where datapoints are centered and scaled (linear regression, logistic regression, PCA).

3.3. Transformation to Test Set

Once we are done with all the preprocessing the training data after train-test split, it is important to apply the same transformations and feature engineering techniques to the test set as well. This particularly helps prevent data leakage to train set and influence the independent evaluation.

Some key points to remember for transformation of testing set are:

  • Apply all transformations (encoding, scaling, etc.) to the test set using parameters from the training set.
  • Avoid leaking information and extract the metrics from training set alone.
  • Ensure consistency in transforming and feature engineering between training and testing set.

Summary

In machine learning, data preprocessing plays an essential role in efficiency and reliability of models. Here is the summary of the topics discussed above:

  1. Handling missing values case by case.
  2. Choosing the right encoding techniques for categorical variables.
  3. Splitting the data to training and testing dataset to avoid data leakage.
  4. Different techniques to scale the features.

By carefully considering each preprocessing step, we can lay the groundwork for building robust, scalable, and accurate machine learning models.

--

--