SuperAPI AI 工具集

scikit-learn

数据与分析

查看项目

更新于 10-15 18:31

技能介绍

用途

本技能为使用 scikit-learn 进行机器学习任务提供全面指导。scikit-learn 是 Python 中经典的机器学习标准库,适用于分类、回归、聚类、降维、预处理、模型评估以及构建生产级 ML 流水线。当需要可解释的经典机器学习方法,或处理结构化(表格)与文本数据时,可使用本技能。

主要能力

  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。分类用于预测离散类别(如垃圾邮件检测、图像分类、欺诈检测),回归用于预测连续值(如价格预测、需求预测)。

  2. 无监督学习:通过聚类与降维发现无标签数据中的模式。聚类算法包括 K-Means、MiniBatchKMeans、DBSCAN、HDBSCAN、OPTICS、AgglomerativeClustering、高斯混合模型、MeanShift、SpectralClustering、BIRCH;降维包括 PCA、TruncatedSVD、NMF、t-SNE、UMAP、Isomap、LLE、FastICA、LatentDirichletAllocation。适用于客户分群、异常检测、数据可视化、特征降维、探索性数据分析、主题建模、图像压缩。

  3. 模型评估与选择:提供交叉验证策略(KFold、StratifiedKFold、TimeSeriesSplit、GroupKFold)、超参数调优(GridSearchCV、RandomizedSearchCV、HalvingGridSearchCV)以及指标(分类:accuracy、precision、recall、F1、ROC AUC、混淆矩阵;回归:MSE、RMSE、MAE、R²、MAPE;聚类:轮廓系数、Calinski-Harabasz、Davies-Bouldin)。

  4. 数据预处理:缩放与归一化(StandardScaler、MinMaxScaler、RobustScaler、Normalizer)、类别编码(OneHotEncoder、OrdinalEncoder、LabelEncoder)、缺失值处理(SimpleImputer、KNNImputer、IterativeImputer)、特征工程(PolynomialFeatures、KBinsDiscretizer、RFE、SelectKBest、SelectFromModel)。

  5. 流水线与组合:Pipeline 顺序连接转换器与估计器,ColumnTransformer 对不同列应用不同预处理,FeatureUnion 并行组合多个转换器,TransformedTargetRegressor 转换目标变量。可防止交叉验证中的数据泄漏、简化代码、支持联合超参数调优,并保证训练与预测的一致性。

使用方式

安装命令:

# 使用 uv 安装 scikit-learn
uv uv pip install scikit-learn

# 可选:安装可视化依赖
uv uv pip install matplotlib seaborn

# 常与以下库配合使用
uv uv pip install pandas numpy

分类快速示例:

from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import classification_report

X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, stratify=y, random_state=42
)

scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)

model = RandomForestClassifier(n_estimators=100, random_state=42)
model.fit(X_train_scaled, y_train)

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

numeric_features = ['age', 'income']
categorical_features = ['gender', 'occupation']

numeric_transformer = Pipeline([
    ('imputer', SimpleImputer(strategy='median')),
    ('scaler', StandardScaler())
])

categorical_transformer = Pipeline([
    ('imputer', SimpleImputer(strategy='most_frequent')),
    ('onehot', OneHotEncoder(handle_unknown='ignore'))
])

preprocessor = ColumnTransformer([
    ('num', numeric_transformer, numeric_features),
    ('cat', categorical_transformer, categorical_features)
])

model = Pipeline([
    ('preprocessor', preprocessor),
    ('classifier', GradientBoostingClassifier(random_state=42))
])

model.fit(X_train, y_train)
y_pred = model.predict(X_test)

示例脚本:

python scripts/classification_pipeline.py
python scripts/clustering_analysis.py

classification_pipeline.py 演示混合数据类型处理、交叉验证模型比较、GridSearchCV 超参数调优、多指标评估与特征重要性分析。clustering_analysis.py 演示最优聚类数搜索(肘部法、轮廓分析)、多聚类算法比较(K-Means、DBSCAN、Agglomerative、高斯混合)、无真实标签下的聚类质量评估,以及 PCA 投影可视化。

参考文档包括:references/quick_reference.md(常用导入、工作流模板、算法选择速查、常见陷阱、性能优化)、references/supervised_learning.md、references/unsupervised_learning.md、references/model_evaluation.md、references/preprocessing.md、references/pipelines_and_composition.md。

适用场景

  • 构建分类或回归模型
  • 执行聚类或降维
  • 为机器学习预处理与转换数据
  • 使用交叉验证评估模型性能
  • 使用网格或随机搜索调优超参数
  • 为生产工作流创建 ML 流水线
  • 针对任务比较不同算法
  • 处理结构化(表格)与文本数据
  • 需要可解释的经典机器学习方法

限制与注意事项

最佳实践包括:始终使用 Pipeline 防止数据泄漏;仅在训练数据上拟合,测试数据只做 transform;分类任务使用分层切分;设置 random_state 保证可复现;根据数据情况选择合适指标(平衡数据用 accuracy、F1;不平衡数据用 precision、recall、ROC AUC、Balanced Accuracy;成本敏感场景定义自定义 scorer);对需要缩放的算法(SVM、KNN、神经网络、PCA、带正则的线性/逻辑回归、K-Means)进行特征缩放,树模型与 Naive Bayes 通常不需要。

常见问题排查:ConvergenceWarning 可通过增大 max_iter 或缩放特征解决;测试集表现差(过拟合)可使用正则化、交叉验证或更简单的模型;大数据内存不足可使用 SGDClassifier 或 MiniBatchKMeans 等面向大数据的算法。

官方资源:文档 https://scikit-learn.org/stable/ ,用户指南 https://scikit-learn.org/stable/user_guide.html ,API 参考 https://scikit-learn.org/stable/api/index.html ,示例库 https://scikit-learn.org/stable/auto_examples/index.html 。