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

Feature Engineering

Feature Engineering

Imagine you are a chef preparing a delicious dish; the machine learning model is like your "cooking algorithm", and the raw data is the various ingredients you buy from the market: vegetables, meat, and seasonings, but some may be muddy, some in whole pieces, and some with strong flavors.Feature Engineering, is the process of cleaning, cutting, marinating, and combining these raw "ingredients", finally processing them into "semi-finished products" ready for cooking. It is the bridge connecting raw data and machine learning models, and a critical step that determines the upper limit of model performance.

Simply put,Feature Engineeringis the process of using domain knowledge and a series of technical methods to extract, construct, and select from raw data features (variables) that are more valuable and easier to learn for machine learning models.


I. Why is feature engineering so important?

In machine learning projects, the quality of data and features directly determines the upper limit of model performance, while models and algorithms merely approach this limit. Good feature engineering can:

  1. Improve model performance: Good features make it easier for the model to discover patterns in the data.
  2. Speed up model training: Reducing irrelevant or redundant features can lower computational complexity.
  3. Enhance model generalization ability: Prevent the model from overfitting to noise in the training data.
  4. Meet model requirements: Different models have different assumptions about data (e.g., linear models assume linear relationships); feature engineering can make the data satisfy these assumptions.

We can use the following flowchart to intuitively understand the position of feature engineering in the entire machine learning workflow:


II. Core operations of feature engineering

Feature engineering mainly includes three major categories of operations:Feature Processing、Feature constructionandFeature selection。

1. Feature processing

This is the most basic step, aimed at "cleaning" raw data into a neat, well-organized format.

a) Handling missing values

Missing values often exist in data (e.g., NaN, NULL), which need to be handled properly.

Handling Methods Description Applicable scenarios
Delete Directly delete the rows or columns containing missing values. When missing data is very rare, or the feature is unimportant.
Fill Fill with a certain value, such as the mean, median, mode, or a special value (e.g., -1). The most commonly used method, applicable in various situations.
Interpolation Use time series or neighboring data points for interpolation. For time series data,

Code example (using Python's pandas library):

Example

import

pandas

as

pd

import

numpy

as

np

Create a sample DataFrame containing missing values.

data

=

{

'Age'

:

[

25

,

np.

nan

,

30

,

35

,

np.

nan

]

,

       

'Salary'

:

[

50000

,

54000

,

np.

nan

,

62000

,

58000

]

,

       

'City'

:

[

'Beijing'

,

'Shanghai'

,

'Guangzhou'

,

np.

nan

,

'Beijing'

]

}

df

=

pd.

DataFrame

(

data

)

print

(

"Original data:"

)

print

(

df

)

1. Remove missing values (delete any row containing NaN).

df_dropped

=

df.

dropna

(

)

print

(

"\nAfter removing missing values:"

)

print

(

df_dropped

)

2. Fill missing values.

Fill numeric columns with the mean.

df_filled

=

df.

copy

(

)

df_filled

[

'Age'

]

.

fillna

(

df_filled

[

'Age'

]

.

mean

(

)

,

inplace

=

True

)

df_filled

[

'Salary'

]

.

fillna

(

df_filled

[

'Salary'

]

.

mean

(

)

,

inplace

=

True

)

Fill categorical columns with the mode.

df_filled

[

'City'

]

.

fillna

(

df_filled

[

'City'

]

.

mode

(

)

[

0

]

,

inplace

=

True

)

print

(

"\nAfter filling missing values:"

)

print

(

df_filled

)

b) Handling outliers

Outliers are values significantly different from most data and may interfere with the model. Common detection methods include:

Treatment can be deletion, replacement with boundary values, or handling as missing values.

c) Data standardization/normalization

Many models (such as SVM, KNN, neural networks) are sensitive to feature scales. We need to transform features of different scales to the same scale.

Method Formula Description Applicable scenarios
Standardization (x - 均值) / 标准差 After processing, the data has mean 0 and standard deviation 1. When the data distribution is approximately normal.
Normalization (x - min) / (max - min) Scale the data to the [0, 1] interval. When data boundaries are clear and fast computation is needed.

Code example (using the scikit-learn library):

Example

from

sklearn.

preprocessing

import

StandardScaler

,

MinMaxScaler

import

numpy

as

np

Sample data

data

=

np.

array

(

[

[

1000

,

25

]

,

                 

[

1500

,

30

]

,

                 

[

800

,

20

]

,

                 

[

1200

,

28

]

]

)

Standardization

scaler_standard

=

StandardScaler

(

)

data_standardized

=

scaler_standard.

fit_transform

(

data

)

print

(

"Standardized data (mean ~0, std ~1):"

)

print

(

data_standardized

)

print

(

f

"Mean: {data_standardized.mean(axis=0)}"

)

print

(

f

"Std: {data_standardized.std(axis=0)}"

)

Normalization

scaler_minmax

=

MinMaxScaler

(

)

data_normalized

=

scaler_minmax.

fit_transform

(

data

)

print

(

"\nNormalized data (range [0,1]):"

)

print

(

data_normalized

)

2. Feature construction

Create new, more predictive features by combining or transforming existing features.

a) Transforming numeric features

b) Encoding categorical features

Machine learning models cannot directly handle text like "Beijing" or "Shanghai". They need to be converted into numbers.

Method Description Feature
Label Encoding Assign a unique integer to each category, such as 北京:0, 上海:1 Simple, but may introduce incorrect ordinal relationships (the model may think 1>0).
One-Hot Encoding Create a new binary feature (0 or 1) for each category. Eliminates ordinal misunderstanding, but if there are many categories, it leads to feature dimension explosion.

Code example:

Example

import

pandas

as

pd

from

sklearn.

preprocessing

import

LabelEncoder

,

OneHotEncoder

Sample data

df_cat

=

pd.

DataFrame

(

{

'City'

:

[

'Beijing'

,

'Shanghai'

,

'Guangzhou'

,

'Beijing'

,

'Shenzhen'

]

}

)

Label Encoding

le

=

LabelEncoder

(

)

df_cat

[

'city_label_encoding'

]

=

le.

fit_transform

(

df_cat

[

'City'

]

)

print

(

"Label encoding result:"

)

print

(

df_cat

)

One-Hot Encoding

Method 1: Using pandas' get_dummies.

df_onehot_pd

=

pd.

get_dummies

(

df_cat

[

'City'

]

,

prefix

=

'City'

)

print

(

"\nOne-hot encoding with pandas:"

)

print

(

df_onehot_pd

)

Method 2: Using sklearn's OneHotEncoder (more commonly used in pipelines).

ohe

=

OneHotEncoder

(

sparse_output

=

False

)

sparse_output=False returns an array instead of a sparse matrix.

encoded_array

=

ohe.

fit_transform

(

df_cat

[

[

'City'

]

]

)

Note that the input is two-dimensional.

print

(

"\nOne-hot encoding with sklearn (array form):"

)

print

(

encoded_array

)

print

(

"New feature names:"

,

ohe.

get_feature_names_out

(

)

)

3. Feature selection

Select the most important subset from all features to reduce dimensionality and lower the risk of overfitting.

Method Description
Filter method Rank and filter based on the statistical correlation between features and the target variable (e.g., variance, chi-square test, mutual information). Independent of any model.
Wrapper method Treat feature selection as a search problem, using model performance as the evaluation criterion (e.g., recursive feature elimination, RFE). Effective, but computationally expensive.
Embedded method Automatically perform feature selection during model training (e.g., L1-regularized LASSO regression, feature importance of tree models).

Code example (selection based on feature importance):

Example

from

sklearn.

datasets

import

load_breast_cancer

from

sklearn.

ensemble

import

RandomForestClassifier

import

pandas

as

pd

import

matplotlib.

pyplot

as

plt

Load the dataset

data

=

load_breast_cancer

(

)

X

=

pd.

DataFrame

(

data.

data

,

columns

=

data.

feature_names

)

y

=

data.

target

Train a random forest model, which computes feature importance.

model

=

RandomForestClassifier

(

n_estimators

=

100

,

random_state

=

42

)

model.

fit

(

X

,

y

)

Get feature importance

importances

=

model.

feature_importances_

feature_importance_df

=

pd.

DataFrame

(

{

   

'feature'

: data.

feature_names

,

   

'importance'

: importances

}

)

.

sort_values

(

'importance'

,

ascending

=

False

)

print

(

"Feature importance ranking:"

)

print

(

feature_importance_df.

head

(

10

)

)

View the top 10 most important features.

Visualization

plt.

figure

(

figsize

=

(

10

,

6

)

)

plt.

barh

(

feature_importance_df

[

'feature'

]

[

:

10

]

,

feature_importance_df

[

'importance'

]

[

:

10

]

)

plt.

xlabel

(

'feature_importance'

)

plt.

title

(

'Top 10 feature importance'

)

plt.

gca

(

)

.

invert_yaxis

(

)

Put the most important at the top.

plt.

show

(

)

Assume we select features with importance greater than 0.03.

selected_features

=

feature_importance_df

[

feature_importance_df

[

'importance'

]

0.03

]

[

'feature'

]

.

tolist

(

)

print

(

f

"\nSelected features: {selected_features}"

)


III. Practical exercise: Hands-on with a simple dataset

Task: Perform basic feature engineering on the famous Titanic passenger dataset, in preparation for predicting whether passengers survived.

Step hints:

  1. Load the data (you can use seaborn In the library, the load_dataset('titanic'))。
  2. Observe the data: check feature types and missing values.
  3. Feature processing:
  4. Handle missing values (e.g., fill with the medianage, fill with the modeembarked)。
  5. data to the child component viasex(gender) feature withLabel EncodingorOne-Hot Encoding。
  6. locksage(age) withBinning, creating new age-group features.
  7. - Handle missing values (e.g., fill `age` with the median, fill `embarked` with the mode). - Perform **label encoding** or **one-hot encoding** on the `sex` (gender) feature. - **Bin** `age` (age) to create new age-group features.
    1. Feature construction:
    2. combined withsibsp(siblings/spouse count) andparch(parents/children count), construct a newfamily_size(family size) feature.
    3. - Combine `sibsp` (siblings/spouse count) and `parch` (parents/children count) to construct a new `family_size` (family size) feature.
      1. Feature selection:
      2. Remove features you consider obviously irrelevant (e.g.,passenger_id, name, ticket)。
      3. Try computing the correlation between numeric features and the survival target to filter features.
      4. - Remove features you consider obviously irrelevant (e.g., `passenger_id`, `name`, `ticket`). - Try computing the correlation between numeric features and the survival target to filter features.

        Through this exercise, you will experience firsthand how raw data, step by step through feature engineering, becomes more "friendly" to machine learning models.

        Summary

        Feature engineering is a craft in machine learning that combinesart(domain knowledge, experience, intuition) withscience(statistical methods, algorithms). It has no fixed rules and requires repeated trial and iteration based on specific data, problems, and models. For beginners, mastering the basic methods introduced here and practicing diligently, you have already laid the strongest foundation for building effective machine learning models. Remember,excellent models often stem from excellent features.。