sklearn Pipeline 如何进行模型评估与交叉验证?
·
文章目录
一、核心结论(先记这一句)
Pipeline 本身就是一个模型,你可以把它当成 KNN、随机森林直接用。
所有模型评估、交叉验证代码完全不用改,直接套 Pipeline 就行!
二、最简完整模板(直接运行)
# 1. 导入必备库
import pandas as pd
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split, cross_val_score
from sklearn.metrics import accuracy_score, classification_report, confusion_matrix
# 2. 加载数据
from sklearn.datasets import load_iris
X, y = load_iris(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 3. 定义 Pipeline(预处理 + 模型)
pipe = Pipeline(steps=[
("scaler", StandardScaler()), # 预处理
("rf", RandomForestClassifier()) # 模型
])
# ==================== 核心:评估与验证 ====================
# 训练
pipe.fit(X_train, y_train)
# 预测
y_pred = pipe.predict(X_test)
# 评估
print("准确率:", accuracy_score(y_test, y_pred))
print("\n分类报告:\n", classification_report(y_test, y_pred))
print("\n混淆矩阵:\n", confusion_matrix(y_test, y_pred))
这就是最标准的 Pipeline 评估代码!
三、Pipeline 模型评估(全场景)
1. 分类任务评估(最常用)
输出:准确率、精确率、召回率、F1、混淆矩阵
from sklearn.metrics import (
accuracy_score,
precision_score,
recall_score,
f1_score,
classification_report,
confusion_matrix
)
y_pred = pipe.predict(X_test)
print("准确率 =", accuracy_score(y_test, y_pred))
print("精确率 =", precision_score(y_test, y_pred, average='macro'))
print("召回率 =", recall_score(y_test, y_pred, average='macro'))
print("F1分数 =", f1_score(y_test, y_pred, average='macro'))
print("\n===== 详细分类报告 =====")
print(classification_report(y_test, y_pred))
2. 回归任务评估(预测数值)
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score
# 回归流水线
pipe_reg = Pipeline([
("scaler", StandardScaler()),
("lr", LinearRegression())
])
pipe_reg.fit(X_train, y_train)
y_pred_reg = pipe_reg.predict(X_test)
print("MAE =", mean_absolute_error(y_test, y_pred_reg))
print("MSE =", mean_squared_error(y_test, y_pred_reg))
print("R² =", r2_score(y_test, y_pred_reg))
四、Pipeline 交叉验证(最关键!防过拟合)
交叉验证是评估模型真实能力的最标准方法,Pipeline 支持一行调用:
1. 一行实现交叉验证
from sklearn.model_selection import cross_val_score
# cv=5 表示 5 折交叉验证
scores = cross_val_score(
estimator=pipe, # 直接传入 Pipeline!
X=X_train,
y=y_train,
cv=5, # 5折
scoring='accuracy' # 评分标准
)
print("每折得分:", scores.round(3))
print("平均得分:", scores.mean().round(3))
print("标准差:", scores.std().round(3))
常用 scoring 参数(直接用)
- 分类:
accuracy,f1_macro,roc_auc,precision - 回归:
r2,neg_mean_squared_error,neg_mean_absolute_error
2. 输出多指标交叉验证(更全面)
from sklearn.model_selection import cross_validate
# 同时输出多个指标
scores = cross_validate(
pipe,
X_train, y_train,
cv=5,
scoring=['accuracy', 'f1_macro']
)
print("5折平均准确率:", scores['test_accuracy'].mean())
print("5折平均F1:", scores['test_f1_macro'].mean())
五、Pipeline + GridSearchCV 自动调参 + 最优评估(企业最强组合)
这是工作中最常用的写法:
预处理 + 模型 + 调参 + 评估 全部自动化。
from sklearn.model_selection import GridSearchCV
# 定义参数网格(步骤名__参数)
param_grid = {
'rf__n_estimators': [50, 100, 200],
'rf__max_depth': [3, 5, None]
}
# 网格搜索(自带交叉验证)
grid = GridSearchCV(
estimator=pipe,
param_grid=param_grid,
cv=5, # 5折交叉验证
n_jobs=-1 # 全速运行
)
grid.fit(X_train, y_train)
# 输出最优结果
print("最优参数:", grid.best_params_)
print("最优交叉验证得分:", grid.best_score_.round(3))
# 用最优模型评估测试集
best_model = grid.best_estimator_
print("测试集得分:", best_model.score(X_test, y_test))
六、最重要的 3 个知识点(避坑)
1. Pipeline 会自动避免数据泄露!
交叉验证时:
- 每一折只在训练集上做预处理
- 测试集完全隔离
这是手动写不出来的安全性!
2. 评估必须在测试集上做
cross_val_score→ 用训练集做验证- 最终评估 → 必须用完全独立的测试集
3. Pipeline 可以直接保存(包含预处理)
import joblib
joblib.dump(pipe, "pipeline_model.pkl")
# 加载后直接预测,无需任何预处理
model = joblib.load("pipeline_model.pkl")
model.predict(new_data)
AtomGit 是由开放原子开源基金会联合 CSDN 等生态伙伴共同推出的新一代开源与人工智能协作平台。平台坚持“开放、中立、公益”的理念,把代码托管、模型共享、数据集托管、智能体开发体验和算力服务整合在一起,为开发者提供从开发、训练到部署的一站式体验。
更多推荐

所有评论(0)