特征工程中的特征变换是一个重要的步骤,旨在通过转换原始特征来提高模型的性能。特征变换主要包括数值特征的归一化和标准化、类别特征的编码、特征组合和分解、以及特征缩放等。下面将详细讲解这些内容,并提供相应的Python代码示例。
1. 数值特征的归一化和标准化
归一化(Normalization)
归一化是将特征的值缩放到一个固定的范围(通常是 [0, 1])内。归一化常用于在特征值范围差异较大的情况下,减小这种差异对模型的影响。
归一化的公式通常为:
标准化(Standardization)
标准化是将特征的值转换为均值为0、标准差为1的正态分布。标准化在数据具有不同的度量单位或不同的范围时非常有用。
标准化的公式为:
示例代码:
import numpy as np
import pandas as pd
from sklearn.preprocessing import MinMaxScaler, StandardScaler
# 生成示例数据
data = {'feature1': np.random.rand(100) * 10, 'feature2': np.random.rand(100) * 100}
df = pd.DataFrame(data)
# 归一化
scaler = MinMaxScaler()
df[['feature1_norm', 'feature2_norm']] = scaler.fit_transform(df[['feature1', 'feature2']])
# 标准化
scaler = StandardScaler()
df[['feature1_std', 'feature2_std']] = scaler.fit_transform(df[['feature1', 'feature2']])
print(df.head())
 
运行结果示例:
   feature1   feature2  feature1_norm  feature2_norm  feature1_std  feature2_std
0  5.371278  50.936181       0.537127       0.509362     0.177720     0.066669
1  1.122034  89.489587       0.112203       0.894896    -1.264731     1.370891
2  7.991217  16.046858       0.799122       0.160469     1.139588    -1.162611
3  4.543309  18.512042       0.454331       0.185120    -0.044308    -1.063248
4  6.940704   8.839065       0.694070       0.088391     0.718581    -1.480131
 
2. 类别特征的编码
类别特征编码是将离散的类别变量转换为数值变量,使其可以被模型理解。常见的类别编码方法包括独热编码、标签编码、频率编码和目标编码。
独热编码(One-Hot Encoding)
独热编码将每个类别转换为一个独立的二进制特征。每个特征只包含0或1,表示某个类别是否存在。
标签编码(Label Encoding)
标签编码将每个类别映射到一个唯一的整数。适用于具有顺序关系的类别变量。
示例代码:
from sklearn.preprocessing import OneHotEncoder, LabelEncoder
# 生成示例数据
df = pd.DataFrame({'category': ['A', 'B', 'C', 'A', 'B', 'C']})
# 独热编码
onehot_encoder = OneHotEncoder(sparse=False)
onehot_encoded = onehot_encoder.fit_transform(df[['category']])
onehot_df = pd.DataFrame(onehot_encoded, columns=onehot_encoder.get_feature_names_out(['category']))
# 标签编码
label_encoder = LabelEncoder()
df['category_encoded'] = label_encoder.fit_transform(df['category'])
print(df.head())
print(onehot_df.head())
 
运行结果示例:
  category  category_encoded
0        A                 0
1        B                 1
2        C                 2
3        A                 0
4        B                 1
   category_A  category_B  category_C
0         1.0         0.0         0.0
1         0.0         1.0         0.0
2         0.0         0.0         1.0
3         1.0         0.0         0.0
4         0.0         1.0         0.0
 
3. 特征组合和分解
特征组合和分解是通过组合现有特征或分解特征来创建新的特征,从而增加模型的表达能力。
特征组合
特征组合通过交互或多项式特征生成新的特征。例如,将两个数值特征相乘或取它们的平方。
特征分解
特征分解通过将一个复杂的特征分解成多个简单的特征。例如,将一个日期特征分解为年、月、日。
示例代码:
from sklearn.preprocessing import PolynomialFeatures
# 生成示例数据
df = pd.DataFrame({'feature1': [1, 2, 3, 4, 5], 'feature2': [10, 20, 30, 40, 50]})
# 特征组合(多项式特征)
poly = PolynomialFeatures(degree=2, include_bias=False)
poly_features = poly.fit_transform(df)
poly_df = pd.DataFrame(poly_features, columns=poly.get_feature_names_out(['feature1', 'feature2']))
# 特征分解(日期分解)
df['date'] = pd.to_datetime(['2022-01-01', '2022-02-01', '2022-03-01', '2022-04-01', '2022-05-01'])
df['year'] = df['date'].dt.year
df['month'] = df['date'].dt.month
df['day'] = df['date'].dt.day
print(df.head())
print(poly_df.head())
 
运行结果示例:
   feature1  feature2  year  month  day
0         1        10  2022      1    1
1         2        20  2022      2    1
2         3        30  2022      3    1
3         4        40  2022      4    1
4         5        50  2022      5    1
   feature1  feature2  feature1^2  feature1 feature2  feature2^2
0         1        10           1           10         100
1         2        20           4           40         400
2         3        30           9           90         900
3         4        40          16          160        1600
4         5        50          25          250        2500
 
4. 特征缩放
特征缩放是指将特征数据进行比例调整,以便它们位于一个更合理的范围内,通常在应用梯度下降类算法时尤为重要。
常见方法:
- 最小-最大缩放(Min-Max Scaling):将数据缩放到指定范围内,通常是[0, 1]。
 - Z-Score缩放:将数据缩放为均值为0,标准差为1的分布。
 
示例代码:
from sklearn.preprocessing import MinMaxScaler, StandardScaler
# 生成示例数据
data = {'feature1': [1, 2, 3, 4, 5], 'feature2': [10, 20, 30, 40, 50]}
df = pd.DataFrame(data)
# 最小-最大缩放
scaler = MinMaxScaler()
df[['feature1_minmax', 'feature2_minmax']] = scaler.fit_transform(df[['feature1', 'feature2']])
# Z-Score缩放
scaler = StandardScaler()
df[['feature1_zscore', 'feature2_zscore']] = scaler.fit_transform(df[['feature1', 'feature2']])
print(df.head())
 
运行结果示例:
   feature1  feature2  feature1_minmax  feature2_minmax  feature1_zscore  feature2_zscore
0         1        10              0.0              0.0        -1.414214        -1.414214
1         2        20              0.25             0.25        -0.707107        -0.707107
2         3        30              0.5              0.5          0.000000         0.000000
3          4        40              0.75             0.75         0.707107         0.707107
4          5        50              1.0              1.0          1.414214         1.414214
 
5. 总结
- 归一化 和 标准化 是数值特征变换中的常用方法,可以使特征更适合用于模型训练。
 - 类别特征编码 通过将类别数据转换为数值数据,使模型能够理解类别特征。
 - 特征组合和分解 通过生成新的特征或分解复杂特征来增加模型的表达能力。
 - 特征缩放 通过调整特征的比例,使其更适合于模型训练,特别是在应用梯度下降等算法时。
 
这些特征变换方法在特定的场景下能够显著提高模型的性能,是特征工程中不可忽视的重要步骤。



















