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
(
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:
- Fill with mean (Mean): suitable for numerical data.
- Fill with median (Median): for datasets containing outliers, using the median may be more effective.
- Fill with most frequent value (Mode): suitable for categorical data.
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: transforms the data into a distribution with mean 0 and standard deviation 1. Suitable for most machine learning algorithms.
- Normalization: scales the data to a specified range (usually [0, 1]).
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?
-
Standardization: it is very important for distance metrics (such as K-Nearest Neighbors, Support Vector Machines, etc.), because inconsistent feature scales may cause some features to have excessive influence on the model. Standardization ensures each feature contributes equally to the model.
-
Normalization: some algorithms (such as neural networks, gradient descent optimization algorithms, etc.) are very sensitive to the range of input data, and normalization helps accelerate convergence.
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_
(
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:
- Feature Combination: combining two or more features into a new feature.
- Feature Transformation: applying logarithmic, square root, or other transformations to features to address nonlinearity in the data.
- Feature Creation: creating new features from existing data, such as extracting date, month, and weekday from a timestamp.
Example
For example, combining two numerical features into a new feature
df
[
'new_feature'
]
=
df
[
'feature1'
]
- df
[
'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:
- Dimensionality reduction: when there are too many features, using PCA for dimensionality reduction can reduce computational cost while preserving the main information of the data.
- Visualization: mapping high-dimensional data to 2D or 3D space to help us visualize the data structure.
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
)