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

示例

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 机器学习入门实战

背景

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 各自适用什么场景?