Sitemap
Dr. Pooja

Dr. Pooja⁠

Academician, Mentor, Researcher - Artificial Intelligence | Data Science | Machine Learning | Data Analytics

Data Preprocessing with Scikit-learn

3 min readAug 16, 2023

Data preprocessing is an essential step in any machine learning project. It involves transforming raw data into a clean, consistent, and structured format, making it more usablle and ready for model training.

Scikit-learn, commonly known as sklearn, is a powerful Python library widely used for machine learning tasks, including data preprocessing.

Press enter or click to view image in full size
Photo by Defne Türker on Unsplash

In this post, you will explore some of the many data preprocessing techniques offered by sklearn and learn how they can be applied to enhance the performance of machine learning models.

Data preprocessing is the initial phase of a machine learning pipeline that involves cleaning, transforming, and preparing data for model training. It plays an important role in ensuring the accuracy and efficiency of machine learning models. Some of the common challenges addressed during this phase include missing values, feature scaling, categorical data encoding, and outlier detection.

Scikit-learn is an open-source Python library that provides a wide range of tools for machine learning, including data preprocessing modules. With a simple and consistent API, sklearn enables us to handle various preprocessing tasks effectively and efficiently.

Data Preprocessing Techniques with Scikit-learn

Effective data preprocessing lays the foundation for successful machine learning models, and Scikit-learn simplifies this process with its user-friendly API and extensive feature set.

Handling Missing Data Dealing with missing data is a common challenge in real-world datasets. Scikit-learn provides methods like SimpleImputer to fill missing values with a statistical measure such as mean, median, or mode.

Feature Scaling Feature scaling is essential to ensure that all features have comparable scales, preventing certain features from dominating the model training process. Sklearn offers StandardScaler and MinMaxScaler for standardization and normalization, respectively.

Get Dr. Pooja’s stories in your inbox

Join Medium for free to get updates from this writer.

Categorical Data Encoding Machine learning models often require numerical data, which makes encoding categorical features necessary. Sklearn provides LabelEncoder and OneHotEncoder for handling ordinal and nominal categorical data, respectively.

Handling Outliers Outliers can significantly impact the performance of machine learning models. Sklearn offers various outlier detection methods such as IsolationForest and EllipticEnvelope to identify and handle outliers effectively.

Dimensionality Reduction High-dimensional datasets can be computationally expensive and prone to overfitting. Sklearn provides popular dimensionality reduction techniques like Principal Component Analysis (PCA) and Linear Discriminant Analysis (LDA) to reduce feature dimensions while preserving essential information.

Data Transformation Sklearn allows data transformation using PolynomialFeatures to add polynomial features, FunctionTransformer to apply custom functions, and PowerTransformer to perform various power transformations.

Let’s use the famous Iris dataset and apply various preprocessing steps on it.

import numpy as np
import pandas as pd
from sklearn.datasets import load_iris
from sklearn.preprocessing import StandardScaler, LabelEncoder, OneHotEncoder
from sklearn.impute import SimpleImputer
from sklearn.decomposition import PCA

# Load the Iris dataset
iris = load_iris()
X, y = iris.data, iris.target

# Convert the dataset to a pandas DataFrame for better visualization
df = pd.DataFrame(X, columns=iris.feature_names)
df['target'] = y

# Step 1: Handling Missing Data with SimpleImputer
# Let's introduce some NaN values in the first few rows
#for demonstration purposes

df.iloc[0:3, 0] = np.nan
df.iloc[50:53, 1] = np.nan
df.iloc[100:103, 2] = np.nan

# Create a SimpleImputer object and
#fill missing values with the mean of the respective feature

imputer = SimpleImputer(strategy='mean')
df_nan = pd.DataFrame(imputer.fit_transform(df),
columns=df.columns)

# Step 2: Feature Scaling with StandardScaler
scaler = StandardScaler()
X_scaled = scaler.fit_transform(df_nan.drop('target', axis=1))

# Step 3: Encoding Categorical Data with OneHotEncoder
# For demonstration, let's consider 'target' as a categorical feature (0, 1, 2)
label_encoder = LabelEncoder()
df_nan['target_encoded'] = label_encoder.fit_transform(df_nan['target'])

En = OneHotEncoder(sparse=False)
Target_En = En.fit_transform(df_nan[['target_encoded']])
df_en = pd.concat([df_nan, pd.DataFrame(Target_En, columns=['target_0', 'target_1', 'target_2'])], axis=1)

# Step 4: Dimensionality Reduction with PCA
pca = PCA(n_components=2)
X_pca = pca.fit_transform(X_scaled)

# Display the preprocessed DataFrame
print("Preprocessed DataFrame:")
print(df_en.head())

# Display the reduced data after PCA
print("\nReduced Data after PCA:")
print(pd.DataFrame(X_pca, columns=['PCA Component 1', 'PCA Component 2']).head())

Data preprocessing is a fundamental step in any machine learning project, and Scikit-learn (sklearn) offers a powerful set of tools to tackle various preprocessing challenges efficiently. This post explored the key data preprocessing techniques provided by sklearn, try to use these techniques on anther dataset. Similar to load_iris)(), you can use following inbuid datasets ith functions:-

load_digits(): Loads the handwritten digits dataset [classification tasks]

load_boston(): Loads the Boston Housing dataset [regression tasks]

load_diabetes(): Loads the Diabetes dataset [regression tasks]

load_wine(): Loads the Wine dataset [classification tasks]

Keep practicing!

--

--

Dr. Pooja
Dr. Pooja

Written by Dr. Pooja⁠

Academician, Mentor, Researcher - Artificial Intelligence | Data Science | Machine Learning | Data Analytics