活动公告

系统通知
05-18 21:22
系统通知
通知:本站资源由网友上传分享,如有违规等问题请到版务模块进行投诉,资源失效请在帖子内回复要求补档,会尽快处理!
10-23 09:31

scikit-learn数据预处理与清洗方法实战指南 打造高质量数据集的完整流程

SunJu_FaceMall

3万

主题

2860

科技点

3万

积分

白金月票

碾压王

积分
32872

塔罗立华奏

<font color=白金月票" /> 发表于 2025-9-5 16:50:00 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

x
引言

在数据科学和机器学习项目中,数据预处理和清洗是构建高质量模型的关键步骤。俗话说,”垃圾进,垃圾出”(Garbage In, Garbage Out),这意味着如果输入数据质量不高,即使是最先进的算法也难以产生准确的结果。Scikit-learn作为Python中最流行的机器学习库之一,提供了丰富的数据预处理和清洗工具,帮助数据科学家和分析师高效地准备数据。

本文将详细介绍使用scikit-learn进行数据预处理和清洗的完整流程,涵盖从数据加载到最终预处理管道构建的各个环节。我们将通过实际代码示例演示各种技术,帮助读者掌握如何打造高质量的数据集。

数据加载与初步检查

在进行任何数据预处理之前,首先需要加载数据并进行初步检查,了解数据的基本情况和潜在问题。
  1. import pandas as pd
  2. import numpy as np
  3. from sklearn.datasets import fetch_openml
  4. # 加载示例数据集
  5. housing = fetch_openml(name="house_prices", as_frame=True)
  6. df = pd.DataFrame(housing.data, columns=housing.feature_names)
  7. df['SalePrice'] = housing.target
  8. # 查看数据基本信息
  9. print(f"数据集形状: {df.shape}")
  10. print("\n前5行数据:")
  11. print(df.head())
  12. # 查看数据类型和缺失值
  13. print("\n数据类型和缺失值信息:")
  14. print(df.info())
  15. # 查看数值型特征的统计摘要
  16. print("\n数值型特征统计摘要:")
  17. print(df.describe())
  18. # 检查缺失值
  19. print("\n各列缺失值数量:")
  20. missing_values = df.isnull().sum()
  21. print(missing_values[missing_values > 0])
复制代码

通过初步检查,我们可以了解数据集的大小、特征类型、缺失值情况以及数值特征的分布等基本信息。这有助于我们确定后续需要采取的预处理步骤。

缺失值处理

缺失值是数据集中常见的问题,可能由数据收集错误、数据录入遗漏或其他原因造成。处理缺失值的方法有多种,选择哪种方法取决于缺失值的数量、特征的性质以及业务背景。

删除含有缺失值的行或列

当缺失值较少或某些列缺失值过多时,可以考虑删除含有缺失值的行或列。
  1. # 删除含有缺失值的行
  2. df_drop_rows = df.dropna()
  3. # 删除含有缺失值的列(例如,缺失值超过30%的列)
  4. threshold = 0.3 * len(df)
  5. df_drop_cols = df.dropna(axis=1, thresh=threshold)
  6. print(f"原始数据集形状: {df.shape}")
  7. print(f"删除缺失行后数据集形状: {df_drop_rows.shape}")
  8. print(f"删除缺失列后数据集形状: {df_drop_cols.shape}")
复制代码

填充缺失值

填充缺失值是更常用的方法,scikit-learn提供了多种填充策略。
  1. from sklearn.impute import SimpleImputer
  2. # 数值型特征填充
  3. # 使用均值填充
  4. num_imputer_mean = SimpleImputer(strategy='mean')
  5. # 使用中位数填充
  6. num_imputer_median = SimpleImputer(strategy='median')
  7. # 使用众数填充
  8. num_imputer_most_frequent = SimpleImputer(strategy='most_frequent')
  9. # 使用固定值填充
  10. num_imputer_constant = SimpleImputer(strategy='constant', fill_value=0)
  11. # 分类特征填充
  12. # 使用众数填充
  13. cat_imputer_most_frequent = SimpleImputer(strategy='most_frequent')
  14. # 使用固定值填充
  15. cat_imputer_constant = SimpleImputer(strategy='constant', fill_value='Missing')
  16. # 示例:对数值型列使用中位数填充
  17. numeric_cols = df.select_dtypes(include=['int64', 'float64']).columns
  18. df_numeric = df[numeric_cols].copy()
  19. df_numeric_imputed = pd.DataFrame(num_imputer_median.fit_transform(df_numeric),
  20.                                  columns=numeric_cols)
  21. print("填充前缺失值数量:")
  22. print(df_numeric.isnull().sum().sum())
  23. print("\n填充后缺失值数量:")
  24. print(df_numeric_imputed.isnull().sum().sum())
复制代码

高级缺失值处理方法

对于更复杂的场景,scikit-learn提供了更高级的缺失值处理方法,如KNN插补和迭代插补。
  1. from sklearn.impute import KNNImputer, IterativeImputer
  2. # KNN插补
  3. knn_imputer = KNNImputer(n_neighbors=5)
  4. df_knn_imputed = pd.DataFrame(knn_imputer.fit_transform(df_numeric),
  5.                              columns=numeric_cols)
  6. # 迭代插补(基于回归模型)
  7. iterative_imputer = IterativeImputer(random_state=42)
  8. df_iter_imputed = pd.DataFrame(iterative_imputer.fit_transform(df_numeric),
  9.                               columns=numeric_cols)
  10. print("KNN插补后缺失值数量:", df_knn_imputed.isnull().sum().sum())
  11. print("迭代插补后缺失值数量:", df_iter_imputed.isnull().sum().sum())
复制代码

特征编码(处理分类变量)

大多数机器学习算法要求数值型输入,因此需要将分类变量转换为数值形式。scikit-learn提供了多种编码方法。

标签编码(Label Encoding)

标签编码将每个类别映射到一个整数。适用于有序分类变量。
  1. from sklearn.preprocessing import LabelEncoder
  2. # 示例:对有序分类变量进行标签编码
  3. df_ordinal = df[['ExterQual']].copy()  # 假设ExterQual是有序分类变量
  4. # 创建标签编码器
  5. le = LabelEncoder()
  6. df_ordinal['ExterQual_encoded'] = le.fit_transform(df_ordinal['ExterQual'])
  7. print("原始值与编码值的映射:")
  8. for i, category in enumerate(le.classes_):
  9.     print(f"{category}: {i}")
  10. print("\n编码结果:")
  11. print(df_ordinal.head())
复制代码

独热编码(One-Hot Encoding)

独热编码为每个类别创建一个新的二元(0/1)特征。适用于无序分类变量。
  1. from sklearn.preprocessing import OneHotEncoder
  2. # 示例:对无序分类变量进行独热编码
  3. df_nominal = df[['Neighborhood']].copy()  # 假设Neighborhood是无序分类变量
  4. # 创建独热编码器
  5. ohe = OneHotEncoder(sparse=False, handle_unknown='ignore')
  6. ohe_features = ohe.fit_transform(df_nominal[['Neighborhood']])
  7. ohe_df = pd.DataFrame(ohe_features, columns=ohe.get_feature_names_out(['Neighborhood']))
  8. print("独热编码结果:")
  9. print(ohe_df.head())
复制代码

目标编码(Target Encoding)

目标编码使用目标变量的统计信息(如均值)来表示分类变量。这种方法特别适用于高基数分类变量。
  1. from sklearn.preprocessing import TargetEncoder
  2. # 示例:使用目标编码
  3. df_target = df[['Neighborhood', 'SalePrice']].copy()
  4. # 创建目标编码器
  5. te = TargetEncoder(target_type='continuous')
  6. df_target['Neighborhood_encoded'] = te.fit_transform(df_target[['Neighborhood']], df_target['SalePrice'])
  7. print("目标编码结果:")
  8. print(df_target[['Neighborhood', 'Neighborhood_encoded']].drop_duplicates().head())
复制代码

二进制编码(Binary Encoding)

二进制编码是一种介于独热编码和哈希编码之间的方法,它首先将类别转换为整数,然后将这些整数表示为二进制形式。
  1. from category_encoders import BinaryEncoder
  2. # 示例:使用二进制编码
  3. df_binary = df[['Neighborhood']].copy()
  4. # 创建二进制编码器
  5. be = BinaryEncoder()
  6. df_binary_encoded = be.fit_transform(df_binary['Neighborhood'])
  7. print("二进制编码结果:")
  8. print(df_binary_encoded.head())
复制代码

特征缩放

特征缩放是确保不同特征具有相似尺度的重要预处理步骤,这对于许多机器学习算法(如SVM、KNN、神经网络等)的性能至关重要。

标准化(Standardization)

标准化将特征缩放为均值为0,标准差为1的分布。
  1. from sklearn.preprocessing import StandardScaler
  2. # 示例:对数值型特征进行标准化
  3. numeric_cols = df.select_dtypes(include=['int64', 'float64']).columns
  4. df_numeric = df[numeric_cols].copy()
  5. # 创建标准化器
  6. scaler = StandardScaler()
  7. df_scaled = pd.DataFrame(scaler.fit_transform(df_numeric), columns=numeric_cols)
  8. print("标准化前统计信息:")
  9. print(df_numeric.describe().loc[['mean', 'std']])
  10. print("\n标准化后统计信息:")
  11. print(df_scaled.describe().loc[['mean', 'std']])
复制代码

归一化(Normalization)

归一化将特征缩放到一个指定的范围,通常是[0, 1]。
  1. from sklearn.preprocessing import MinMaxScaler
  2. # 示例:对数值型特征进行归一化
  3. # 创建归一化器
  4. min_max_scaler = MinMaxScaler()
  5. df_normalized = pd.DataFrame(min_max_scaler.fit_transform(df_numeric), columns=numeric_cols)
  6. print("归一化前统计信息:")
  7. print(df_numeric.describe().loc[['min', 'max']])
  8. print("\n归一化后统计信息:")
  9. print(df_normalized.describe().loc[['min', 'max']])
复制代码

鲁棒缩放(Robust Scaling)

鲁棒缩放使用中位数和四分位数范围进行缩放,对异常值不敏感。
  1. from sklearn.preprocessing import RobustScaler
  2. # 示例:对数值型特征进行鲁棒缩放
  3. # 创建鲁棒缩放器
  4. robust_scaler = RobustScaler()
  5. df_robust_scaled = pd.DataFrame(robust_scaler.fit_transform(df_numeric), columns=numeric_cols)
  6. print("鲁棒缩放前统计信息:")
  7. print(df_numeric.describe().loc[['25%', '50%', '75%']])
  8. print("\n鲁棒缩放后统计信息:")
  9. print(df_robust_scaled.describe().loc[['25%', '50%', '75%']])
复制代码

异常值检测与处理

异常值是显著偏离其他观测值的数据点,可能会影响模型的性能。检测和处理异常值是数据预处理的重要环节。

基于统计方法的异常值检测
  1. # 基于Z-score的异常值检测
  2. from scipy import stats
  3. def detect_outliers_zscore(df, column, threshold=3):
  4.     z_scores = np.abs(stats.zscore(df[column].dropna()))
  5.     outliers = df[column][z_scores > threshold]
  6.     return outliers
  7. # 示例:检测SalePrice列的异常值
  8. outliers_zscore = detect_outliers_zscore(df, 'SalePrice')
  9. print(f"基于Z-score检测到的异常值数量: {len(outliers_zscore)}")
  10. # 基于IQR的异常值检测
  11. def detect_outliers_iqr(df, column):
  12.     Q1 = df[column].quantile(0.25)
  13.     Q3 = df[column].quantile(0.75)
  14.     IQR = Q3 - Q1
  15.     lower_bound = Q1 - 1.5 * IQR
  16.     upper_bound = Q3 + 1.5 * IQR
  17.     outliers = df[(df[column] < lower_bound) | (df[column] > upper_bound)][column]
  18.     return outliers
  19. # 示例:检测SalePrice列的异常值
  20. outliers_iqr = detect_outliers_iqr(df, 'SalePrice')
  21. print(f"基于IQR检测到的异常值数量: {len(outliers_iqr)}")
复制代码

基于机器学习方法的异常值检测
  1. from sklearn.ensemble import IsolationForest
  2. from sklearn.neighbors import LocalOutlierFactor
  3. from sklearn.svm import OneClassSVM
  4. # 准备数据(仅使用数值型列)
  5. numeric_cols = df.select_dtypes(include=['int64', 'float64']).columns
  6. df_numeric = df[numeric_cols].copy()
  7. df_numeric = df_numeric.dropna()  # 移除缺失值
  8. # Isolation Forest
  9. iso_forest = IsolationForest(contamination=0.05, random_state=42)
  10. outliers_iso = iso_forest.fit_predict(df_numeric)
  11. print(f"Isolation Forest检测到的异常值数量: {sum(outliers_iso == -1)}")
  12. # Local Outlier Factor
  13. lof = LocalOutlierFactor(n_neighbors=20, contamination=0.05)
  14. outliers_lof = lof.fit_predict(df_numeric)
  15. print(f"LOF检测到的异常值数量: {sum(outliers_lof == -1)}")
  16. # One-Class SVM
  17. oc_svm = OneClassSVM(nu=0.05)
  18. outliers_svm = oc_svm.fit_predict(df_numeric)
  19. print(f"One-Class SVM检测到的异常值数量: {sum(outliers_svm == -1)}")
复制代码

异常值处理方法
  1. # 删除异常值
  2. def remove_outliers_iqr(df, column):
  3.     Q1 = df[column].quantile(0.25)
  4.     Q3 = df[column].quantile(0.75)
  5.     IQR = Q3 - Q1
  6.     lower_bound = Q1 - 1.5 * IQR
  7.     upper_bound = Q3 + 1.5 * IQR
  8.     df_clean = df[(df[column] >= lower_bound) & (df[column] <= upper_bound)]
  9.     return df_clean
  10. # 示例:删除SalePrice列的异常值
  11. df_clean = remove_outliers_iqr(df.copy(), 'SalePrice')
  12. print(f"删除异常值前数据集大小: {df.shape}")
  13. print(f"删除异常值后数据集大小: {df_clean.shape}")
  14. # 替换异常值
  15. def replace_outliers_with_median(df, column):
  16.     Q1 = df[column].quantile(0.25)
  17.     Q3 = df[column].quantile(0.75)
  18.     IQR = Q3 - Q1
  19.     lower_bound = Q1 - 1.5 * IQR
  20.     upper_bound = Q3 + 1.5 * IQR
  21.     median = df[column].median()
  22.     df[column] = np.where((df[column] < lower_bound) | (df[column] > upper_bound), median, df[column])
  23.     return df
  24. # 示例:用中位数替换SalePrice列的异常值
  25. df_replaced = replace_outliers_with_median(df.copy(), 'SalePrice')
  26. # 比较替换前后的分布
  27. print("\n替换前的统计信息:")
  28. print(df['SalePrice'].describe())
  29. print("\n替换后的统计信息:")
  30. print(df_replaced['SalePrice'].describe())
复制代码

特征转换

特征转换可以改变特征的分布,使其更适合特定的机器学习算法。

对数转换

对数转换可以处理右偏分布的数据,使其更接近正态分布。
  1. import matplotlib.pyplot as plt
  2. import seaborn as sns
  3. # 示例:对SalePrice进行对数转换
  4. df_log = df.copy()
  5. df_log['SalePrice_log'] = np.log1p(df_log['SalePrice'])  # 使用log1p避免log(0)的问题
  6. # 可视化转换前后的分布
  7. fig, axes = plt.subplots(1, 2, figsize=(15, 5))
  8. sns.histplot(df['SalePrice'], kde=True, ax=axes[0])
  9. axes[0].set_title('原始SalePrice分布')
  10. sns.histplot(df_log['SalePrice_log'], kde=True, ax=axes[1])
  11. axes[1].set_title('对数转换后SalePrice分布')
  12. plt.tight_layout()
  13. plt.show()
复制代码

Box-Cox转换

Box-Cox转换是一系列幂转换,可以使数据更接近正态分布。
  1. from sklearn.preprocessing import PowerTransformer
  2. # 示例:对SalePrice进行Box-Cox转换
  3. df_boxcox = df.copy()
  4. # Box-Cox转换要求所有值必须为正数
  5. # 如果数据中有0或负数,可以使用Yeo-Johnson转换
  6. pt = PowerTransformer(method='box-cox')
  7. sale_prices = df_boxcox[['SalePrice']].values
  8. df_boxcox['SalePrice_boxcox'] = pt.fit_transform(sale_prices)
  9. # 可视化转换前后的分布
  10. fig, axes = plt.subplots(1, 2, figsize=(15, 5))
  11. sns.histplot(df['SalePrice'], kde=True, ax=axes[0])
  12. axes[0].set_title('原始SalePrice分布')
  13. sns.histplot(df_boxcox['SalePrice_boxcox'], kde=True, ax=axes[1])
  14. axes[1].set_title('Box-Cox转换后SalePrice分布')
  15. plt.tight_layout()
  16. plt.show()
复制代码

多项式特征

多项式特征可以创建特征的非线性组合,帮助模型捕捉特征间的非线性关系。
  1. from sklearn.preprocessing import PolynomialFeatures
  2. # 示例:创建多项式特征
  3. df_poly = df.copy()
  4. # 选择几个数值型特征
  5. selected_features = ['OverallQual', 'GrLivArea', 'GarageArea']
  6. df_selected = df_poly[selected_features].dropna()
  7. # 创建二次多项式特征
  8. poly = PolynomialFeatures(degree=2, include_bias=False)
  9. poly_features = poly.fit_transform(df_selected)
  10. poly_feature_names = poly.get_feature_names_out(selected_features)
  11. df_poly_features = pd.DataFrame(poly_features, columns=poly_feature_names)
  12. print("原始特征:")
  13. print(df_selected.head())
  14. print("\n多项式特征:")
  15. print(df_poly_features.head())
复制代码

分箱(Binning)

分箱将连续变量转换为离散类别,可以帮助处理非线性关系和异常值。
  1. from sklearn.preprocessing import KBinsDiscretizer
  2. # 示例:对YearBuilt进行分箱
  3. df_binned = df.copy()
  4. # 创建分箱器
  5. kbd = KBinsDiscretizer(n_bins=5, encode='ordinal', strategy='quantile')
  6. year_built = df_binned[['YearBuilt']].values
  7. df_binned['YearBuilt_binned'] = kbd.fit_transform(year_built)
  8. # 查看分箱结果
  9. print("分箱边界:")
  10. print(kbd.bin_edges_)
  11. print("\n分箱结果示例:")
  12. print(df_binned[['YearBuilt', 'YearBuilt_binned']].head(10))
  13. # 可视化分箱结果
  14. plt.figure(figsize=(10, 6))
  15. sns.countplot(x='YearBuilt_binned', data=df_binned)
  16. plt.title('YearBuilt分箱结果')
  17. plt.show()
复制代码

特征选择

特征选择是选择最相关特征子集的过程,可以减少模型复杂度,提高模型性能,并减少训练时间。

基于统计量的特征选择
  1. from sklearn.feature_selection import SelectKBest, f_regression, chi2, mutual_info_regression
  2. # 准备数据(仅使用数值型列)
  3. numeric_cols = df.select_dtypes(include=['int64', 'float64']).columns
  4. df_numeric = df[numeric_cols].copy()
  5. df_numeric = df_numeric.dropna()
  6. X = df_numeric.drop('SalePrice', axis=1)
  7. y = df_numeric['SalePrice']
  8. # 基于F检验的特征选择
  9. selector_f = SelectKBest(score_func=f_regression, k=10)
  10. X_f_selected = selector_f.fit_transform(X, y)
  11. f_selected_features = X.columns[selector_f.get_support()]
  12. print("基于F检验选择的Top 10特征:")
  13. print(f_selected_features)
  14. # 基于互信息的特征选择
  15. selector_mi = SelectKBest(score_func=mutual_info_regression, k=10)
  16. X_mi_selected = selector_mi.fit_transform(X, y)
  17. mi_selected_features = X.columns[selector_mi.get_support()]
  18. print("\n基于互信息选择的Top 10特征:")
  19. print(mi_selected_features)
复制代码

基于模型的特征选择
  1. from sklearn.feature_selection import SelectFromModel
  2. from sklearn.linear_model import Lasso, Ridge
  3. from sklearn.ensemble import RandomForestRegressor
  4. # 基于Lasso的特征选择
  5. lasso = Lasso(alpha=0.01)
  6. selector_lasso = SelectFromModel(lasso)
  7. selector_lasso.fit(X, y)
  8. lasso_selected_features = X.columns[selector_lasso.get_support()]
  9. print("基于Lasso选择的特征:")
  10. print(lasso_selected_features)
  11. # 基于随机森林的特征选择
  12. rf = RandomForestRegressor(n_estimators=100, random_state=42)
  13. selector_rf = SelectFromModel(rf, threshold='median')
  14. selector_rf.fit(X, y)
  15. rf_selected_features = X.columns[selector_rf.get_support()]
  16. print("\n基于随机森林选择的特征:")
  17. print(rf_selected_features)
  18. # 可视化特征重要性
  19. rf.fit(X, y)
  20. importances = rf.feature_importances_
  21. indices = np.argsort(importances)[::-1]
  22. plt.figure(figsize=(12, 8))
  23. plt.title('特征重要性')
  24. plt.bar(range(X.shape[1]), importances[indices], align='center')
  25. plt.xticks(range(X.shape[1]), X.columns[indices], rotation=90)
  26. plt.tight_layout()
  27. plt.show()
复制代码

递归特征消除(RFE)
  1. from sklearn.feature_selection import RFE
  2. from sklearn.linear_model import LinearRegression
  3. # 递归特征消除
  4. estimator = LinearRegression()
  5. selector_rfe = RFE(estimator, n_features_to_select=10, step=1)
  6. selector_rfe = selector_rfe.fit(X, y)
  7. rfe_selected_features = X.columns[selector_rfe.support_]
  8. print("递归特征消除选择的Top 10特征:")
  9. print(rfe_selected_features)
  10. # 可视化特征排名
  11. rfe_ranking = pd.DataFrame({
  12.     'Feature': X.columns,
  13.     'Ranking': selector_rfe.ranking_
  14. }).sort_values('Ranking')
  15. print("\n特征排名:")
  16. print(rfe_ranking)
复制代码

数据预处理管道构建

将所有预处理步骤组合到一个管道中可以简化代码,避免数据泄露,并使模型部署更加容易。

创建预处理管道
  1. from sklearn.compose import ColumnTransformer
  2. from sklearn.pipeline import Pipeline
  3. from sklearn.model_selection import train_test_split
  4. # 准备数据
  5. df_processed = df.copy()
  6. # 分离特征和目标变量
  7. X = df_processed.drop('SalePrice', axis=1)
  8. y = df_processed['SalePrice']
  9. # 分割训练集和测试集
  10. X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
  11. # 识别数值型和分类型特征
  12. numeric_features = X.select_dtypes(include=['int64', 'float64']).columns
  13. categorical_features = X.select_dtypes(include=['object']).columns
  14. # 创建数值型特征的预处理管道
  15. numeric_transformer = Pipeline(steps=[
  16.     ('imputer', SimpleImputer(strategy='median')),
  17.     ('scaler', StandardScaler())
  18. ])
  19. # 创建分类型特征的预处理管道
  20. categorical_transformer = Pipeline(steps=[
  21.     ('imputer', SimpleImputer(strategy='most_frequent')),
  22.     ('onehot', OneHotEncoder(handle_unknown='ignore'))
  23. ])
  24. # 创建列转换器
  25. preprocessor = ColumnTransformer(
  26.     transformers=[
  27.         ('num', numeric_transformer, numeric_features),
  28.         ('cat', categorical_transformer, categorical_features)
  29.     ])
  30. # 应用预处理
  31. X_train_processed = preprocessor.fit_transform(X_train)
  32. X_test_processed = preprocessor.transform(X_test)
  33. print("预处理后的训练集形状:", X_train_processed.shape)
  34. print("预处理后的测试集形状:", X_test_processed.shape)
复制代码

将预处理与模型训练结合
  1. from sklearn.linear_model import LinearRegression
  2. from sklearn.ensemble import RandomForestRegressor
  3. from sklearn.metrics import mean_squared_error, r2_score
  4. # 创建完整的管道(预处理+模型)
  5. # 线性回归管道
  6. lr_pipeline = Pipeline(steps=[
  7.     ('preprocessor', preprocessor),
  8.     ('regressor', LinearRegression())
  9. ])
  10. # 随机森林管道
  11. rf_pipeline = Pipeline(steps=[
  12.     ('preprocessor', preprocessor),
  13.     ('regressor', RandomForestRegressor(n_estimators=100, random_state=42))
  14. ])
  15. # 训练模型
  16. lr_pipeline.fit(X_train, y_train)
  17. rf_pipeline.fit(X_train, y_train)
  18. # 评估模型
  19. def evaluate_model(pipeline, X_test, y_test):
  20.     y_pred = pipeline.predict(X_test)
  21.     mse = mean_squared_error(y_test, y_pred)
  22.     rmse = np.sqrt(mse)
  23.     r2 = r2_score(y_test, y_pred)
  24.     return {'MSE': mse, 'RMSE': rmse, 'R2': r2}
  25. lr_metrics = evaluate_model(lr_pipeline, X_test, y_test)
  26. rf_metrics = evaluate_model(rf_pipeline, X_test, y_test)
  27. print("线性回归模型性能:")
  28. print(lr_metrics)
  29. print("\n随机森林模型性能:")
  30. print(rf_metrics)
复制代码

保存和加载预处理管道
  1. import joblib
  2. # 保存管道
  3. joblib.dump(rf_pipeline, 'rf_pipeline.pkl')
  4. # 加载管道
  5. loaded_pipeline = joblib.load('rf_pipeline.pkl')
  6. # 使用加载的管道进行预测
  7. y_pred_loaded = loaded_pipeline.predict(X_test)
  8. mse_loaded = mean_squared_error(y_test, y_pred_loaded)
  9. print(f"使用加载的管道预测的MSE: {mse_loaded}")
复制代码

实战案例:端到端的数据预处理流程

让我们通过一个完整的案例来演示如何应用上述所有技术来处理真实数据集。
  1. # 加载数据集
  2. from sklearn.datasets import fetch_openml
  3. # 加载Ames Housing数据集
  4. housing = fetch_openml(name="house_prices", as_frame=True, parser='auto')
  5. df = pd.DataFrame(housing.data, columns=housing.feature_names)
  6. df['SalePrice'] = housing.target
  7. # 1. 数据初步检查
  8. print("数据集形状:", df.shape)
  9. print("\n数据类型:")
  10. print(df.dtypes.value_counts())
  11. # 检查缺失值
  12. missing_values = df.isnull().sum()
  13. missing_pct = (missing_values / len(df)) * 100
  14. missing_info = pd.DataFrame({
  15.     'Missing Values': missing_values,
  16.     'Percentage': missing_pct
  17. }).sort_values('Missing Values', ascending=False)
  18. print("\n缺失值信息 (Top 10):")
  19. print(missing_info.head(10))
  20. # 2. 处理缺失值
  21. # 删除缺失值超过80%的列
  22. cols_to_drop = missing_info[missing_info['Percentage'] > 80].index
  23. df = df.drop(columns=cols_to_drop)
  24. print(f"\n删除了 {len(cols_to_drop)} 个缺失值过多的列")
  25. # 分离数值型和分类型特征
  26. numeric_features = df.select_dtypes(include=['int64', 'float64']).columns.drop('SalePrice')
  27. categorical_features = df.select_dtypes(include=['object']).columns
  28. # 3. 异常值检测与处理
  29. # 使用IQR方法检测SalePrice的异常值
  30. Q1 = df['SalePrice'].quantile(0.25)
  31. Q3 = df['SalePrice'].quantile(0.75)
  32. IQR = Q3 - Q1
  33. lower_bound = Q1 - 1.5 * IQR
  34. upper_bound = Q3 + 1.5 * IQR
  35. # 标记异常值但不删除,因为我们将在后续步骤中处理
  36. df['Price_Outlier'] = ((df['SalePrice'] < lower_bound) | (df['SalePrice'] > upper_bound)).astype(int)
  37. print(f"\n检测到 {df['Price_Outlier'].sum()} 个价格异常值")
  38. # 4. 特征工程
  39. # 创建一些新特征
  40. df['TotalSF'] = df['TotalBsmtSF'] + df['1stFlrSF'] + df['2ndFlrSF']
  41. df['TotalBathrooms'] = df['FullBath'] + 0.5 * df['HalfBath'] + df['BsmtFullBath'] + 0.5 * df['BsmtHalfBath']
  42. df['YrSinceRemodel'] = df['YrSold'] - df['YearRemodAdd']
  43. # 5. 数据分割
  44. X = df.drop('SalePrice', axis=1)
  45. y = df['SalePrice']
  46. X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
  47. # 6. 构建预处理管道
  48. # 更新数值型和分类型特征列表
  49. numeric_features = X_train.select_dtypes(include=['int64', 'float64']).columns
  50. categorical_features = X_train.select_dtypes(include=['object']).columns
  51. # 数值型特征处理管道
  52. numeric_transformer = Pipeline(steps=[
  53.     ('imputer', SimpleImputer(strategy='median')),
  54.     ('scaler', RobustScaler())  # 使用RobustScaler处理异常值
  55. ])
  56. # 分类型特征处理管道
  57. categorical_transformer = Pipeline(steps=[
  58.     ('imputer', SimpleImputer(strategy='most_frequent')),
  59.     ('onehot', OneHotEncoder(handle_unknown='ignore', sparse_output=False))
  60. ])
  61. # 列转换器
  62. preprocessor = ColumnTransformer(
  63.     transformers=[
  64.         ('num', numeric_transformer, numeric_features),
  65.         ('cat', categorical_transformer, categorical_features)
  66.     ])
  67. # 7. 特征选择
  68. # 使用随机森林进行特征选择
  69. feature_selector = Pipeline(steps=[
  70.     ('preprocessor', preprocessor),
  71.     ('feature_selection', SelectFromModel(RandomForestRegressor(n_estimators=100, random_state=42), threshold='median'))
  72. ])
  73. # 8. 模型训练与评估
  74. # 创建完整管道
  75. model_pipeline = Pipeline(steps=[
  76.     ('preprocessor', preprocessor),
  77.     ('feature_selection', SelectFromModel(RandomForestRegressor(n_estimators=100, random_state=42), threshold='median')),
  78.     ('regressor', RandomForestRegressor(n_estimators=200, random_state=42))
  79. ])
  80. # 训练模型
  81. model_pipeline.fit(X_train, y_train)
  82. # 评估模型
  83. y_pred = model_pipeline.predict(X_test)
  84. mse = mean_squared_error(y_test, y_pred)
  85. rmse = np.sqrt(mse)
  86. r2 = r2_score(y_test, y_pred)
  87. print("\n模型性能:")
  88. print(f"MSE: {mse:.2f}")
  89. print(f"RMSE: {rmse:.2f}")
  90. print(f"R2: {r2:.2f}")
  91. # 9. 可视化预测结果
  92. plt.figure(figsize=(10, 6))
  93. plt.scatter(y_test, y_pred, alpha=0.5)
  94. plt.plot([y_test.min(), y_test.max()], [y_test.min(), y_test.max()], 'r--')
  95. plt.xlabel('Actual Price')
  96. plt.ylabel('Predicted Price')
  97. plt.title('Actual vs Predicted Prices')
  98. plt.show()
  99. # 10. 保存模型
  100. joblib.dump(model_pipeline, 'ames_housing_model.pkl')
  101. print("\n模型已保存为 'ames_housing_model.pkl'")
复制代码

总结与最佳实践

数据预处理和清洗是机器学习项目成功的关键。通过本文,我们详细介绍了使用scikit-learn进行数据预处理和清洗的完整流程,包括:

1. 数据加载与初步检查:了解数据的基本情况,识别潜在问题。
2. 缺失值处理:使用删除、填充或高级插补方法处理缺失值。
3. 特征编码:将分类变量转换为数值形式,包括标签编码、独热编码、目标编码等。
4. 特征缩放:确保不同特征具有相似尺度,包括标准化、归一化和鲁棒缩放。
5. 异常值检测与处理:识别并处理异常值,包括基于统计和机器学习的方法。
6. 特征转换:改变特征分布,使其更适合模型,包括对数转换、Box-Cox转换、多项式特征和分箱。
7. 特征选择:选择最相关的特征子集,提高模型性能。
8. 数据预处理管道构建:将所有预处理步骤组合到一个管道中,简化代码并避免数据泄露。

最佳实践

1. 始终分割数据:在应用任何预处理技术之前,先将数据分割为训练集和测试集,以避免数据泄露。
2. 使用管道:将预处理步骤和模型训练组合到管道中,确保一致的预处理和简化部署。
3. 了解数据:在应用任何技术之前,先深入了解数据的特性、分布和业务背景。
4. 迭代处理:数据预处理是一个迭代过程,可能需要多次尝试不同的方法和技术。
5. 文档记录:记录所有预处理步骤和决策,以便重现结果和团队协作。
6. 考虑计算效率:对于大型数据集,考虑预处理步骤的计算效率,可能需要采样或分布式处理。
7. 处理类别不平衡:如果目标变量存在类别不平衡问题,考虑使用过采样、欠采样或类别权重等方法。
8. 特征工程:不要仅限于原始特征,尝试创建有意义的组合特征或转换特征。
9. 验证预处理效果:在应用预处理后,验证其对模型性能的影响。
10. 保持一致性:确保训练集和测试集应用相同的预处理步骤。

通过遵循这些最佳实践和使用scikit-learn提供的强大工具,您可以有效地预处理和清洗数据,为机器学习模型构建高质量的数据集,从而提高模型的性能和可靠性。
「七転び八起き(ななころびやおき)」
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则