scikit-learn

传统机器学习工具库,适合分类、回归、聚类和预处理。安装名是 scikit-learn,导入名是 sklearn。

安装与准备

python -m pip install scikit-learn pandas

先生成一份本地数据;后面的分类、评估和搜索示例按顺序运行。

from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split

X, y = make_classification(
    n_samples=240, n_features=6, n_informative=4,
    n_redundant=0, random_state=42,
)
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, stratify=y, random_state=42,
)

常用用法

用 Pipeline 连接预处理与模型

from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression

pipe = make_pipeline(
    StandardScaler(),
    LogisticRegression(max_iter=1000, random_state=42),
)
pipe.fit(X_train, y_train)
predicted = pipe.predict(X_test)
probabilities = pipe.predict_proba(X_test)

缩放器只在训练数据上拟合,测试数据复用同一组统计量。Pipeline 也能在交叉验证中保持这个顺序,见入门指南。

读懂常见接口

接口作用
fit(X, y)从数据学习参数
transform(X)按已学规则转换特征
fit_transform(X)拟合并转换,主要用于训练阶段
predict(X)输出预测类别或数值
predict_proba(X)支持此接口的分类器输出类别概率

predict_proba 的列顺序对应 pipe.classes_,不能自行假定第 0 列是什么类别。

评估分类结果

from sklearn.metrics import accuracy_score, confusion_matrix, classification_report

print(accuracy_score(y_test, predicted))
print(confusion_matrix(y_test, predicted))
print(classification_report(y_test, predicted, zero_division=0))

类别不平衡时,结合 precision、recall、F1 看效果,不能只看准确率。见模型评估。

交叉验证

from sklearn.model_selection import StratifiedKFold, cross_val_score

cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
scores = cross_val_score(pipe, X_train, y_train, cv=cv, scoring="accuracy")
print(scores.mean(), scores.std())

这里仅在训练集内交叉验证,测试集留到最终评估。分层抽样适用于当前分类示例;时间序列需要保留时间顺序,见交叉验证指南。

进阶与不常用用法

搜索超参数

from sklearn.model_selection import GridSearchCV

search = GridSearchCV(
    pipe,
    param_grid={"logisticregression__C": [0.1, 1.0, 10.0]},
    scoring="accuracy", cv=cv, n_jobs=1,
)
search.fit(X_train, y_train)
print(search.best_params_)
print(search.score(X_test, y_test))

Pipeline 参数通过 步骤名__参数名 指定。不要反复根据测试集得分调整搜索范围,见参数搜索。

数值列与类别列分别处理

下面是独立的混合特征示例:

import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import OneHotEncoder

table = pd.DataFrame({
    "hours": [1, 2, 3, 4, 5, 6],
    "method": ["book", "video", "book", "video", "book", "video"],
})
preprocess = ColumnTransformer([
    ("numeric", StandardScaler(), ["hours"]),
    ("category", OneHotEncoder(handle_unknown="ignore"), ["method"]),
])
mixed_pipe = make_pipeline(preprocess, LogisticRegression(max_iter=1000))
mixed_pipe.fit(table, [0, 0, 0, 1, 1, 1])
print(mixed_pipe.predict(pd.DataFrame({"hours": [4], "method": ["video"]})))

handle_unknown="ignore" 允许推理时遇到未见过的类别;这份六行数据仅演示接口。见组合预处理器。

易错点

  • 先对全量数据标准化再划分训练、测试集,会泄漏测试集信息。
  • random_state 方便复现,但一次随机划分不能代表所有情况下的效果。
  • 多数传统估计器的输入形状为 (样本数, 特征数);单样本也要保留二维。
  • 模型是否需要标准化取决于算法,树模型通常不需要与线性模型相同的缩放步骤。

官方文档

应用于项目

手写数字识别 从 NumPy 核心实现到 PyTorch 对照,按六阶段组织手写数字识别的模块、知识与实践。