scikit-learn数据预处理技巧全解析:从缺失值填充到特征缩放的实战指南

引言
在机器学习项目中,数据预处理是决定模型性能的关键步骤。原始数据往往包含噪声、缺失值、量纲差异等问题,直接使用这些数据训练模型会导致结果不理想。scikit-learn作为Python生态中最受欢迎的机器学习库,提供了丰富且高效的数据预处理工具。本文将系统解析scikit-learn中的核心预处理技巧,涵盖缺失值处理、特征编码、特征缩放等关键环节,并通过完整的实战代码示例帮助读者掌握这些技术。
一、缺失值处理
1.1 缺失值检测
在处理缺失值之前,首先需要识别数据中的缺失值。pandas提供了便捷的方法来检测缺失值:
import pandas as pd
import numpy as np
from sklearn.impute import SimpleImputer, KNNImputer

# 创建示例数据集
data = pd.DataFrame({
‘age’: [25, 30, np.nan, 35, 40],
‘income’: [50000, 60000, 70000, np.nan, 80000],
‘score’: [85, np.nan, 90, 88, np.nan]
})

print(“原始数据:”)
print(data)
print(“\n缺失值统计:”)
print(data.isnull().sum())
1.2 简单填充策略
SimpleImputer是处理缺失值的基础工具,支持均值、中位数、众数和常数填充:
# 均值填充
mean_imputer = SimpleImputer(strategy=’mean’)
data_mean = data.copy()
data_mean[[‘age’, ‘income’, ‘score’]] = mean_imputer.fit_transform(data_mean[[‘age’, ‘income’, ‘score’]])

# 中位数填充
median_imputer = SimpleImputer(strategy=’median’)
data_median = data.copy()
data_median[[‘age’, ‘income’, ‘score’]] = median_imputer.fit_transform(data_median[[‘age’, ‘income’, ‘score’]])

# 众数填充(适用于分类变量)
mode_imputer = SimpleImputer(strategy=’most_frequent’)
data_mode = data.copy()
data_mode[[‘age’, ‘income’, ‘score’]] = mode_imputer.fit_transform(data_mode[[‘age’, ‘income’, ‘score’]])

# 常数填充
constant_imputer = SimpleImputer(strategy=’constant’, fill_value=0)
data_constant = data.copy()
data_constant[[‘age’, ‘income’, ‘score’]] = constant_imputer.fit_transform(data_constant[[‘age’, ‘income’, ‘score’]])

print(“均值填充结果:”)
print(data_mean)
1.3 高级填充方法
对于时间序列或具有空间相关性的数据,可以使用KNNImputer基于最近邻进行填充:
# KNN填充
knn_imputer = KNNImputer(n_neighbors=2)
data_knn = data.copy()
data_knn[[‘age’, ‘income’, ‘score’]] = knn_imputer.fit_transform(data_knn[[‘age’, ‘income’, ‘score’]])

print(“KNN填充结果:”)
print(data_knn)
1.4 自定义填充策略
对于复杂场景,可以使用FunctionTransformer创建自定义填充逻辑:
from sklearn.preprocessing import FunctionTransformer

def custom_impute(X):
“””自定义填充:用前一行的值填充当前行的缺失值”””
X_filled = X.copy()
for col in X_filled.columns:
for i in range(1, len(X_filled)):
if pd.isna(X_filled.loc[i, col]):
X_filled.loc[i, col] = X_filled.loc[i-1, col]
return X_filled

custom_transformer = FunctionTransformer(custom_impute)
data_custom = custom_transformer.fit_transform(data)

print(“自定义填充结果:”)
print(data_custom)
二、特征编码
2.1 标签编码(Label Encoding)
将分类标签转换为整数编码:
from sklearn.preprocessing import LabelEncoder

# 示例数据
labels = [‘cat’, ‘dog’, ‘bird’, ‘cat’, ‘dog’]

label_encoder = LabelEncoder()
encoded_labels = label_encoder.fit_transform(labels)

print(“原始标签:”, labels)
print(“编码后:”, encoded_labels)
print(“逆变换:”, label_encoder.inverse_transform(encoded_labels))
2.2 独热编码(One-Hot Encoding)
将分类变量转换为二进制向量:
from sklearn.preprocessing import OneHotEncoder

# 示例数据
categories = [[‘cat’], [‘dog’], [‘bird’], [‘cat’], [‘dog’]]

onehot_encoder = OneHotEncoder(sparse=False)
encoded_categories = onehot_encoder.fit_transform(categories)

print(“原始类别:”, categories)
print(“独热编码后:”)
print(encoded_categories)
print(“特征名称:”, onehot_encoder.get_feature_names_out())
2.3 Ordinal Encoding
有序分类变量的编码:
from sklearn.preprocessing import OrdinalEncoder

# 示例数据
ratings = [[‘low’], [‘medium’], [‘high’], [‘low’], [‘medium’]]

ordinal_encoder = OrdinalEncoder(categories=[[‘low’, ‘medium’, ‘high’]])
encoded_ratings = ordinal_encoder.fit_transform(ratings)

print(“原始评分:”, ratings)
print(“序数编码后:”, encoded_ratings)
2.4 Target Encoding
基于目标变量均值进行编码,适用于高基数分类变量:
from category_encoders import TargetEncoder
import pandas as pd

# 示例数据
data = pd.DataFrame({
‘city’: [‘Beijing’, ‘Shanghai’, ‘Beijing’, ‘Guangzhou’, ‘Shanghai’],
‘target’: [1, 0, 1, 0, 0]
})

target_encoder = TargetEncoder()
data[‘city_encoded’] = target_encoder.fit_transform(data[‘city’], data[‘target’])

print(“Target Encoding结果:”)
print(data)
三、特征缩放
3.1 标准化(Standardization)
将特征缩放到均值为0,方差为1:
from sklearn.preprocessing import StandardScaler

# 示例数据
X = [[1, 2], [3, 4], [5, 6], [7, 8]]

scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)

print(“原始数据:”, X)
print(“标准化后:”, X_scaled)
print(“均值:”, scaler.mean_)
print(“方差:”, scaler.var_)
3.2 归一化(Normalization)
将特征缩放到指定范围(通常为[0,1]):
from sklearn.preprocessing import MinMaxScaler

# 示例数据
X = [[1, 2], [3, 4], [5, 6], [7, 8]]

minmax_scaler = MinMaxScaler()
X_normalized = minmax_scaler.fit_transform(X)

print(“原始数据:”, X)
print(“归一化后:”, X_normalized)
print(“最小值:”, minmax_scaler.min_)
print(“缩放比例:”, minmax_scaler.scale_)
3.3 Robust Scaling
对异常值鲁棒的缩放方法:
from sklearn.preprocessing import RobustScaler

# 包含异常值的数据
X = [[1], [2], [3], [4], [100]]

robust_scaler = RobustScaler()
X_robust = robust_scaler.fit_transform(X)

print(“原始数据:”, X)
print(“Robust Scaling后:”, X_robust)
3.4 最大值缩放(MaxAbsScaler)
将特征缩放到[-1,1]范围,保持稀疏性:
from sklearn.preprocessing import MaxAbsScaler

# 示例数据
X = [[-1, 2], [-3, 4], [5, -6]]

maxabs_scaler = MaxAbsScaler()
X_maxabs = maxabs_scaler.fit_transform(X)

print(“原始数据:”, X)
print(“MaxAbs Scaling后:”, X_maxabs)
四、特征工程与变换
4.1 多项式特征
生成特征的多项式组合:
from sklearn.preprocessing import PolynomialFeatures

# 示例数据
X = [[1, 2], [3, 4], [5, 6]]

poly = PolynomialFeatures(degree=2, include_bias=False)
X_poly = poly.fit_transform(X)

print(“原始特征:”, X)
print(“多项式特征:”, X_poly)
print(“特征名称:”, poly.get_feature_names_out())
4.2 分箱(Binning)
将连续变量转换为离散区间:
from sklearn.preprocessing import KBinsDiscretizer

# 示例数据
X = [[1.2], [2.5], [3.7], [4.1], [5.8]]

# 等宽分箱
kbins_equal = KBinsDiscretizer(n_bins=3, strategy=’equal_width’)
X_equal = kbins_equal.fit_transform(X)

# 等频分箱
kbins_quantile = KBinsDiscretizer(n_bins=3, strategy=’quantile’)
X_quantile = kbins_quantile.fit_transform(X)

print(“原始数据:”, X)
print(“等宽分箱:”, X_equal.toarray())
print(“等频分箱:”, X_quantile.toarray())
4.3 自定义变换
使用FunctionTransformer实现自定义特征变换:
from sklearn.preprocessing import FunctionTransformer

# 对数变换
log_transformer = FunctionTransformer(np.log1p, validate=True)
X_log = log_transformer.fit_transform(X)

# 平方根变换
sqrt_transformer = FunctionTransformer(np.sqrt, validate=True)
X_sqrt = sqrt_transformer.fit_transform(X)

print(“原始数据:”, X)
print(“对数变换:”, X_log)
print(“平方根变换:”, X_sqrt)
五、Pipeline集成
5.1 基础Pipeline
将多个预处理步骤组合成一个流水线:
from sklearn.pipeline import Pipeline
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split

# 创建示例数据
X, y = [[1, 2], [3, 4], [5, 6], [7, 8]], [0, 1, 0, 1]

# 构建Pipeline
pipeline = Pipeline([
(‘scaler’, StandardScaler()),
(‘classifier’, LogisticRegression())
])

# 训练模型
pipeline.fit(X, y)
print(“Pipeline训练完成,得分:”, pipeline.score(X, y))
5.2 复杂Pipeline与ColumnTransformer
处理混合类型数据(数值型和类别型):
from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import OneHotEncoder

# 创建混合数据
data = pd.DataFrame({
‘age’: [25, 30, 35, 40],
‘income’: [50000, 60000, 70000, 80000],
‘city’: [‘Beijing’, ‘Shanghai’, ‘Beijing’, ‘Shanghai’],
‘target’: [0, 1, 0, 1]
})

# 定义特征
numeric_features = [‘age’, ‘income’]
categorical_features = [‘city’]

# 创建ColumnTransformer
preprocessor = ColumnTransformer(
transformers=[
(‘num’, StandardScaler(), numeric_features),
(‘cat’, OneHotEncoder(), categorical_features)
])

# 完整Pipeline
full_pipeline = Pipeline([
(‘preprocessor’, preprocessor),
(‘classifier’, LogisticRegression())
])

# 拆分数据
X = data.drop(‘target’, axis=1)
y = data[‘target’]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42)

# 训练
full_pipeline.fit(X_train, y_train)
print(“复杂Pipeline得分:”, full_pipeline.score(X_test, y_test))
5.3 Pipeline中的特征选择
在预处理后进行特征选择:
from sklearn.feature_selection import SelectKBest, f_classif

# 在Pipeline中加入特征选择
pipeline_with_selection = Pipeline([
(‘preprocessor’, preprocessor),
(‘selector’, SelectKBest(score_func=f_classif, k=2)),
(‘classifier’, LogisticRegression())
])

pipeline_with_selection.fit(X_train, y_train)
print(“带特征选择的Pipeline得分:”, pipeline_with_selection.score(X_test, y_test))
六、高级预处理技巧
6.1 异常值检测与处理
使用Isolation Forest检测异常值:
from sklearn.ensemble import IsolationForest

# 创建包含异常值的数据
X = np.array([[1], [2], [3], [4], [100], [-50]])

iso_forest = IsolationForest(contamination=0.1, random_state=42)
outliers = iso_forest.fit_predict(X)

print(“异常值检测结果:”, outliers)
print(“异常值索引:”, np.where(outliers == -1)[0])
6.2 数据增强
使用imbalanced-learn库进行数据增强:
from imblearn.over_sampling import SMOTE
from sklearn.datasets import make_classification

# 创建不平衡数据集
X, y = make_classification(n_samples=1000, n_features=10, n_informative=2,
n_redundant=0, n_clusters_per_class=1, weights=[0.9, 0.1],
random_state=42)

print(“原始类别分布:”, np.bincount(y))

# SMOTE过采样
smote = SMOTE(random_state=42)
X_resampled, y_resampled = smote.fit_resample(X, y)

print(“重采样后类别分布:”, np.bincount(y_resampled))
6.3 特征重要性分析
from sklearn.ensemble import RandomForestClassifier

# 训练随机森林
rf = RandomForestClassifier(n_estimators=100, random_state=42)
rf.fit(X_train, y_train)

# 获取特征重要性
importances = rf.feature_importances_
feature_names = numeric_features + list(preprocessor.named_transformers_[‘cat’].get_feature_names_out())

print(“特征重要性:”)
for name, importance in zip(feature_names, importances):
print(f”{name}: {importance:.4f}”)
七、实战案例:端到端数据预处理流程
7.1 完整案例:泰坦尼克号生存预测
import seaborn as sns
from sklearn.model_selection import cross_val_score
from sklearn.ensemble import RandomForestClassifier

# 加载数据
titanic = sns.load_dataset(‘titanic’)
print(“数据形状:”, titanic.shape)
print(“缺失值统计:”)
print(titanic.isnull().sum())

# 定义预处理函数
def preprocess_titanic(data):
# 复制数据
df = data.copy()

# 填充缺失值
df[‘age’] = df[‘age’].fillna(df[‘age’].median())
df[’embarked’] = df[’embarked’].fillna(df[’embarked’].mode()[0])
df[‘fare’] = df[‘fare’].fillna(df[‘fare’].median())

# 特征工程
df[‘family_size’] = df[‘sibsp’] + df[‘parch’] + 1
df[‘is_alone’] = (df[‘family_size’] == 1).astype(int)
df[‘title’] = df[‘name’].str.extract(‘ ([A-Za-z]+)\.’, expand=False)
df[‘title’] = df[‘title’].replace([‘Lady’, ‘Countess’,’Capt’, ‘Col’, ‘Don’,
‘Dr’, ‘Major’, ‘Rev’, ‘Sir’, ‘Jonkheer’, ‘Dona’], ‘Rare’)
df[‘title’] = df[‘title’].replace(‘Mlle’, ‘Miss’)
df[‘title’] = df[‘title’].replace(‘Ms’, ‘Miss’)
df[‘title’] = df[‘title’].replace(‘Mme’, ‘Mrs’)

# 删除不需要的列
df = df.drop([‘name’, ‘ticket’, ‘cabin’, ’embark_town’, ‘alive’], axis=1)

return df

# 预处理数据
titanic_processed = preprocess_titanic(titanic)

# 定义特征和目标
X = titanic_processed.drop(‘survived’, axis=1)
y = titanic_processed[‘survived’]

# 创建预处理管道
numeric_features = [‘age’, ‘fare’, ‘family_size’]
categorical_features = [‘sex’, ’embarked’, ‘class’, ‘who’, ‘adult_male’, ‘deck’, ’embark_town’, ‘alone’, ‘title’]

preprocessor = ColumnTransformer(
transformers=[
(‘num’, StandardScaler(), numeric_features),
(‘cat’, OneHotEncoder(handle_unknown=’ignore’), categorical_features)
])

# 完整Pipeline
pipeline = Pipeline([
(‘preprocessor’, preprocessor),
(‘classifier’, RandomForestClassifier(n_estimators=100, random_state=42))
])

# 交叉验证
scores = cross_val_score(pipeline, X, y, cv=5)
print(“交叉验证得分:”, scores.mean())
八、最佳实践与注意事项
8.1 数据泄漏问题
重要原则
:所有预处理步骤必须在训练集上拟合,然后在测试集上转换。
# 错误的做法(会导致数据泄漏)
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train) # 在训练集上拟合
X_test_scaled = scaler.transform(X_test) # 在测试集上转换

# 正确的做法:使用Pipeline自动处理
pipeline = Pipeline([
(‘scaler’, StandardScaler()),
(‘model’, LogisticRegression())
])
pipeline.fit(X_train, y_train)
pipeline.predict(X_test)
8.2 处理高基数分类变量
对于类别数量很多的分类变量,可以考虑:
# 方法1:限制类别数量
def limit_categories(X, column, max_categories=50):
top_categories = X[column].value_counts().nlargest(max_categories).index
X[column] = X[column].where(X[column].isin(top_categories), ‘Other’)
return X

# 方法2:使用频率编码
def frequency_encoding(X, column):
freq_map = X[column].value_counts().to_dict()
X[column + ‘_freq’] = X[column].map(freq_map)
return X

# 方法3:使用Hashing Trick(需要sklearn 1.3+)
from sklearn.feature_extraction import FeatureHasher
hasher = FeatureHasher(n_features=10, input_type=’string’)
8.3 内存优化
对于大数据集,可以使用稀疏矩阵:
from scipy.sparse import csr_matrix

# 使用OneHotEncoder的稀疏输出
encoder = OneHotEncoder(sparse_output=True)
X_sparse = encoder.fit_transform(X_categorical)

# 使用稀疏矩阵进行训练
from sklearn.linear_model import LogisticRegression
model = LogisticRegression(solver=’saga’, max_iter=1000)
model.fit(X_sparse, y)
8.4 保存和加载预处理器
import joblib

# 保存预处理器
joblib.dump(pipeline, ‘preprocessor_model.pkl’)

# 加载预处理器
loaded_pipeline = joblib.load(‘preprocessor_model.pkl’)
predictions = loaded_pipeline.predict(new_data)
九、总结
数据预处理是机器学习工作流中至关重要的一环。本文详细介绍了scikit-learn中的核心预处理技巧:
缺失值处理
:从简单填充到高级KNN填充,根据数据特性选择合适方法
特征编码
:独热编码、标签编码、目标编码等处理分类变量
特征缩放
:标准化、归一化、Robust Scaling等缩放技术
特征工程
:多项式特征、分箱、自定义变换
Pipeline集成
:构建端到端的预处理流水线
高级技巧
:异常值检测、数据增强、特征选择
关键要点
:
始终使用Pipeline来避免数据泄漏
根据数据分布和业务场景选择合适的预处理方法
对于分类变量,注意高基数问题
保存预处理器以确保训练和预测的一致性
通过合理应用这些预处理技巧,可以显著提升模型性能,为后续的模型训练和调优奠定坚实基础。