Scikit-learn – 机器学习

面向初学者的在线Python训练器

轻松学习Python,无需理论负担。在浏览器中直接解决带自动检查的实践任务,无需安装任何东西。

开始课程

什么是 Scikit-learn

Scikit-learn — 是 Python 中最流行且最强大的开源机器学习库之一。该库由 David Cournapeau 于 2007 年开发,已成为 Python 生态系统中实现机器学习算法的事实标准。

Scikit-learn 的主要任务和功能

该库提供了解决广泛机器学习任务的现成工具:

监督学习任务:

  • 分类 — 确定对象属于特定类别
  • 回归 — 预测连续数值

无监督学习任务:

  • 聚类 — 对相似对象进行分组
  • 降维 — 在保留重要信息的同时压缩数据
  • 异常检测 — 识别数据中的异常值

其他功能:

  • 数据预处理 — 归一化、缩放、编码
  • 特征选择 — 选择信息量最大的特征
  • 模型评估 — 各种质量指标
  • 交叉验证 — 检查模型稳定性
  • 超参数调优 — 自动参数调整

安装与初始设置

通过 pip 安装

pip install scikit-learn

安装附加依赖项

pip install scikit-learn pandas matplotlib seaborn jupyter

验证安装

import sklearn
print(sklearn.__version__)

导入主要组件

# 主要模块
from sklearn.model_selection import train_test_split, cross_val_score
from sklearn.preprocessing import StandardScaler, LabelEncoder
from sklearn.linear_model import LinearRegression, LogisticRegression
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score, classification_report
from sklearn.datasets import load_iris, make_classification

架构与核心概念

Estimator(估计器)

Estimator — 是 Scikit-learn 中所有机器学习算法的基类。每个 estimator 实现两个主要方法:

  • fit(X, y) — 在数据上训练模型
  • predict(X) — 对新数据进行预测
from sklearn.linear_model import LinearRegression

model = LinearRegression()
model.fit(X_train, y_train)
predictions = model.predict(X_test)

Transformer(转换器)

Transformer — 用于数据转换的类。实现的方法:

  • fit(X) — 学习转换参数
  • transform(X) — 应用转换
  • fit_transform(X) — 结合 fit 和 transform
from sklearn.preprocessing import StandardScaler

scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)

Pipeline(管道)

Pipeline 允许将多个数据处理和训练步骤组合成一个序列:

from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC

pipeline = Pipeline([
    ('scaler', StandardScaler()),
    ('classifier', SVC())
])

pipeline.fit(X_train, y_train)
predictions = pipeline.predict(X_test)

数据处理

内置数据集

Scikit-learn 提供了许多现成的数据

推荐