名称: sklearn模型训练器 描述: 使用交叉验证、超参数调优、管道构建和模型序列化的Scikit-learn模型训练技能。利用scikit-learn的全面工具包实现自动化机器学习模型开发。 允许工具: Read, Grep, Write, Bash, Edit, Glob
Scikit-learn模型训练器
使用scikit-learn训练机器学习模型,支持交叉验证、超参数调优和管道构建。
概述
本技能提供使用scikit-learn训练机器学习模型的全面能力。它支持从数据预处理到模型训练、评估和序列化的完整模型开发工作流程。
能力
模型训练
- 训练分类模型(逻辑回归、随机森林、支持向量机等)
- 训练回归模型(线性回归、梯度提升等)
- 训练聚类模型(K均值、DBSCAN等)
- 支持集成方法(投票分类器、堆叠等)
交叉验证
- K折交叉验证
- 用于不平衡数据集的分层K折
- 时间序列分割用于时序数据
- 留一法和留p法验证
- 自定义交叉验证策略
超参数调优
- GridSearchCV用于穷举搜索
- RandomizedSearchCV用于随机采样
- 减半搜索策略提高效率
- 自定义评分函数
- 多指标评估
管道构建
- 特征预处理管道
- 异构数据的列转换器
- 特征选择集成
- 带缓存的复合管道
模型序列化
- 使用joblib保存模型(推荐)
- Pickle序列化
- ONNX导出实现互操作性
- 模型版本控制支持
先决条件
安装
pip install scikit-learn>=1.0.0 joblib pandas numpy
可选依赖
# 用于ONNX导出
pip install skl2onnx onnxruntime
# 用于额外预处理
pip install category_encoders imbalanced-learn
使用模式
基础模型训练
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split, cross_val_score
from sklearn.metrics import classification_report
import joblib
# 分割数据
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42, stratify=y
)
# 训练模型
model = RandomForestClassifier(
n_estimators=100,
max_depth=10,
random_state=42
)
model.fit(X_train, y_train)
# 交叉验证
cv_scores = cross_val_score(model, X_train, y_train, cv=5, scoring='accuracy')
print(f"CV准确率: {cv_scores.mean():.3f} (+/- {cv_scores.std() * 2:.3f})")
# 评估
y_pred = model.predict(X_test)
print(classification_report(y_test, y_pred))
# 保存模型
joblib.dump(model, 'model.joblib')
带预处理的管道
from sklearn.pipeline import Pipeline
from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import StandardScaler, OneHotEncoder
from sklearn.impute import SimpleImputer
from sklearn.ensemble import GradientBoostingClassifier
# 定义预处理
数值特征 = ['年龄', '收入', '分数']
分类特征 = ['类别', '地区']
数值转换器 = Pipeline(steps=[
('填充器', SimpleImputer(strategy='median')),
('标准化器', StandardScaler())
])
分类转换器 = Pipeline(steps=[
('填充器', SimpleImputer(strategy='constant', fill_value='缺失')),
('独热编码', OneHotEncoder(handle_unknown='ignore'))
])
预处理器 = ColumnTransformer(
transformers=[
('数值', 数值转换器, 数值特征),
('分类', 分类转换器, 分类特征)
]
)
# 创建完整管道
管道 = Pipeline(steps=[
('预处理器', 预处理器),
('分类器', GradientBoostingClassifier())
])
# 训练
管道.fit(X_train, y_train)
使用GridSearchCV进行超参数调优
from sklearn.model_selection import GridSearchCV
# 定义参数网格
参数网格 = {
'分类器__n_estimators': [50, 100, 200],
'分类器__max_depth': [3, 5, 10, None],
'分类器__learning_rate': [0.01, 0.1, 0.2]
}
# 网格搜索
网格搜索 = GridSearchCV(
管道,
参数网格,
cv=5,
scoring='f1_weighted',
n_jobs=-1,
verbose=2
)
网格搜索.fit(X_train, y_train)
print(f"最佳参数: {网格搜索.best_params_}")
print(f"最佳分数: {网格搜索.best_score_:.3f}")
# 获取最佳模型
最佳模型 = 网格搜索.best_estimator_
特征选择
from sklearn.feature_selection import SelectFromModel, RFE
from sklearn.ensemble import RandomForestClassifier
# 方法1: SelectFromModel
选择器 = SelectFromModel(
RandomForestClassifier(n_estimators=100, random_state=42),
threshold='median'
)
X_选择 = 选择器.fit_transform(X_train, y_train)
# 方法2: 递归特征消除
递归特征消除 = RFE(
estimator=RandomForestClassifier(n_estimators=100, random_state=42),
n_features_to_select=10,
step=1
)
X_递归特征消除 = 递归特征消除.fit_transform(X_train, y_train)
# 获取选择的特征
选择的特征 = X.columns[递归特征消除.support_].tolist()
与Babysitter SDK集成
任务定义示例
const sklearn训练任务 = defineTask({
name: 'sklearn模型训练',
description: '使用交叉验证训练scikit-learn模型',
inputs: {
modelType: { type: 'string', required: true },
trainDataPath: { type: 'string', required: true },
targetColumn: { type: 'string', required: true },
hyperparameters: { type: 'object', default: {} },
cvFolds: { type: 'number', default: 5 },
scoringMetric: { type: 'string', default: 'accuracy' }
},
outputs: {
modelPath: { type: 'string' },
cvScores: { type: 'array' },
bestScore: { type: 'number' },
featureImportances: { type: 'object' }
},
async run(inputs, taskCtx) {
return {
kind: 'skill',
title: `训练 ${inputs.modelType} 模型`,
skill: {
name: 'sklearn模型训练器',
context: {
operation: 'train_with_cv',
modelType: inputs.modelType,
trainDataPath: inputs.trainDataPath,
targetColumn: inputs.targetColumn,
hyperparameters: inputs.hyperparameters,
cvFolds: inputs.cvFolds,
scoringMetric: inputs.scoringMetric
}
},
io: {
inputJsonPath: `tasks/${taskCtx.effectId}/input.json`,
outputJsonPath: `tasks/${taskCtx.effectId}/result.json`
}
};
}
});
模型选择指南
分类模型
| 模型 | 使用场景 | 优点 | 缺点 |
|---|---|---|---|
| 逻辑回归 | 二分类/多分类,可解释性 | 快速,可解释 | 线性边界 |
| 随机森林分类器 | 通用目的 | 鲁棒,处理非线性 | 可能过拟合 |
| 梯度提升分类器 | 需要高精度 | 最先进的性能 | 训练较慢 |
| 支持向量分类器 | 小/中型数据集 | 高维空间有效 | 大数据集慢 |
| XGB分类器 | 竞赛/生产 | 快速,准确 | 许多超参数 |
回归模型
| 模型 | 使用场景 | 优点 | 缺点 |
|---|---|---|---|
| 线性回归 | 基线,可解释性 | 简单,快速 | 假设线性 |
| 岭回归/Lasso | 需要正则化 | 防止过拟合 | 仍为线性 |
| 随机森林回归器 | 通用目的 | 处理非线性 | 可能过拟合 |
| 梯度提升回归器 | 高精度 | 优秀性能 | 较慢 |
| 支持向量回归器 | 小数据集 | 对异常值鲁棒 | 扩展慢 |
最佳实践
- 始终使用管道: 通过在管道中包含预处理来防止数据泄漏
- 分层分割: 对不平衡分类使用分层采样
- 交叉验证: 切勿在测试数据上调整超参数
- 特征缩放: 对基于距离的模型应用适当的缩放
- 随机种子: 设置random_state以确保可重复性
- 模型持久化: 对大型numpy数组使用joblib而非pickle