Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Sklearn Data Preprocessing

Sklearn Data Preprocessing

Data preprocessing is a critical step in machine learning projects, directly affecting the model's training effectiveness and final performance.

When building machine learning models, data preprocessing is a crucial step that helps clean and transform raw data to provide the best input for machine learning models.

Data preprocessing involves multiple steps, including handling missing values, data transformation, standardization, encoding, etc.

Proper preprocessing not only improves model accuracy but also helps the model generalize better.


1. Handling Missing Values

Missing values refer to the absence of values for certain features in a dataset.

Machine learning algorithms usually cannot directly handle missing values, so we need to process them.

Check for missing values

First, check whether there are missing values in the dataset.

Usually you can use pandas to inspect missing values in the dataset:

Example

import

pandas

as

pd

Suppose we have a DataFrame df

print

(

df.

isnull

(

)

.

sum

(

)

)

 

View the number of missing values in each column

Fill missing values

For handling missing values, the most common method is filling.

Common filling strategies include:

In scikit-learn, SimpleImputer can easily perform missing value imputation:

Example

from

sklearn.

impute

import

SimpleImputer

For numerical data, use mean imputation

imputer

=

SimpleImputer

(

strategy

=

'mean'

)

 

Optional: 'mean', 'median', 'most_frequent'

df_imputed

=

imputer.

fit_transform

(

df

)

 

Fill missing values

Delete missing values

If the number of missing values is small and removing them will not significantly affect the analysis results, another option is to directly delete the missing values.



df_cleaned = df.dropna()  # 删除包含缺失值的行

For more information, refer to:

Pandas Data Cleaning


2. Data Scaling

Machine learning algorithms are sensitive to the scale of data, so data needs to be scaled so that features have the same scale.

Common scaling methods include:

Standardization

Standardization can be implemented via StandardScaler, which transforms each feature to zero mean and unit variance:

Example

from

sklearn.

preprocessing

import

StandardScaler

scaler

=

StandardScaler

(

)

X_scaled

=

scaler.

fit_transform

(

X

)

 

Standardize X

Normalization

Normalization scales each feature to a specified range (usually [0, 1]).

MinMaxScaler is used to normalize the data:

Example

from

sklearn.

preprocessing

import

MinMaxScaler

scaler

=

MinMaxScaler

(

)

X_normalized

=

scaler.

fit_transform

(

X

)

 

Normalize X

Why do we need standardization and normalization?


3. Categorical Variable Encoding

Machine learning models usually cannot directly process string-type categorical variables, so categorical variables need to be converted into numerical data.

Common encoding methods include:

Label Encoding

Label encoding maps each category to a unique integer.

Suitable for cases where there is an ordinal relationship between categories (e.g., low, medium, high).

Example

from

sklearn.

preprocessing

import

LabelEncoder

Suppose we have a categorical variable y

label_encoder

=

LabelEncoder

(

)

y_encoded

=

label_encoder.

fit_transform

(

y

)

 

Convert the categorical variable to integers

One-Hot Encoding

One-hot encoding converts each category into a binary vector, suitable for cases where there is no ordinal relationship between categories (e.g., color, country, etc.).

OneHotEncoder can convert categorical variables into one-hot encoding.

Example

from

sklearn.

preprocessing

import

OneHotEncoder

Suppose we have a categorical variable X

encoder

=

OneHotEncoder

(

sparse

=

False

)

 

sparse=False returns a dense matrix

X_encoded

=

encoder.

fit_transform

(

X

)

 

Convert the categorical variable to one-hot encoding

In pandas, you can also use the get_dummies() function for one-hot encoding:



X_encoded = pd.get_dummies(X)


4. Feature Selection

Feature selection improves model performance and reduces computational cost by selecting the most important features.

Common feature selection methods include:

Model-based feature selection

Use some machine learning models (such as decision trees or random forests) to evaluate feature importance for feature selection.

Example

from

sklearn.

ensemble

import

RandomForestClassifier

Train a random forest model

clf

=

RandomForestClassifier

(

)

clf.

fit

(

X_train

,

y_train

)

Get feature importance

importances

=

clf.

feature_importances_

print

(

importances

)

Recursive Feature Elimination (RFE)

RFE is a method that recursively removes the least important features step by step to select the optimal features.

RFE can help us automatically select important features.

Example

from

sklearn.

feature_selection

import

RFE

Use a linear model for recursive feature elimination

rfe

=

RFE

(

clf

,

n_features_to_select

=

3

)

 

Keep the 3 most important features

X_rfe

=

rfe.

fit_transform

(

X_train

,

y_train

)


5. Feature Engineering

Feature engineering improves model performance by processing, combining, or constructing new features from existing ones.

Common approaches to feature engineering include:

Example

For example, combining two numerical features into a new feature

df

[

'new_feature'

]

=

df

[

'feature1'

]

[

'feature2'

]


6. Feature Extraction

Feature extraction aims to derive new, more expressive features from the original features.

Common feature extraction methods include: Principal Component Analysis (PCA) and Linear Discriminant Analysis (LDA).

Principal Component Analysis (PCA)

PCA is a commonly used dimensionality reduction technique that maps data from a high-dimensional space to a low-dimensional space through linear transformation, so that the new features (principal components) preserve the data's variance as much as possible.

PCA is especially suitable when the number of features is too large, effectively reducing computational complexity.

Example

from

sklearn.

decomposition

import

PCA

Suppose X is the feature matrix

pca

=

PCA

(

n_components

=

2

)

 

Reduce to 2 principal components

X_pca

=

pca.

fit_transform

(

X

)

PCA is mainly used in two scenarios:

Linear Discriminant Analysis (LDA)

LDA is a supervised dimensionality reduction method that aims to find a linear combination that maximizes the distance between different classes and minimizes the distance within each class.

LDA is typically used in classification tasks.

Example

from

sklearn.

discriminant_analysis

import

LinearDiscriminantAnalysis

Suppose X is the feature matrix and y is the target variable

lda

=

LinearDiscriminantAnalysis

(

n_components

=

2

)

 

Reduce to 2 linear discriminant components

X_lda

=

lda.

fit_transform

(

X

,

y

)


7. Handling Imbalanced Data

In classification problems, if the number of samples in each class differs significantly, the model may be biased toward predicting the majority class, affecting its performance.

Common handling methods include:

Over-sampling

Balance the dataset by increasing the number of minority class samples.

A common method is to use the SMOTE (Synthetic Minority Over-sampling Technique) algorithm.

Example

from

imblearn.

over_sampling

import

SMOTE

smote

=

SMOTE

(

)

X_resampled

,

y_resampled

=

smote.

fit_resample

(

X_train

,

y_train

)

Under-sampling

Balance the dataset by reducing the number of majority class samples.

Example

from

imblearn.

under_sampling

import

RandomUnderSampler

undersampler

=

RandomUnderSampler

(

)

X_resampled

,

y_resampled

=

undersampler.

fit_resample

(

X_train

,

y_train

)