Scikit-learn

技术栈
AI 框架
scikit-learnpython机器学习分类回归聚类

概览

Scikit-learn

Scikit-learn 是 Python 最流行的机器学习库,构建在 NumPy、SciPy 和 Matplotlib 之上。由 David Cournapeau 于 2007 年发起,现在由 INRIA 和社区维护。

解决什么问题

  • 提供统一的 API 进行分类、回归、聚类、降维等经典机器学习任务
  • 内置大量预处理、特征选择、模型选择的工具
  • 让非深度学习场景的 ML 建模变得极其简单

关键特性

  • 统一的 fit/predict/transform API 设计
  • 涵盖 SVM、随机森林、XGBoost 风格接口、K-Means 等 100+ 算法
  • 强大的 Pipeline 和 ColumnTransformer 用于复杂特征工程
  • 交叉验证、网格搜索(GridSearchCV)等模型调优工具
  • 丰富的内置数据集(iris、digits、wine 等)

安装

环境准备

  • 操作系统: Windows / macOS / Linux 均可
  • Python 版本: 3.9 及以上(推荐 3.10+)
  • 前置依赖: NumPy、SciPy(会自动安装)

安装命令

# 基础安装
pip install scikit-learn

# 如果需要完整科学计算环境(推荐新手)
pip install scikit-learn numpy scipy matplotlib pandas

# 清华镜像加速
pip install scikit-learn -i https://pypi.tuna.tsinghua.edu.cn/simple

验证安装:

import sklearn
print(sklearn.__version__)  # 应输出 1.x.x
print(sklearn.show_versions())  # 查看所有依赖版本

常见安装问题

Q: ImportError 关于 NumPy

pip install --upgrade numpy scipy

Q: macOS M1/M2 芯片安装失败

pip install --no-cache-dir scikit-learn

Q: 编译错误缺少 OpenMP(macOS)

brew install libomp

Q: 与已安装的 SciPy 版本冲突

pip install --upgrade scikit-learn scipy numpy

示例

Hello World — 鸢尾花分类.md

Scikit-learn Hello World:鸢尾花分类

目标

使用经典的 Iris 数据集,训练一个随机森林分类器并评估准确率。这是 scikit-learn 最经典的入门示例。

完整代码

from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score, classification_report

# 1. 加载数据
iris = load_iris()
X, y = iris.data, iris.target
print(f"特征形状: {X.shape}, 标签形状: {y.shape}")
print(f"类别名: {iris.target_names}")

# 2. 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.3, random_state=42
)

# 3. 创建并训练模型
clf = RandomForestClassifier(n_estimators=100, random_state=42)
clf.fit(X_train, y_train)

# 4. 预测并评估
y_pred = clf.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
print(f"\n准确率: {accuracy:.2%}")
print("\n分类报告:")
print(classification_report(y_test, y_pred, target_names=iris.target_names))

# 5. 特征重要性
for name, importance in zip(iris.feature_names, clf.feature_importances_):
    print(f"  {name}: {importance:.4f}")

运行步骤

pip install scikit-learn
python iris_classify.py

预期输出

特征形状: (150, 4), 标签形状: (150,)
类别名: ['setosa' 'versicolor' 'virginica']

准确率: 97.78%

分类报告:
              precision    recall  f1-score   support

      setosa       1.00      1.00      1.00        19
  versicolor       0.93      1.00      0.96        13
   virginica       1.00      0.92      0.96        13

    accuracy                           0.98        45

  sepal length (cm): 0.1081
  sepal width (cm): 0.0304
  petal length (cm): 0.4195
  petal width (cm): 0.4420

教程

Scikit-learn 机器学习入门实战.md

Scikit-learn 机器学习入门实战

背景

Scikit-learn 提供了「瑞士军刀」式的机器学习工具箱。无论你是做表格数据的分类、用户分群还是异常检测,掌握它能让你在几分钟内完成从数据处理到模型评估的完整流程。


第 1 章:理解 API 设计哲学

Scikit-learn 所有模型遵循统一接口:

模式 伪代码
分类/回归 model.fit(X_train, y_train)model.predict(X_test)
降维/聚类 model.fit(X)model.transform(X)
预处理 transformer.fit(X)transformer.transform(X)

第 2 章:Pipeline 优雅构建数据流

from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
from sklearn.linear_model import LogisticRegression

pipe = Pipeline([
    ("scaler", StandardScaler()),
    ("pca", PCA(n_components=2)),
    ("clf", LogisticRegression())
])

pipe.fit(X_train, y_train)
accuracy = pipe.score(X_test, y_test)
print(f"Pipeline 准确率: {accuracy:.2%}")

第 3 章:类别型与数值型混合特征处理

from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import OneHotEncoder, StandardScaler
from sklearn.pipeline import Pipeline

# 假设 columns 0-2 是数值型,column 3 是类别型
preprocessor = ColumnTransformer([
    ("num", StandardScaler(), [0, 1, 2]),
    ("cat", OneHotEncoder(), [3])
])

full_pipeline = Pipeline([
    ("preprocess", preprocessor),
    ("classifier", RandomForestClassifier())
])

第 4 章:网格搜索 + 交叉验证调参

from sklearn.model_selection import GridSearchCV
from sklearn.ensemble import GradientBoostingClassifier

param_grid = {
    "n_estimators": [50, 100, 200],
    "max_depth": [3, 5, None],
    "learning_rate": [0.01, 0.1, 0.2]
}

grid = GridSearchCV(
    GradientBoostingClassifier(),
    param_grid,
    cv=5,
    scoring="accuracy",
    n_jobs=-1
)
grid.fit(X_train, y_train)
print(f"最佳参数: {grid.best_params_}")
print(f"最佳 CV 分数: {grid.best_score_:.3f}")

第 5 章:模型持久化

import joblib

# 保存
joblib.dump(grid.best_estimator_, "best_model.joblib")

# 加载
model = joblib.load("best_model.joblib")
print(model.predict(X_test[:5]))

思考题

  1. 为什么 Pipeline 可以防止数据泄露?fit_transformtransform 在 cross-validation 中如何区分使用?
  2. 类别型特征超过 1000 个不同值时,OneHotEncoder 会有什么问题?可以用什么替代方案(如 Target Encoding)?
  3. GridSearchCV 和 RandomizedSearchCV 各自适用什么场景?

参考资料

  1. [1] Fabian Pedregosa, Gaël Varoquaux, Alexandre Gramfort, et al.. Scikit-learn: Machine Learning in Python. Journal of Machine Learning Research, 2011. https://www.jmlr.org/papers/v12/pedregosa11a.html
  2. [2] Fabian Pedregosa, Gaël Varoquaux, Alexandre Gramfort, et al.. Scikit-learn: Machine Learning in Python PDF. Journal of Machine Learning Research, 2011. https://jmlr.org/papers/volume12/pedregosa11a/pedregosa11a.pdf
  3. [3] Fabian Pedregosa, Gaël Varoquaux, Alexandre Gramfort, et al.. Scikit-learn: Machine Learning in Python. arXiv, 2012. https://arxiv.org/abs/1201.0490
  4. [4] Fabian Pedregosa, Gaël Varoquaux, Alexandre Gramfort, et al.. Scikit-learn: Machine Learning in Python. ACM Digital Library, 2011. doi:10.5555/1953048.2078195 https://dl.acm.org/doi/10.5555/1953048.2078195
  5. [5] Lars Buitinck, Gilles Louppe, Mathieu Blondel, et al.. API design for machine learning software: experiences from the scikit-learn project. arXiv, 2013. https://arxiv.org/abs/1309.0238
  6. [6] scikit-learn developers. scikit-learn Documentation. scikit-learn Docs, 2026. https://scikit-learn.org/
  7. [7] scikit-learn developers. scikit-learn API Reference. scikit-learn Docs, 2026. https://scikit-learn.org/stable/api/index.html
  8. [8] scikit-learn developers. scikit-learn User Guide. scikit-learn Docs, 2026. https://scikit-learn.org/stable/user_guide.html
  9. [9] scikit-learn developers. scikit-learn GitHub Repository. GitHub, 2026. https://github.com/scikit-learn/scikit-learn
  10. [10] scikit-learn developers. scikit-learn PyPI Project. PyPI, 2026. https://pypi.org/project/scikit-learn/
  11. [11] Jake VanderPlas. Introducing Scikit-Learn. Python Data Science Handbook, 2016. https://jakevdp.github.io/PythonDataScienceHandbook/05.02-introducing-scikit-learn.html
  12. [12] Jake VanderPlas. Python Data Science Handbook. O'Reilly Media, 2016. https://jakevdp.github.io/PythonDataScienceHandbook/
  13. [13] Aurélien Géron. Hands-On Machine Learning with Scikit-Learn, Keras, and TensorFlow, 3rd Edition. O'Reilly Media, 2022. https://www.oreilly.com/library/view/hands-on-machine-learning/9781098125967/
  14. [14] Trevor Hastie, Robert Tibshirani, Jerome Friedman. The Elements of Statistical Learning, Second Edition. Springer, 2009. doi:10.1007/978-0-387-84858-7 https://hastie.su.domains/ElemStatLearn/
  15. [15] Christopher M. Bishop. Pattern Recognition and Machine Learning. Springer, 2006. https://www.microsoft.com/en-us/research/people/cmbishop/prml-book/
  16. [16] Leo Breiman. Random Forests. Machine Learning, 2001. doi:10.1023/A:1010933404324
  17. [17] Chih-Chung Chang, Chih-Jen Lin. LIBSVM: A Library for Support Vector Machines. ACM Transactions on Intelligent Systems and Technology, 2011. doi:10.1145/1961189.1961199 https://www.csie.ntu.edu.tw/~cjlin/papers/libsvm.pdf
  18. [18] Christopher J. C. Burges. A Tutorial on Support Vector Machines for Pattern Recognition. Data Mining and Knowledge Discovery, 1998. doi:10.1023/A:1009715923555
  19. [19] David M. Blei, Andrew Y. Ng, Michael I. Jordan. Latent Dirichlet Allocation. Journal of Machine Learning Research, 2003. https://www.jmlr.org/papers/v3/blei03a.html
  20. [20] Martin Ester, Hans-Peter Kriegel, Jörg Sander, et al.. A Density-Based Algorithm for Discovering Clusters in Large Spatial Databases with Noise. KDD, 1996. https://www.aaai.org/Papers/KDD/1996/KDD96-037.pdf