✅ 今日目标
- 理解模型调参的重要性(避免欠拟合/过拟合)
- 掌握
GridSearchCV
的使用方法 - 学习 K 折交叉验证的基本流程与意义
- 对比不同参数组合的表现
- 使用
Pipeline
简化流程(进阶)
📘 一、调参思路
方法 | 描述 |
---|
Grid Search | 穷举所有参数组合,适合小规模 |
Random Search | 随机采样参数组合,适合大空间 |
Bayesian Optimization | 高级调参方式,非必须了解 |
🧰 二、GridSearchCV 使用步骤
from sklearn.model_selection import GridSearchCVparams = {'C': [0.1, 1, 10],'kernel': ['linear', 'rbf'],'gamma': ['scale', 'auto']
}grid = GridSearchCV(SVC(), param_grid=params, cv=5)
grid.fit(X_train, y_train)
print("最佳参数组合:", grid.best_params_)
print("交叉验证得分:", grid.best_score_)
📊 三、交叉验证原理
类型 | 描述 |
---|
KFold | 将数据划分为 K 份轮流验证 |
StratifiedKFold | 分类任务中保持标签比例一致 |
Leave-One-Out | 留一法,训练集几乎包含全部样本 |
🔍 避免单一划分可能带来的偶然性,提升泛化性能评估的可靠性。
🔁 四、结合管道 Pipeline(可选)
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScalerpipe = Pipeline([('scaler', StandardScaler()),('clf', SVC())
])params = {'clf__C': [1, 10],'clf__kernel': ['rbf'],'clf__gamma': ['scale', 'auto']
}grid = GridSearchCV(pipe, param_grid=params, cv=5)
grid.fit(X_train, y_train)
💡 小技巧
技巧 | 建议 |
---|
优先调影响最大的参数 | 如 C , n_estimators , max_depth |
控制计算量 | 限制搜索空间、减少 CV 次数 |
保存模型 | 用 joblib 或 pickle 序列化结果 |
🧾 今日总结
- ✅ 掌握
GridSearchCV
调参与模型选择方法 - ✅ 了解交叉验证原理与
KFold
/StratifiedKFold
- ✅ 提高模型的鲁棒性和泛化能力
- ✅ 准备在后续模型部署中使用“最佳参数”模型
📁 练习脚本:gridsearch_svm_pipeline.py
import numpy as np
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.svm import SVC
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import accuracy_score, classification_report
np.random.seed(42)
size = 100
scores = np.random.randint(40, 100, size)
genders = np.random.choice([0, 1], size=size)
labels = (scores >= 60).astype(int)X = np.column_stack(((scores - scores.mean()) / scores.std(), genders))
y = labelsX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
pipe = Pipeline([('scaler', StandardScaler()),('clf', SVC())
])
param_grid = {'clf__C': [0.1, 1, 10],'clf__kernel': ['linear', 'rbf'],'clf__gamma': ['scale', 'auto']
}
grid = GridSearchCV(pipe, param_grid=param_grid, cv=5, verbose=1, n_jobs=-1)
grid.fit(X_train, y_train)print("最佳参数组合:", grid.best_params_)
print("最佳交叉验证得分:", grid.best_score_)
y_pred = grid.predict(X_test)
print("\\n=== 最佳模型在测试集上的表现 ===")
print("准确率:", accuracy_score(y_test, y_pred))
print(classification_report(y_test, y_pred))
运行输出:
Fitting 5 folds for each of 12 candidates, totalling 60 fits
最佳参数组合: {'clf__C': 0.1, 'clf__gamma': 'scale', 'clf__kernel': 'linear'}
最佳交叉验证得分: 0.9875=== 最佳模型在测试集上的表现 ===
准确率: 0.95precision recall f1-score support0 0.88 1.00 0.93 71 1.00 0.92 0.96 13accuracy 0.95 20macro avg 0.94 0.96 0.95 20
weighted avg 0.96 0.95 0.95 20