关于 scikit-learn
面向使用 scikit-learn 进行经典机器学习的开发者,提供从预处理、建模到评估和调参的实践指导。涵盖监督与无监督任务,并强调用 Pipeline 组织可复现的工作流。
主要功能
- 01分类与回归建模
- 02聚类与降维
- 03数据预处理与特征工程
- 04交叉验证与超参数调优
- 05Pipeline 工作流构建
适用场景
- 01构建分类或回归模型
- 02探索未标注数据中的模式
- 03评估并比较候选模型
- 04将预处理与模型整合为生产流程
安装
复制下面的命令,在终端中运行。
npx skills add https:/ / github.com/ crazymsn/ academic-skills --skill scikit-learn安装后在 Claude Code 中输入/scikit-learn确认已加载。
包含的文件
除 SKILL.md 外,安装时一起下载的参考资料和脚本。
references/model_evaluation.mdpipelines_and_composition.mdpreprocessing.mdquick_reference.mdsupervised_learning.mdunsupervised_learning.mdscripts/classification_pipeline.pyclustering_analysis.py详细介绍
Scikit-learn
概述
本技能为使用 scikit-learn 进行机器学习任务提供全面指导。scikit-learn 是经典机器学习的行业标准 Python 库。可将本技能用于分类、回归、聚类、降维、预处理、模型评估,以及构建可用于生产的 ML 流水线。
安装
# Install scikit-learn using uv
uv pip install scikit-learn
# Optional: Install visualization dependencies
uv pip install matplotlib seaborn
# Commonly used with
uv pip install pandas numpy
何时使用本技能
在以下情况下使用 scikit-learn 技能:
- 构建分类或回归模型
- 执行聚类或降维
- 为机器学习预处理和转换数据
- 通过交叉验证评估模型性能
- 使用网格搜索或随机搜索调优超参数
- 为生产工作流创建 ML 流水线
- 针对某一任务比较不同算法
- 同时处理结构化(表格)数据和文本数据
- 需要可解释的经典机器学习方法
快速开始
分类示例
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import classification_report
# Split data
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, stratify=y, random_state=42
)
# Preprocess
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)
# Train model
model = RandomForestClassifier(n_estimators=100, random_state=42)
model.fit(X_train_scaled, y_train)
# Evaluate
y_pred = model.predict(X_test_scaled)
print(classification_report(y_test, y_pred))
处理混合数据的完整流水线
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
# Define feature types
numeric_features = ['age', 'income']
categorical_features = ['gender', 'occupation']
# Create preprocessing pipelines
numeric_transformer = Pipeline([
('imputer', SimpleImputer(strategy='median')),
('scaler', StandardScaler())
])
categorical_transformer = Pipeline([
('imputer', SimpleImputer(strategy='most_frequent')),
('onehot', OneHotEncoder(handle_unknown='ignore'))
])
# Combine transformers
preprocessor = ColumnTransformer([
('num', numeric_transformer, numeric_features),
('cat', categorical_transformer, categorical_features)
])
# Full pipeline
model = Pipeline([
('preprocessor', preprocessor),
('classifier', GradientBoostingClassifier(random_state=42))
])
# Fit and predict
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
核心能力
1. 监督学习
用于分类和回归任务的全面算法。
关键算法:
- 线性模型:Logistic Regression、Linear Regression、Ridge、Lasso、ElasticNet
- 基于树的模型:Decision Trees、Random Forest、Gradient Boosting
- 支持向量机:SVC、SVR,支持多种核函数
- 集成方法:AdaBoost、Voting、Stacking
- 神经网络:MLPClassifier、MLPRegressor
- 其他:Naive Bayes、K-Nearest Neighbors
适用场景:
- 分类:预测离散类别(垃圾邮件检测、图像分类、欺诈检测)
- 回归:预测连续值(价格预测、需求预测)
参见: references/supervised_learning.md,了解详细的算法文档、参数和使用示例。
2. 无监督学习
通过聚类和降维发现无标签数据中的模式。
聚类算法:
- 基于划分:K-Means、MiniBatchKMeans
- 基于密度:DBSCAN、HDBSCAN、OPTICS
- 层次聚类:AgglomerativeClustering
- 概率模型:Gaussian Mixture Models
- 其他:MeanShift、SpectralClustering、BIRCH
降维:
- 线性:PCA、TruncatedSVD、NMF
- 流形学习:t-SNE、UMAP、Isomap、LLE
- 特征提取:FastICA、LatentDirichletAllocation
适用场景:
- 客户细分、异常检测、数据可视化
- 降低特征维度、探索性数据分析
- 主题建模、图像压缩
参见: references/unsupervised_learning.md,了解详细文档。
3. 模型评估与选择
用于稳健模型评估、交叉验证和超参数调优的工具。
交叉验证策略:
- KFold、StratifiedKFold(分类)
- TimeSeriesSplit(时间序列数据)
- GroupKFold(分组样本)
超参数调优:
- GridSearchCV(穷举搜索)
- RandomizedSearchCV(随机采样)
- HalvingGridSearchCV(逐次减半)
指标:
- 分类:accuracy、precision、recall、F1-score、ROC AUC、confusion matrix
- 回归:MSE、RMSE、MAE、R²、MAPE
- 聚类:silhouette score、Calinski-Harabasz、Davies-Bouldin
适用场景:
- 客观比较模型性能
- 寻找最优超参数
- 通过交叉验证防止过拟合
- 使用学习曲线理解模型行为
参见: references/model_evaluation.md,了解全面的指标和调优策略。
4. 数据预处理
将原始数据转换为适合机器学习的格式。
缩放与归一化:
- StandardScaler(零均值、单位方差)
- MinMaxScaler(有界范围)
- RobustScaler(对离群值稳健)
- Normalizer(按样本归一化)
编码分类变量:
- OneHotEncoder(名义类别)
- OrdinalEncoder(有序类别)
- LabelEncoder(目标编码)
处理缺失值:
- SimpleImputer(均值、中位数、最频繁值)
- KNNImputer(k 近邻)
- IterativeImputer(多变量插补)
特征工程:
- PolynomialFeatures(交互项)
- KBinsDiscretizer(分箱)
- 特征选择(RFE、SelectKBest、SelectFromModel)
何时使用:
- 在训练任何需要缩放特征的算法(SVM、KNN、神经网络)之前
- 将分类变量转换为数值格式
- 系统性地处理缺失数据
- 为线性模型创建非线性特征
参见: references/preprocessing.md 了解详细的预处理技术。
5. 管道与组合
构建可复现、可用于生产的 ML 工作流。
关键组件:
- Pipeline:按顺序串联转换器和估计器
- ColumnTransformer:对不同列应用不同的预处理
- FeatureUnion:并行组合多个转换器
- TransformedTargetRegressor:转换目标变量
优势:
- 防止交叉验证中的数据泄漏
- 简化代码并提高可维护性
- 支持联合超参数调优
- 确保训练和预测之间的一致性
何时使用:
- 生产工作流中始终使用 Pipeline
- 当混合数值和分类特征时(使用 ColumnTransformer)
- 当执行带有预处理步骤的交叉验证时
- 当超参数调优包含预处理参数时
参见: references/pipelines_and_composition.md 了解全面的管道模式。
示例脚本
分类管道
运行完整的分类工作流,包括预处理、模型比较、超参数调优和评估:
python scripts/classification_pipeline.py
该脚本演示了:
- 处理混合数据类型(数值和分类)
- 使用交叉验证进行模型比较
- 使用 GridSearchCV 进行超参数调优
- 使用多个指标进行全面评估
- 特征重要性分析
聚类分析
执行聚类分析,包括算法比较和可视化:
python scripts/clustering_analysis.py
该脚本演示了:
- 寻找最佳聚类数(肘部法、轮廓分析)
- 比较多种聚类算法(K-Means、DBSCAN、Agglomerative、Gaussian Mixture)
- 在没有真实标签的情况下评估聚类质量
- 使用 PCA 投影可视化结果
参考文档
本技能包含全面的参考文件,可深入探讨特定主题:
快速参考
文件: references/quick_reference.md
- 常见导入模式和安装说明
- 常见任务的快速工作流模板
- 算法选择速查表
- 常见模式和陷阱
- 性能优化技巧
监督学习
文件: references/supervised_learning.md
- 线性模型(回归和分类)
- 支持向量机
- 决策树和集成方法
- K 近邻、朴素贝叶斯、神经网络
- 算法选择指南
无监督学习
文件: references/unsupervised_learning.md
- 所有聚类算法及其参数和用例
- 降维技术
- 离群值和新颖性检测
- 高斯混合模型
- 方法选择指南
模型评估
文件: references/model_evaluation.md
- 交叉验证策略
- 超参数调优方法
- 分类、回归和聚类指标
- 学习和验证曲线
- 模型选择的最佳实践
预处理
文件: references/preprocessing.md
- 特征缩放与归一化
- 类别变量编码
- 缺失值填充
- 特征工程技术
- 自定义转换器
流水线与组合
文件: references/pipelines_and_composition.md
- 流水线的构建与使用
- 用于混合数据类型的 ColumnTransformer
- 用于并行转换的 FeatureUnion
- 完整的端到端示例
- 最佳实践
常见工作流
构建分类模型
-
加载并探索数据
import pandas as pd df = pd.read_csv('data.csv') X = df.drop('target', axis=1) y = df['target'] -
使用分层抽样划分数据
from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.2, stratify=y, random_state=42 ) -
创建预处理流水线
from sklearn.pipeline import Pipeline from sklearn.preprocessing import StandardScaler from sklearn.compose import ColumnTransformer # Handle numeric and categorical features separately preprocessor = ColumnTransformer([ ('num', StandardScaler(), numeric_features), ('cat', OneHotEncoder(), categorical_features) ]) -
构建完整流水线
model = Pipeline([ ('preprocessor', preprocessor), ('classifier', RandomForestClassifier(random_state=42)) ]) -
调优超参数
from sklearn.model_selection import GridSearchCV param_grid = { 'classifier__n_estimators': [100, 200], 'classifier__max_depth': [10, 20, None] } grid_search = GridSearchCV(model, param_grid, cv=5) grid_search.fit(X_train, y_train) -
在测试集上评估
from sklearn.metrics import classification_report best_model = grid_search.best_estimator_ y_pred = best_model.predict(X_test) print(classification_report(y_test, y_pred))
执行聚类分析
-
预处理数据
from sklearn.preprocessing import StandardScaler scaler = StandardScaler() X_scaled = scaler.fit_transform(X) -
寻找最优聚类数量
from sklearn.cluster import KMeans from sklearn.metrics import silhouette_score scores = [] for k in range(2, 11): kmeans = KMeans(n_clusters=k, random_state=42) labels = kmeans.fit_predict(X_scaled) scores.append(silhouette_score(X_scaled, labels)) optimal_k = range(2, 11)[np.argmax(scores)] -
应用聚类
model = KMeans(n_clusters=optimal_k, random_state=42) labels = model.fit_predict(X_scaled) -
使用降维进行可视化
from sklearn.decomposition import PCA pca = PCA(n_components=2) X_2d = pca.fit_transform(X_scaled) plt.scatter(X_2d[:, 0], X_2d[:, 1], c=labels, cmap='viridis')
最佳实践
始终使用流水线
流水线可防止数据泄漏并确保一致性:
# Good: Preprocessing in pipeline
pipeline = Pipeline([
('scaler', StandardScaler()),
('model', LogisticRegression())
])
# Bad: Preprocessing outside (can leak information)
X_scaled = StandardScaler().fit_transform(X)
仅在训练数据上拟合
绝不要在测试数据上拟合:
# Good
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test) # Only transform
# Bad
scaler = StandardScaler()
X_all_scaled = scaler.fit_transform(np.vstack([X_train, X_test]))
对分类任务使用分层划分
保留类别分布:
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, stratify=y, random_state=42
)
设置随机状态以确保可复现性
model = RandomForestClassifier(n_estimators=100, random_state=42)
选择合适的指标
- 平衡数据:准确率、F1 分数
- 不平衡数据:精确率、召回率、ROC AUC、平衡准确率
- 成本敏感:定义自定义评分器
在需要时对特征进行缩放
需要特征缩放的算法:
- SVM、KNN、神经网络
- PCA、带正则化的线性/逻辑回归
- K-Means 聚类
不需要缩放的算法:
- 基于树的模型(决策树、随机森林、梯度提升)
- 朴素贝叶斯
常见问题排查
ConvergenceWarning
问题: 模型未收敛
解决方案: 增大 max_iter 或对特征进行缩放
model = LogisticRegression(max_iter=1000)
测试集上表现不佳
问题: 过拟合 解决方案: 使用正则化、交叉验证或更简单的模型
# Add regularization
model = Ridge(alpha=1.0)
# Use cross-validation
scores = cross_val_score(model, X, y, cv=5)
大数据集导致内存错误
解决方案: 使用专为大数据设计的算法
# Use SGD for large datasets
from sklearn.linear_model import SGDClassifier
model = SGDClassifier()
# Or MiniBatchKMeans for clustering
from sklearn.cluster import MiniBatchKMeans
model = MiniBatchKMeans(n_clusters=8, batch_size=100)