活动公告

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

scikit-learn模型评估与预测实战指南从基础指标到高级技巧全面掌握机器学习核心技能

SunJu_FaceMall

3万

主题

2860

科技点

3万

积分

白金月票

碾压王

积分
32872

塔罗立华奏

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

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

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

x
引言

在机器学习项目中,模型评估与预测是至关重要的环节。它们帮助我们了解模型的性能、选择最佳模型、调整超参数以及最终将模型应用于实际场景。scikit-learn作为Python中最流行的机器学习库之一,提供了丰富的工具和函数来支持模型评估与预测的全过程。本文将带你从基础指标到高级技巧,全面掌握使用scikit-learn进行模型评估与预测的核心技能。

1. 基础评估指标

1.1 分类问题评估指标

准确率是最直观的分类评估指标,表示正确预测的样本数占总样本数的比例。
  1. from sklearn.metrics import accuracy_score
  2. from sklearn.datasets import make_classification
  3. from sklearn.model_selection import train_test_split
  4. from sklearn.linear_model import LogisticRegression
  5. # 生成模拟数据
  6. X, y = make_classification(n_samples=1000, n_classes=2, random_state=42)
  7. X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
  8. # 训练模型
  9. model = LogisticRegression()
  10. model.fit(X_train, y_train)
  11. # 预测
  12. y_pred = model.predict(X_test)
  13. # 计算准确率
  14. accuracy = accuracy_score(y_test, y_pred)
  15. print(f"准确率: {accuracy:.4f}")
复制代码

精确率是指被正确预测为正例的样本数占所有被预测为正例的样本数的比例。召回率是指被正确预测为正例的样本数占所有实际为正例的样本数的比例。
  1. from sklearn.metrics import precision_score, recall_score
  2. # 计算精确率和召回率
  3. precision = precision_score(y_test, y_pred)
  4. recall = recall_score(y_test, y_pred)
  5. print(f"精确率: {precision:.4f}")
  6. print(f"召回率: {recall:.4f}")
复制代码

F1分数是精确率和召回率的调和平均值,是综合评估模型性能的指标。
  1. from sklearn.metrics import f1_score
  2. # 计算F1分数
  3. f1 = f1_score(y_test, y_pred)
  4. print(f"F1分数: {f1:.4f}")
复制代码

scikit-learn提供了classification_report函数,可以一次性输出多个分类指标。
  1. from sklearn.metrics import classification_report
  2. # 生成分类报告
  3. report = classification_report(y_test, y_pred)
  4. print("分类报告:")
  5. print(report)
复制代码

1.2 回归问题评估指标

MAE是预测值与真实值之差的绝对值的平均值。
  1. from sklearn.datasets import make_regression
  2. from sklearn.linear_model import LinearRegression
  3. from sklearn.metrics import mean_absolute_error
  4. # 生成模拟数据
  5. X, y = make_regression(n_samples=1000, n_features=10, noise=0.1, random_state=42)
  6. X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
  7. # 训练模型
  8. model = LinearRegression()
  9. model.fit(X_train, y_train)
  10. # 预测
  11. y_pred = model.predict(X_test)
  12. # 计算MAE
  13. mae = mean_absolute_error(y_test, y_pred)
  14. print(f"平均绝对误差 (MAE): {mae:.4f}")
复制代码

MSE是预测值与真实值之差的平方的平均值,RMSE是MSE的平方根。
  1. from sklearn.metrics import mean_squared_error
  2. # 计算MSE
  3. mse = mean_squared_error(y_test, y_pred)
  4. print(f"均方误差 (MSE): {mse:.4f}")
  5. # 计算RMSE
  6. rmse = mean_squared_error(y_test, y_pred, squared=False)
  7. print(f"均方根误差 (RMSE): {rmse:.4f}")
复制代码

R²分数表示模型对数据方差的解释程度,范围通常在0到1之间,越接近1表示模型拟合效果越好。
  1. from sklearn.metrics import r2_score
  2. # 计算R²分数
  3. r2 = r2_score(y_test, y_pred)
  4. print(f"决定系数 (R²): {r2:.4f}")
复制代码

2. 高级评估指标与技术

2.1 混淆矩阵 (Confusion Matrix)

混淆矩阵提供了更详细的分类结果展示,包括真正例(TP)、假正例(FP)、假反例(FN)和真反例(TN)。
  1. import matplotlib.pyplot as plt
  2. from sklearn.metrics import confusion_matrix, ConfusionMatrixDisplay
  3. # 计算混淆矩阵
  4. cm = confusion_matrix(y_test, y_pred)
  5. # 可视化混淆矩阵
  6. disp = ConfusionMatrixDisplay(confusion_matrix=cm, display_labels=model.classes_)
  7. disp.plot(cmap=plt.cm.Blues)
  8. plt.title('混淆矩阵')
  9. plt.show()
复制代码

2.2 ROC曲线和AUC值

ROC曲线展示了在不同阈值下模型的真正例率(TPR)和假正例率(FPR)之间的关系,AUC值表示ROC曲线下的面积,用于评估模型的整体性能。
  1. from sklearn.metrics import roc_curve, auc, RocCurveDisplay
  2. # 获取预测概率
  3. y_prob = model.predict_proba(X_test)[:, 1]
  4. # 计算ROC曲线
  5. fpr, tpr, thresholds = roc_curve(y_test, y_prob)
  6. roc_auc = auc(fpr, tpr)
  7. # 可视化ROC曲线
  8. display = RocCurveDisplay(fpr=fpr, tpr=tpr, roc_auc=roc_auc, estimator_name='Logistic Regression')
  9. display.plot()
  10. plt.title('ROC曲线')
  11. plt.show()
  12. print(f"AUC值: {roc_auc:.4f}")
复制代码

2.3 精确率-召回率曲线

精确率-召回率曲线展示了精确率和召回率之间的权衡关系,特别适用于类别不平衡的数据集。
  1. from sklearn.metrics import precision_recall_curve, average_precision_score, PrecisionRecallDisplay
  2. # 计算精确率-召回率曲线
  3. precision, recall, _ = precision_recall_curve(y_test, y_prob)
  4. average_precision = average_precision_score(y_test, y_prob)
  5. # 可视化精确率-召回率曲线
  6. display = PrecisionRecallDisplay(precision=precision, recall=recall, average_precision=average_precision)
  7. display.plot()
  8. plt.title('精确率-召回率曲线')
  9. plt.show()
  10. print(f"平均精确率: {average_precision:.4f}")
复制代码

2.4 学习曲线 (Learning Curve)

学习曲线展示了模型性能随训练集大小变化的情况,有助于判断模型是否过拟合或欠拟合。
  1. import numpy as np
  2. from sklearn.model_selection import learning_curve
  3. def plot_learning_curve(estimator, title, X, y, cv=None, n_jobs=None, train_sizes=np.linspace(.1, 1.0, 5)):
  4.     plt.figure()
  5.     plt.title(title)
  6.     plt.xlabel("训练样本数")
  7.     plt.ylabel("得分")
  8.    
  9.     train_sizes, train_scores, test_scores = learning_curve(
  10.         estimator, X, y, cv=cv, n_jobs=n_jobs, train_sizes=train_sizes)
  11.    
  12.     train_scores_mean = np.mean(train_scores, axis=1)
  13.     train_scores_std = np.std(train_scores, axis=1)
  14.     test_scores_mean = np.mean(test_scores, axis=1)
  15.     test_scores_std = np.std(test_scores, axis=1)
  16.    
  17.     plt.grid()
  18.    
  19.     plt.fill_between(train_sizes, train_scores_mean - train_scores_std,
  20.                      train_scores_mean + train_scores_std, alpha=0.1,
  21.                      color="r")
  22.     plt.fill_between(train_sizes, test_scores_mean - test_scores_std,
  23.                      test_scores_mean + test_scores_std, alpha=0.1, color="g")
  24.     plt.plot(train_sizes, train_scores_mean, 'o-', color="r",
  25.              label="训练集得分")
  26.     plt.plot(train_sizes, test_scores_mean, 'o-', color="g",
  27.              label="交叉验证集得分")
  28.    
  29.     plt.legend(loc="best")
  30.     return plt
  31. # 绘制学习曲线
  32. plot_learning_curve(model, "学习曲线 (Logistic Regression)", X, y, cv=5)
  33. plt.show()
复制代码

2.5 验证曲线 (Validation Curve)

验证曲线展示了模型性能随超参数变化的情况,有助于选择最佳超参数值。
  1. from sklearn.model_selection import validation_curve
  2. def plot_validation_curve(estimator, title, X, y, param_name, param_range, cv=None, scoring=None, n_jobs=None):
  3.     train_scores, test_scores = validation_curve(
  4.         estimator, X, y, param_name=param_name, param_range=param_range,
  5.         cv=cv, scoring=scoring, n_jobs=n_jobs)
  6.    
  7.     train_scores_mean = np.mean(train_scores, axis=1)
  8.     train_scores_std = np.std(train_scores, axis=1)
  9.     test_scores_mean = np.mean(test_scores, axis=1)
  10.     test_scores_std = np.std(test_scores, axis=1)
  11.    
  12.     plt.title(title)
  13.     plt.xlabel(param_name)
  14.     plt.ylabel("得分")
  15.     plt.ylim(0.0, 1.1)
  16.     lw = 2
  17.     plt.plot(param_range, train_scores_mean, label="训练集得分", color="darkorange", lw=lw)
  18.     plt.fill_between(param_range, train_scores_mean - train_scores_std,
  19.                      train_scores_mean + train_scores_std, alpha=0.2,
  20.                      color="darkorange", lw=lw)
  21.     plt.plot(param_range, test_scores_mean, label="交叉验证集得分", color="navy", lw=lw)
  22.     plt.fill_between(param_range, test_scores_mean - test_scores_std,
  23.                      test_scores_mean + test_scores_std, alpha=0.2,
  24.                      color="navy", lw=lw)
  25.     plt.legend(loc="best")
  26.     return plt
  27. # 绘制验证曲线
  28. param_range = np.logspace(-3, 3, 7)
  29. plot_validation_curve(model, "验证曲线 (Logistic Regression)", X, y,
  30.                      param_name="C", param_range=param_range, cv=5)
  31. plt.xscale('log')
  32. plt.show()
复制代码

3. 交叉验证技术

3.1 K折交叉验证 (K-Fold Cross-Validation)

K折交叉验证将数据集分成K个子集,每次使用K-1个子集进行训练,剩余1个子集进行验证,重复K次。
  1. from sklearn.model_selection import cross_val_score
  2. # 执行5折交叉验证
  3. cv_scores = cross_val_score(model, X, y, cv=5)
  4. print(f"交叉验证得分: {cv_scores}")
  5. print(f"平均交叉验证得分: {cv_scores.mean():.4f}")
  6. print(f"交叉验证得分标准差: {cv_scores.std():.4f}")
复制代码

3.2 分层K折交叉验证 (Stratified K-Fold Cross-Validation)

分层K折交叉验证确保每个折中各类别的比例与整个数据集中的比例相同,特别适用于类别不平衡的数据集。
  1. from sklearn.model_selection import StratifiedKFold
  2. # 创建分层K折交叉验证对象
  3. stratified_kfold = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
  4. # 执行分层K折交叉验证
  5. stratified_cv_scores = cross_val_score(model, X, y, cv=stratified_kfold)
  6. print(f"分层交叉验证得分: {stratified_cv_scores}")
  7. print(f"平均分层交叉验证得分: {stratified_cv_scores.mean():.4f}")
  8. print(f"分层交叉验证得分标准差: {stratified_cv_scores.std():.4f}")
复制代码

3.3 留一交叉验证 (Leave-One-Out Cross-Validation)

留一交叉验证是K折交叉验证的特例,其中K等于样本数,每次只留一个样本进行验证。
  1. from sklearn.model_selection import LeaveOneOut
  2. # 创建留一交叉验证对象
  3. loo = LeaveOneOut()
  4. # 执行留一交叉验证(注意:计算量较大,适合小数据集)
  5. # loo_scores = cross_val_score(model, X, y, cv=loo)
  6. # print(f"留一交叉验证平均得分: {loo_scores.mean():.4f}")
复制代码

3.4 时间序列交叉验证 (Time Series Split)

时间序列交叉验证专门用于时间序列数据,确保验证集始终在训练集之后。
  1. from sklearn.model_selection import TimeSeriesSplit
  2. # 创建时间序列交叉验证对象
  3. tscv = TimeSeriesSplit(n_splits=5)
  4. # 执行时间序列交叉验证
  5. ts_scores = cross_val_score(model, X, y, cv=tscv)
  6. print(f"时间序列交叉验证得分: {ts_scores}")
  7. print(f"平均时间序列交叉验证得分: {ts_scores.mean():.4f}")
复制代码

4. 超参数调优

4.1 网格搜索 (Grid Search)

网格搜索通过遍历给定的超参数组合,找到最佳超参数。
  1. from sklearn.model_selection import GridSearchCV
  2. from sklearn.svm import SVC
  3. # 定义参数网格
  4. param_grid = {
  5.     'C': [0.1, 1, 10, 100],
  6.     'gamma': [1, 0.1, 0.01, 0.001],
  7.     'kernel': ['rbf', 'linear']
  8. }
  9. # 创建SVC模型
  10. svc = SVC(probability=True)
  11. # 创建网格搜索对象
  12. grid_search = GridSearchCV(estimator=svc, param_grid=param_grid, cv=5, verbose=2, n_jobs=-1)
  13. # 执行网格搜索
  14. grid_search.fit(X_train, y_train)
  15. # 输出最佳参数和得分
  16. print(f"最佳参数: {grid_search.best_params_}")
  17. print(f"最佳交叉验证得分: {grid_search.best_score_:.4f}")
  18. # 使用最佳模型进行预测
  19. best_model = grid_search.best_estimator_
  20. y_pred = best_model.predict(X_test)
  21. print(f"测试集准确率: {accuracy_score(y_test, y_pred):.4f}")
复制代码

4.2 随机搜索 (Random Search)

随机搜索在参数空间中随机采样一定数量的参数组合,通常比网格搜索更高效。
  1. from sklearn.model_selection import RandomizedSearchCV
  2. from scipy.stats import uniform, randint
  3. # 定义参数分布
  4. param_dist = {
  5.     'C': uniform(0.1, 100),
  6.     'gamma': uniform(0.001, 1),
  7.     'kernel': ['rbf', 'linear']
  8. }
  9. # 创建随机搜索对象
  10. random_search = RandomizedSearchCV(
  11.     estimator=svc,
  12.     param_distributions=param_dist,
  13.     n_iter=20,
  14.     cv=5,
  15.     verbose=2,
  16.     n_jobs=-1,
  17.     random_state=42
  18. )
  19. # 执行随机搜索
  20. random_search.fit(X_train, y_train)
  21. # 输出最佳参数和得分
  22. print(f"最佳参数: {random_search.best_params_}")
  23. print(f"最佳交叉验证得分: {random_search.best_score_:.4f}")
  24. # 使用最佳模型进行预测
  25. best_model = random_search.best_estimator_
  26. y_pred = best_model.predict(X_test)
  27. print(f"测试集准确率: {accuracy_score(y_test, y_pred):.4f}")
复制代码

4.3 贝叶斯优化 (Bayesian Optimization)

贝叶斯优化是一种更高级的超参数调优方法,它使用贝叶斯方法来选择下一个要评估的参数组合。
  1. # 需要安装scikit-optimize: pip install scikit-optimize
  2. from skopt import BayesSearchCV
  3. from skopt.space import Real, Categorical, Integer
  4. # 定义搜索空间
  5. search_spaces = {
  6.     'C': Real(0.1, 100, prior='log-uniform'),
  7.     'gamma': Real(0.001, 1, prior='log-uniform'),
  8.     'kernel': Categorical(['rbf', 'linear'])
  9. }
  10. # 创建贝叶斯优化对象
  11. bayes_search = BayesSearchCV(
  12.     estimator=svc,
  13.     search_spaces=search_spaces,
  14.     n_iter=20,
  15.     cv=5,
  16.     verbose=2,
  17.     n_jobs=-1,
  18.     random_state=42
  19. )
  20. # 执行贝叶斯优化
  21. bayes_search.fit(X_train, y_train)
  22. # 输出最佳参数和得分
  23. print(f"最佳参数: {bayes_search.best_params_}")
  24. print(f"最佳交叉验证得分: {bayes_search.best_score_:.4f}")
  25. # 使用最佳模型进行预测
  26. best_model = bayes_search.best_estimator_
  27. y_pred = best_model.predict(X_test)
  28. print(f"测试集准确率: {accuracy_score(y_test, y_pred):.4f}")
复制代码

5. 模型预测技术

5.1 分类模型预测
  1. from sklearn.ensemble import RandomForestClassifier
  2. # 训练随机森林分类器
  3. rf_classifier = RandomForestClassifier(n_estimators=100, random_state=42)
  4. rf_classifier.fit(X_train, y_train)
  5. # 基本预测
  6. y_pred = rf_classifier.predict(X_test)
  7. print(f"前5个预测结果: {y_pred[:5]}")
复制代码
  1. # 预测概率
  2. y_prob = rf_classifier.predict_proba(X_test)
  3. print(f"前5个样本的类别概率:\n{y_prob[:5]}")
  4. # 获取正类的概率
  5. y_prob_positive = y_prob[:, 1]
  6. print(f"前5个样本的正类概率: {y_prob_positive[:5]}")
复制代码
  1. # 预测决策函数值(适用于支持决策函数的模型,如SVM)
  2. if hasattr(rf_classifier, 'decision_function'):
  3.     y_decision = rf_classifier.decision_function(X_test)
  4.     print(f"前5个样本的决策函数值: {y_decision[:5]}")
复制代码

5.2 回归模型预测
  1. from sklearn.ensemble import RandomForestRegressor
  2. # 训练随机森林回归器
  3. rf_regressor = RandomForestRegressor(n_estimators=100, random_state=42)
  4. rf_regressor.fit(X_train, y_train)
  5. # 预测
  6. y_pred = rf_regressor.predict(X_test)
  7. print(f"前5个预测结果: {y_pred[:5]}")
  8. print(f"前5个真实值: {y_test[:5]}")
复制代码

5.3 聚类模型预测
  1. from sklearn.cluster import KMeans
  2. from sklearn.datasets import make_blobs
  3. # 生成聚类数据
  4. X_blob, y_blob = make_blobs(n_samples=300, centers=4, random_state=42)
  5. # 训练KMeans聚类模型
  6. kmeans = KMeans(n_clusters=4, random_state=42)
  7. kmeans.fit(X_blob)
  8. # 预测簇标签
  9. y_cluster = kmeans.predict(X_blob)
  10. print(f"前5个样本的簇标签: {y_cluster[:5]}")
  11. # 获取簇中心
  12. centers = kmeans.cluster_centers_
  13. print(f"簇中心坐标:\n{centers}")
复制代码

6. 模型持久化

6.1 使用pickle保存和加载模型
  1. import pickle
  2. # 保存模型到文件
  3. with open('model.pkl', 'wb') as file:
  4.     pickle.dump(rf_classifier, file)
  5. # 从文件加载模型
  6. with open('model.pkl', 'rb') as file:
  7.     loaded_model = pickle.load(file)
  8. # 使用加载的模型进行预测
  9. y_pred_loaded = loaded_model.predict(X_test)
  10. print(f"使用加载模型的前5个预测结果: {y_pred_loaded[:5]}")
复制代码

6.2 使用joblib保存和加载模型
  1. from joblib import dump, load
  2. # 保存模型到文件
  3. dump(rf_classifier, 'model.joblib')
  4. # 从文件加载模型
  5. loaded_model = load('model.joblib')
  6. # 使用加载的模型进行预测
  7. y_pred_loaded = loaded_model.predict(X_test)
  8. print(f"使用加载模型的前5个预测结果: {y_pred_loaded[:5]}")
复制代码

7. 实战案例:使用真实数据集进行模型评估与预测

7.1 数据准备与探索
  1. import pandas as pd
  2. from sklearn.datasets import load_breast_cancer
  3. # 加载乳腺癌数据集
  4. cancer = load_breast_cancer()
  5. X = pd.DataFrame(cancer.data, columns=cancer.feature_names)
  6. y = pd.Series(cancer.target)
  7. # 查看数据基本信息
  8. print(f"数据形状: {X.shape}")
  9. print(f"特征名称: {X.columns.tolist()}")
  10. print(f"目标类别: {cancer.target_names}")
  11. print(f"类别分布:\n{y.value_counts()}")
  12. # 查看数据统计信息
  13. print("\n数据统计信息:")
  14. print(X.describe())
  15. # 划分训练集和测试集
  16. X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42, stratify=y)
复制代码

7.2 数据预处理
  1. from sklearn.preprocessing import StandardScaler
  2. from sklearn.pipeline import Pipeline
  3. # 创建预处理管道
  4. preprocessor = Pipeline([
  5.     ('scaler', StandardScaler())
  6. ])
  7. # 预处理训练数据
  8. X_train_processed = preprocessor.fit_transform(X_train)
  9. # 预处理测试数据
  10. X_test_processed = preprocessor.transform(X_test)
复制代码

7.3 模型训练与评估
  1. from sklearn.ensemble import RandomForestClassifier
  2. from sklearn.svm import SVC
  3. from sklearn.linear_model import LogisticRegression
  4. # 定义多个模型
  5. models = {
  6.     'Logistic Regression': LogisticRegression(max_iter=10000, random_state=42),
  7.     'SVM': SVC(probability=True, random_state=42),
  8.     'Random Forest': RandomForestClassifier(random_state=42)
  9. }
  10. # 训练和评估每个模型
  11. results = {}
  12. for name, model in models.items():
  13.     # 训练模型
  14.     model.fit(X_train_processed, y_train)
  15.    
  16.     # 预测
  17.     y_pred = model.predict(X_test_processed)
  18.     y_prob = model.predict_proba(X_test_processed)[:, 1] if hasattr(model, 'predict_proba') else None
  19.    
  20.     # 评估模型
  21.     accuracy = accuracy_score(y_test, y_pred)
  22.     precision = precision_score(y_test, y_pred)
  23.     recall = recall_score(y_test, y_pred)
  24.     f1 = f1_score(y_test, y_pred)
  25.    
  26.     # 计算AUC(如果模型支持概率预测)
  27.     if y_prob is not None:
  28.         fpr, tpr, _ = roc_curve(y_test, y_prob)
  29.         roc_auc = auc(fpr, tpr)
  30.     else:
  31.         roc_auc = None
  32.    
  33.     # 存储结果
  34.     results[name] = {
  35.         'accuracy': accuracy,
  36.         'precision': precision,
  37.         'recall': recall,
  38.         'f1': f1,
  39.         'roc_auc': roc_auc
  40.     }
  41.    
  42.     # 打印结果
  43.     print(f"\n{name} 评估结果:")
  44.     print(f"准确率: {accuracy:.4f}")
  45.     print(f"精确率: {precision:.4f}")
  46.     print(f"召回率: {recall:.4f}")
  47.     print(f"F1分数: {f1:.4f}")
  48.     if roc_auc is not None:
  49.         print(f"AUC: {roc_auc:.4f}")
  50.    
  51.     # 打印分类报告
  52.     print("\n分类报告:")
  53.     print(classification_report(y_test, y_pred))
复制代码

7.4 模型比较与可视化
  1. import matplotlib.pyplot as plt
  2. import numpy as np
  3. # 准备比较数据
  4. metrics = ['accuracy', 'precision', 'recall', 'f1']
  5. model_names = list(results.keys())
  6. # 创建条形图
  7. x = np.arange(len(metrics))
  8. width = 0.25
  9. fig, ax = plt.subplots(figsize=(12, 6))
  10. for i, model in enumerate(model_names):
  11.     values = [results[model][metric] for metric in metrics]
  12.     ax.bar(x + i * width, values, width, label=model)
  13. # 添加标签和标题
  14. ax.set_xlabel('评估指标')
  15. ax.set_ylabel('分数')
  16. ax.set_title('模型性能比较')
  17. ax.set_xticks(x + width)
  18. ax.set_xticklabels(metrics)
  19. ax.legend()
  20. plt.tight_layout()
  21. plt.show()
  22. # 绘制ROC曲线
  23. plt.figure(figsize=(10, 8))
  24. for name, model in models.items():
  25.     if hasattr(model, 'predict_proba'):
  26.         y_prob = model.predict_proba(X_test_processed)[:, 1]
  27.         fpr, tpr, _ = roc_curve(y_test, y_prob)
  28.         roc_auc = auc(fpr, tpr)
  29.         plt.plot(fpr, tpr, label=f'{name} (AUC = {roc_auc:.2f})')
  30. plt.plot([0, 1], [0, 1], 'k--')
  31. plt.xlim([0.0, 1.0])
  32. plt.ylim([0.0, 1.05])
  33. plt.xlabel('假正例率')
  34. plt.ylabel('真正例率')
  35. plt.title('ROC曲线比较')
  36. plt.legend(loc="lower right")
  37. plt.show()
复制代码

7.5 超参数调优
  1. # 选择最佳模型进行超参数调优
  2. best_model_name = max(results.keys(), key=lambda k: results[k]['f1'])
  3. print(f"选择 {best_model_name} 进行超参数调优")
  4. if best_model_name == 'Logistic Regression':
  5.     model = LogisticRegression(max_iter=10000, random_state=42)
  6.     param_grid = {
  7.         'C': [0.001, 0.01, 0.1, 1, 10, 100, 1000],
  8.         'penalty': ['l1', 'l2'],
  9.         'solver': ['liblinear', 'saga']
  10.     }
  11. elif best_model_name == 'SVM':
  12.     model = SVC(probability=True, random_state=42)
  13.     param_grid = {
  14.         'C': [0.1, 1, 10, 100],
  15.         'gamma': [1, 0.1, 0.01, 0.001],
  16.         'kernel': ['rbf', 'linear']
  17.     }
  18. else:  # Random Forest
  19.     model = RandomForestClassifier(random_state=42)
  20.     param_grid = {
  21.         'n_estimators': [50, 100, 200],
  22.         'max_depth': [None, 10, 20, 30],
  23.         'min_samples_split': [2, 5, 10],
  24.         'min_samples_leaf': [1, 2, 4]
  25.     }
  26. # 创建网格搜索对象
  27. grid_search = GridSearchCV(
  28.     estimator=model,
  29.     param_grid=param_grid,
  30.     cv=5,
  31.     scoring='f1',
  32.     verbose=1,
  33.     n_jobs=-1
  34. )
  35. # 执行网格搜索
  36. grid_search.fit(X_train_processed, y_train)
  37. # 输出最佳参数和得分
  38. print(f"\n最佳参数: {grid_search.best_params_}")
  39. print(f"最佳交叉验证F1分数: {grid_search.best_score_:.4f}")
  40. # 使用最佳模型进行预测
  41. best_model = grid_search.best_estimator_
  42. y_pred = best_model.predict(X_test_processed)
  43. y_prob = best_model.predict_proba(X_test_processed)[:, 1] if hasattr(best_model, 'predict_proba') else None
  44. # 评估最佳模型
  45. accuracy = accuracy_score(y_test, y_pred)
  46. precision = precision_score(y_test, y_pred)
  47. recall = recall_score(y_test, y_pred)
  48. f1 = f1_score(y_test, y_pred)
  49. if y_prob is not None:
  50.     fpr, tpr, _ = roc_curve(y_test, y_prob)
  51.     roc_auc = auc(fpr, tpr)
  52. else:
  53.     roc_auc = None
  54. print(f"\n调优后模型评估结果:")
  55. print(f"准确率: {accuracy:.4f}")
  56. print(f"精确率: {precision:.4f}")
  57. print(f"召回率: {recall:.4f}")
  58. print(f"F1分数: {f1:.4f}")
  59. if roc_auc is not None:
  60.     print(f"AUC: {roc_auc:.4f}")
  61. # 打印分类报告
  62. print("\n分类报告:")
  63. print(classification_report(y_test, y_pred))
复制代码

7.6 特征重要性分析
  1. # 如果模型支持特征重要性,则进行分析
  2. if hasattr(best_model, 'feature_importances_'):
  3.     # 获取特征重要性
  4.     importances = best_model.feature_importances_
  5.    
  6.     # 创建特征重要性DataFrame
  7.     feature_importance = pd.DataFrame({
  8.         'feature': X.columns,
  9.         'importance': importances
  10.     }).sort_values('importance', ascending=False)
  11.    
  12.     # 打印前10个最重要的特征
  13.     print("前10个最重要的特征:")
  14.     print(feature_importance.head(10))
  15.    
  16.     # 可视化特征重要性
  17.     plt.figure(figsize=(12, 8))
  18.     plt.barh(feature_importance['feature'][:10], feature_importance['importance'][:10])
  19.     plt.xlabel('重要性')
  20.     plt.ylabel('特征')
  21.     plt.title('特征重要性')
  22.     plt.gca().invert_yaxis()
  23.     plt.show()
  24. elif hasattr(best_model, 'coef_'):
  25.     # 对于线性模型,使用系数的绝对值作为特征重要性
  26.     if len(best_model.coef_.shape) == 1:
  27.         coefficients = best_model.coef_
  28.     else:
  29.         coefficients = best_model.coef_[0]
  30.    
  31.     # 创建特征重要性DataFrame
  32.     feature_importance = pd.DataFrame({
  33.         'feature': X.columns,
  34.         'importance': np.abs(coefficients)
  35.     }).sort_values('importance', ascending=False)
  36.    
  37.     # 打印前10个最重要的特征
  38.     print("前10个最重要的特征:")
  39.     print(feature_importance.head(10))
  40.    
  41.     # 可视化特征重要性
  42.     plt.figure(figsize=(12, 8))
  43.     plt.barh(feature_importance['feature'][:10], feature_importance['importance'][:10])
  44.     plt.xlabel('系数绝对值')
  45.     plt.ylabel('特征')
  46.     plt.title('特征重要性')
  47.     plt.gca().invert_yaxis()
  48.     plt.show()
复制代码

8. 最佳实践和常见陷阱

8.1 数据泄露 (Data Leakage)

数据泄露是指测试集的信息在训练过程中被使用,导致模型评估过于乐观。
  1. # 错误示例:在划分数据集之前进行标准化
  2. X_wrong = StandardScaler().fit_transform(X)  # 错误:使用整个数据集进行拟合
  3. X_train_wrong, X_test_wrong, y_train, y_test = train_test_split(X_wrong, y, test_size=0.2, random_state=42)
  4. # 正确示例:先划分数据集,然后分别对训练集和测试集进行标准化
  5. X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
  6. scaler = StandardScaler()
  7. X_train_correct = scaler.fit_transform(X_train)  # 正确:只使用训练集进行拟合
  8. X_test_correct = scaler.transform(X_test)  # 正确:使用相同的变换应用于测试集
复制代码

8.2 类别不平衡处理

类别不平衡会导致模型偏向多数类,影响模型性能。
  1. from imblearn.over_sampling import SMOTE
  2. from imblearn.under_sampling import RandomUnderSampler
  3. from imblearn.pipeline import Pipeline as ImbPipeline
  4. # 创建不平衡数据集
  5. X_imb, y_imb = make_classification(n_samples=1000, n_classes=2, weights=[0.9, 0.1], random_state=42)
  6. # 查看类别分布
  7. print(f"原始数据类别分布: {pd.Series(y_imb).value_counts().to_dict()}")
  8. # 方法1:使用class_weight参数
  9. model_balanced = LogisticRegression(class_weight='balanced', random_state=42)
  10. model_balanced.fit(X_imb, y_imb)
  11. # 方法2:使用过采样和欠采样
  12. resampling = ImbPipeline([
  13.     ('oversample', SMOTE(random_state=42)),
  14.     ('undersample', RandomUnderSampler(random_state=42)),
  15.     ('classifier', LogisticRegression(random_state=42))
  16. ])
  17. resampling.fit(X_imb, y_imb)
复制代码

8.3 交叉验证的正确使用

交叉验证应该在整个预处理流程之后进行,而不是之前。
  1. # 错误示例:先进行交叉验证,再进行预处理
  2. cv_scores_wrong = cross_val_score(LogisticRegression(), X, y, cv=5)
  3. # 正确示例:使用Pipeline将预处理和模型结合,然后进行交叉验证
  4. pipeline = Pipeline([
  5.     ('scaler', StandardScaler()),
  6.     ('classifier', LogisticRegression())
  7. ])
  8. cv_scores_correct = cross_val_score(pipeline, X, y, cv=5)
  9. print(f"错误交叉验证得分: {cv_scores_wrong}")
  10. print(f"正确交叉验证得分: {cv_scores_correct}")
复制代码

8.4 模型选择与评估

在模型选择和评估过程中,应该使用独立的数据集进行最终评估。
  1. # 划分数据为训练集、验证集和测试集
  2. X_temp, X_test, y_temp, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
  3. X_train, X_val, y_train, y_val = train_test_split(X_temp, y_temp, test_size=0.25, random_state=42)
  4. print(f"训练集大小: {X_train.shape[0]}")
  5. print(f"验证集大小: {X_val.shape[0]}")
  6. print(f"测试集大小: {X_test.shape[0]}")
  7. # 在训练集上训练模型,在验证集上选择最佳模型
  8. pipeline = Pipeline([
  9.     ('scaler', StandardScaler()),
  10.     ('classifier', LogisticRegression())
  11. ])
  12. pipeline.fit(X_train, y_train)
  13. val_score = pipeline.score(X_val, y_val)
  14. # 在测试集上评估最终模型
  15. test_score = pipeline.score(X_test, y_test)
  16. print(f"验证集得分: {val_score:.4f}")
  17. print(f"测试集得分: {test_score:.4f}")
复制代码

9. 结论

本文全面介绍了使用scikit-learn进行模型评估与预测的核心技能,从基础指标到高级技巧。我们学习了各种评估指标的使用方法、交叉验证技术、超参数调优策略以及模型预测和持久化的方法。通过实战案例,我们展示了如何将这些技术应用到真实数据集上,并讨论了常见的陷阱和最佳实践。

掌握这些技能将帮助你更好地评估机器学习模型的性能,选择最适合特定问题的模型,并将模型应用到实际场景中。记住,模型评估与预测是机器学习项目成功的关键环节,需要仔细考虑数据特点、业务需求和评估指标的选择。

随着你经验的积累,你将能够更加熟练地运用这些技术,并探索更高级的方法来解决复杂的机器学习问题。希望本文能为你的机器学习之旅提供有价值的指导。
「七転び八起き(ななころびやおき)」
回复

使用道具 举报

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

本版积分规则