0% found this document useful (0 votes)
28 views10 pages

Python Data Preprocessing Techniques

The document provides an overview of key concepts in Python for data preprocessing, including the use of SimpleImputer for handling missing values, StandardScaler for feature scaling, and the significance of train_test_split for model evaluation. It also explains OneHotEncoding, the differences between fit(), transform(), and fit_transform() methods, and the importance of normalization and standardization in machine learning. Additionally, it emphasizes the necessity of splitting data before normalization to prevent data leakage.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views10 pages

Python Data Preprocessing Techniques

The document provides an overview of key concepts in Python for data preprocessing, including the use of SimpleImputer for handling missing values, StandardScaler for feature scaling, and the significance of train_test_split for model evaluation. It also explains OneHotEncoding, the differences between fit(), transform(), and fit_transform() methods, and the importance of normalization and standardization in machine learning. Additionally, it emphasizes the necessity of splitting data before normalization to prevent data leakage.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Subject Code: PGCSE 102

Subject Name: Python for Data Science

Q1. What is the purpose of the SimpleImputer class in Python?

Answer:
The SimpleImputer class in Python (from [Link]) is used to fill missing values in a
dataset with a specific strategy such as mean, median, most frequent, or a constant value.

Code Example:

from [Link] import SimpleImputer


import numpy as np

data = [Link]([[1, 2], [[Link], 3], [7, 6]])


imputer = SimpleImputer(strategy='mean')
result = imputer.fit_transform(data)
print(result)

Q2. Define how the “preprocessing” module is useful in Python for data preprocessing.

Answer:
The [Link] module provides functions and classes for feature scaling,
normalization, encoding categorical features, and transformation, making raw data suitable for
modeling.

Functions include: StandardScaler, MinMaxScaler, LabelEncoder, OneHotEncoder, etc.


Q3. Describe the significance of StandardScaler class in data preprocessing.

Answer:
StandardScaler standardizes features by removing the mean and scaling to unit variance. It is
crucial for algorithms sensitive to feature scales (e.g., SVM, KNN).

Code Example:

from [Link] import StandardScaler

data = [[1, 20], [2, 40], [3, 60]]


scaler = StandardScaler()
scaled_data = scaler.fit_transform(data)
print(scaled_data)

Q4. How does Label Encoding affect model performance?

Answer:
Label Encoding converts categorical labels into numeric values. For models that consider label
ordering (like linear regression), it may introduce unintended bias. Best for tree-based models.

Q5. What are the steps involved in data preprocessing for machine learning?

Answer:

1. Importing libraries

2. Loading the dataset

3. Handling missing values

4. Encoding categorical data

5. Feature scaling
6. Splitting into train-test sets

7. Model fitting
Q6. Explain the use of train_test_split in data preprocessing.

Answer:
train_test_split (from sklearn.model_selection) is used to divide the dataset into training and
testing sets to evaluate model generalization.

Code Example:

from sklearn.model_selection import train_test_split

X = [[1], [2], [3], [4]]


y = [1, 2, 3, 4]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25)

******************************************************************************

Q1. Define the term "OneHotEncoding” and its application with suitable example.

Answer:
One-Hot Encoding converts categorical variables into a binary matrix (dummy variables),
avoiding ordinal relationships.

Code Example:

from [Link] import OneHotEncoder


import numpy as np

data = [Link]([['red'], ['green'], ['blue']])


encoder = OneHotEncoder(sparse=False)
encoded = encoder.fit_transform(data)
print(encoded)
Application: Used in ML models that require numeric input like logistic regression or neural
networks.
Q2. Describe the difference between fit_transform(), fit() and transform()

methods. Answer:

Method Description

fit() Learns parameters from data (e.g., mean/std)

transform() Applies the learned parameters to transform data

fit_transform() Combines fit() and transform() in one step

Example:

scaler = StandardScaler()
[Link](X_train) # learns mean/std
X_train_scaled = [Link](X_train) # uses learned parameters
# OR
X_train_scaled = scaler.fit_transform(X_train)

Q3. Demonstrate how to load a dataset in Python using Pandas and perform basic
summary statistics.

Answer:

import pandas as pd

# Load dataset
df = pd.read_csv("[Link]")

# Display first 5 rows


print([Link]())

# Summary statistics
print([Link]())
# Check for missing values
print([Link]().sum())
******************************************************************************

Q1. Analyze a dataset to deal with missing values and the potential impact of these missing
values on a machine learning model.

Answer:
Missing data can reduce model accuracy, introduce bias, or cause errors during training.

Handling Missing Values:

● Remove rows (dropna())

● Impute with mean/median/mode (SimpleImputer)

● Predict missing values (advanced methods)

Code Example:

import pandas as pd
from [Link] import SimpleImputer

df = pd.read_csv("[Link]")
print("Missing before:\n", [Link]().sum())

# Imputation
imputer = SimpleImputer(strategy='mean')
df[['Age', 'Salary']] = imputer.fit_transform(df[['Age', 'Salary']])
print("Missing after:\n", [Link]().sum())

Impact on Model:

● Improved completeness

● Better generalization
● Avoids runtime errors
Q2. Analyze how the “compose” module is significant in Python for data preprocessing.

Answer:
The [Link] module allows combining multiple preprocessing steps for different
column types using ColumnTransformer.

Significance:

● Streamlines preprocessing for numerical and categorical columns

● Reduces manual processing

● Supports pipeline integration

Code Example:

from [Link] import ColumnTransformer


from [Link] import StandardScaler, OneHotEncoder
import pandas as pd

df = [Link]({
'age': [25, 30, 35],
'city': ['Delhi', 'Mumbai', 'Chennai']
})

preprocessor = ColumnTransformer(
transformers=[
('num', StandardScaler(), ['age']),
('cat', OneHotEncoder(), ['city'])
])

processed = preprocessor.fit_transform(df)
print(processed)

*****************************************************************************

Here are detailed notes on data normalization, standardization, and train-test split with clear
explanations of why normalization is done after splitting the data.
Data Normalization, Standardization, and Train-Test Split

1. Data Normalization

Definition:
Normalization is the process of rescaling features to a specific range, typically [0, 1] or [-1, 1],
without distorting differences in the ranges of values.

Formula:
For Min-Max Normalization:

Use Case:

● Suitable when the data has varying scales.

● Useful for distance-based models like KNN, K-means, Neural Networks.

Code Example:

from [Link] import MinMaxScaler


import numpy as np

data = [Link]([[1, 20], [2, 40], [3, 60]])


scaler = MinMaxScaler()
normalized_data = scaler.fit_transform(data)
print(normalized_data)

2. Data Standardization

Definition:
Standardization transforms data to have zero mean and unit variance.
This is achieved using Z-score scaling.
Formula:

where

● μ\mu = mean of feature values

● σ\sigma = standard deviation of feature values

Use Case:

● Works well with algorithms like SVM, Logistic Regression, PCA.

● Keeps negative values (unlike normalization).

Code Example:

from [Link] import StandardScaler

data = [[1, 20], [2, 40], [3, 60]]


scaler = StandardScaler()
standardized_data = scaler.fit_transform(data)
print(standardized_data)

3. Train-Test Split

Definition:
The train_test_split function from scikit-learn divides the dataset into training and testing sets,
ensuring the model is trained on one part and evaluated on unseen data.

Why split the data?


● To prevent overfitting.
● To check how the model performs on unseen data.

Code Example:

from sklearn.model_selection import train_test_split

X = [[1], [2], [3], [4], [5]]


y = [1, 2, 3, 4, 5]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

print("Train:", X_train, y_train)


print("Test:", X_test, y_test)

4. Why Normalization Should Be Done After Train-Test Split

Key Point:
We must fit the scaler only on training data and then transform both train and test data
using the same parameters (mean, std, min, max from the training set).

Reason:

1. If we normalize the entire dataset before splitting, information from the test set leaks
into the training process (data leakage).

2. The test set should mimic real-world unseen data.

Correct Approach:

scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train) # Fit + transform training data
X_test_scaled = [Link](X_test) # Transform test data using training params

5. Why Train-Test Split Should Not Be Null?


● Null test split means no evaluation: If you do not split the dataset, the model is
evaluated on the same data it was trained on, leading to over-optimistic
performance
metrics.

● Generalization check fails: Without a test set, we cannot measure how well the model
performs on new, unseen data.

Summary

Concept Purpose Normalization Scale values to a fixed range (0 to 1).

Standardization Center data around 0 with unit variance.

Train-Test Split Evaluate generalization of the model.

NormalizationAfter
Split
Prevents data leakage.

Common questions

Powered by AI

Data standardization or normalization should precede feature encoding to ensure that the numerical features are on comparable scales before integration with categorical data through encoding. Premature encoding can inflate feature dimensions, adding sparse high cardinality that complicates successive scaling. By scaling numeric features early, the integrative model pipeline can maintain numerical stability, preventing issues related to difference in variances or biases in scale between newly created features .

Standardization is critical for algorithms like SVM and KNN because it ensures that each feature contributes equally to the distance calculations, hence improving convergence speed and model performance. It transforms data to have zero mean and unit variance. Unlike normalization, which scales features to a specific range (like 0 to 1), standardization retains the negative and positive values, maintaining the data's original distribution while removing mean and scaling variance .

Feature scaling affects model performance by ensuring that all features contribute equally to the distance calculations and have comparable ranges, especially important for algorithms sensitive to feature magnitude like KNN or neural networks. Common sklearn techniques include StandardScaler, which standardizes features causing zero mean and unit variance, and MinMaxScaler, which normalizes the data into a specific range like 0 to 1. These methods facilitate faster convergence and improved model accuracy .

Label Encoding converts categorical labels into integer values, which can inadvertently introduce a numerical relationship when none exists. This method is best used for tree-based models where such ordering doesn't affect model performance. In contrast, OneHotEncoding converts categories into a binary matrix, generating a distinct feature for each level of the categorical variable. It avoids ordinal relations, making it suitable for linear models like logistic regression or neural networks that require numerical input without assuming order .

Missing values can lead to model inaccuracies, biases, or training errors. Such data can distort patterns and relationships within the dataset, negatively affecting the model's ability to learn. Strategies to handle missing values include removing them using dropna(), imputing with statistical measures like mean, median, or mode using SimpleImputer, or employing advanced prediction-based methods. Addressing missing values ensures model completeness, better generalization, and avoids runtime errors .

MinMaxScaler is preferred when the goal is to scale features to a specific range, often 0 to 1, which is beneficial when the model needs to have all inputs treated equally on a bounded scale, such as in gradient descent optimizers or Nearest Neighbors algorithms. It's particularly suited for models that assume distance or similarity measures, like KNN or K-means, where feature magnitude can disproportionately affect results. In contrast, StandardScaler is used when there is a need to focus on retaining original data distribution properties while centering data around zero .

Normalization should be performed after the train-test split to prevent data leakage. If the entire dataset is normalized before splitting, information from the test set can inadvertently influence the training dataset, leading to an overfitted model that does not generalize well to unseen data. By splitting the data first and then fitting the scaler only on the training data, we ensure that the test set remains truly representative of unseen, real-world data .

The sklearn.compose module, specifically through the use of ColumnTransformer, significantly enhances preprocessing by allowing different transformations to be applied to different column types within a dataset. It streamlines the process of handling datasets with both numerical and categorical data by enabling a unified workflow. This integration supports pipeline creation, making preprocessing less error-prone and more efficient in preparing data for modeling .

The SimpleImputer class in sklearn is utilized to fill in missing data points using a defined strategy such as mean, median, most frequent, or a constant value. By employing SimpleImputer, datasets can maintain their dimensional integrity without omitting entire rows or columns, thus retaining more useful data for modeling. This imputation aids in strengthening the model's robustness by mitigating biases and minimizing data-induced errors during training .

The train_test_split function divides a dataset into separate training and testing sets, which is crucial for evaluating a model's generalization capabilities on new, unseen data. A test split is essential to accurately assess a model's performance without any bias from the training data. Without it, models risk being overfitted to the training data, leading to overly optimistic performance metrics and poor performance in production environments .

You might also like