机器学习入门:Scikit-learn实战

Python 数据分析与人工智能 · 第4篇

◀ 第3篇 可视化 4 / 5 第5篇 大模型 ▶

前三篇我们掌握了数据处理三件套(NumPy、Pandas、Matplotlib),现在终于进入机器学习的核心地带。Scikit-learn 是 Python 机器学习最成熟的库,统一的 fit/predict/transform 接口让不同算法的切换异常简单。本篇将从概念到实战,带你完整走通分类、回归、评估和调参的全流程。

📖 本篇目录

1 什么是机器学习?
2 Scikit-learn 统一接口
3 数据预处理与划分
4 分类任务:KNN、决策树、逻辑回归
5 模型评估指标
6 回归任务与交叉验证
7 实战:鸢尾花分类完整流程

一、什么是机器学习?

机器学习的核心思想:不手动写规则,而是让机器从数据中自动发现规律。传统编程是"人写规则",机器学习是"人给数据,机器学规则"。

类型 监督学习 无监督学习
数据要求 有标签(特征+目标值) 无标签(只有特征)
目标 预测已知结果 发现隐藏结构
子类型 分类(离散)、回归(连续) 聚类、降维
典型算法 KNN、决策树、逻辑回归 K-Means、PCA
应用场景 垃圾邮件检测、房价预测 用户分群、推荐系统

机器学习基本流程

原始数据
→
特征工程
→
模型训练
→
评估调优
→
预测部署

二、Scikit-learn 统一接口

Scikit-learn 最优雅的设计是其统一 API——无论什么算法,都遵循相同的三个方法:

方法 用途 适用对象
fit(X, y) 用训练数据学习模型 模型、预处理器
predict(X) 对新数据做预测 模型
transform(X) 数据变换(标准化等) 预处理器
score(X, y) 评估模型得分 模型
Python Scikit-learn 三步走
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
# Step 1: 加载数据
iris = load_iris()
X = iris.data # 特征矩阵 (150, 4)
y = iris.target # 目标标签 (150,)
# Step 2: 划分训练集/测试集
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42
)
# Step 3: 创建模型 → 训练 → 预测
model = KNeighborsClassifier(n_neighbors=5)
model.fit(X_train, y_train) # 训练
predictions = model.predict(X_test) # 预测
score = model.score(X_test, y_test) # 评估
print(f"准确率: {score:.2%}")

就这么简单!Scikit-learn 的核心就是这三步:创建 → fit → predict。所有算法都遵循相同接口,切换模型只需更换类名。

三、数据预处理与划分

机器学习模型对输入数据的尺度和格式敏感。比如"年龄"(20~80)和"收入"(5000~50000)量级差很大,直接使用会干扰模型学习。需要标准化处理。

Python 数据预处理 Pipeline
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
from sklearn.preprocessing import StandardScaler
from sklearn.preprocessing import LabelEncoder
from sklearn.model_selection import train_test_split
import numpy as np
# === 数值特征标准化 ===
scaler = StandardScaler()
# 重要:只在训练集上 fit!
X_train_scaled = scaler.fit_transform(X_train)
# 测试集只做 transform(用训练集的参数)
X_test_scaled = scaler.transform(X_test)
print("标准化后均值:", X_train_scaled.mean(axis=0))
# 接近 [0, 0, 0, 0]
print("标准化后标准差:", X_train_scaled.std(axis=0))
# 接近 [1, 1, 1, 1]
# === 分类特征编码 ===
# 文本标签 → 数字
le = LabelEncoder()
cities = ["北京", "上海", "广州", "北京"]
encoded = le.fit_transform(cities)
print("编码结果:", encoded) # [0, 2, 1, 0]
# === 数据集划分最佳实践 ===
X_train, X_temp, y_train, y_temp = train_test_split(
X, y, test_size=0.3, random_state=42
)
X_val, X_test, y_val, y_test = train_test_split(
X_temp, y_temp, test_size=0.5, random_state=42
)
print(f"训练:{len(X_train)} 验证:{len(X_val)} 测试:{len(X_test)}")

⚠️ 常见错误:数据泄露(Data Leakage)

千万不要在全量数据上做 scaler.fit()!必须先划分训练/测试集,然后只在训练集上 fit,测试集只做 transform。否则模型会"偷看"测试集信息,评估结果虚假偏高。

💡 小贴士:为什么要划分验证集?

训练集用来训练模型,验证集用来调超参数,测试集用来最终评估。如果把验证和测试混为一谈,调参过程就会"过拟合"到测试集上,导致真实场景表现变差。

四、分类任务:三大经典算法

分类是预测数据属于哪个类别(离散值)。下面对比三种最常用的入门分类算法:

Python 三种分类算法对比
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.neighbors import KNeighborsClassifier
from sklearn.tree import DecisionTreeClassifier
from sklearn.linear_model import LogisticRegression
# 数据准备
iris = load_iris()
X_train, X_test, y_train, y_test = train_test_split(
iris.data, iris.target, test_size=0.3,
random_state=42
)
scaler = StandardScaler()
X_train_s = scaler.fit_transform(X_train)
X_test_s = scaler.transform(X_test)
# 三种模型
models = {
"KNN (k=5)": KNeighborsClassifier(
n_neighbors=5),
"决策树": DecisionTreeClassifier(
max_depth=3, random_state=42),
"逻辑回归": LogisticRegression(
max_iter=200, random_state=42),
}
# 逐一训练和评估
for name, model in models.items():
model.fit(X_train_s, y_train)
score = model.score(X_test_s, y_test)
print(f"{name}: 准确率 {score:.2%}")
# KNN (k=5): 准确率 100.00%
# 决策树: 准确率 100.00%
# 逻辑回归: 准确率 100.00%
算法 原理 优缺点
KNN 找最近的K个邻居投票 简单直观,大数据慢
决策树 树形规则层层判断 可解释强,易过拟合
逻辑回归 线性组合+Sigmoid 快速稳定,只处理线性

五、模型评估指标

准确率(accuracy)并非万能。在不平衡数据(如99%正常、1%欺诈)中,全猜"正常"也能99%准确率。需要更全面的评估指标:

Python 完整评估指标体系
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
from sklearn.metrics import (
accuracy_score, precision_score,
recall_score, f1_score,
confusion_matrix, classification_report
)
import matplotlib.pyplot as plt
import seaborn as sns
# 假设已有 y_test 和 predictions
y_pred = model.predict(X_test_s)
# 基本指标
print(f"准确率 Accuracy: {accuracy_score(y_test, y_pred):.3f}")
print(f"精确率 Precision: {precision_score(y_test, y_pred, average='macro'):.3f}")
print(f"召回率 Recall: {recall_score(y_test, y_pred, average='macro'):.3f}")
print(f"F1分数: {f1_score(y_test, y_pred, average='macro'):.3f}")
# 混淆矩阵
cm = confusion_matrix(y_test, y_pred)
sns.heatmap(cm, annot=True, fmt="d", cmap="Purples")
plt.title("混淆矩阵")
plt.show()
# 完整分类报告(一次看全所有指标)
print(classification_report(
y_test, y_pred,
target_names=iris.target_names
))
指标 含义 关注什么
Accuracy 预测正确比例 类别均衡时有效
Precision 预测为正的里面真正比例 误报代价高(如垃圾邮件)
Recall 实际为正的里面被找出比例 漏报代价高(如疾病检测)
F1 Precision和Recall调和均值 需两者兼顾时

六、回归任务与交叉验证

回归是预测连续数值(如房价、温度)。而交叉验证能更可靠地评估模型泛化能力。

Python 线性回归 + 交叉验证
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
from sklearn.datasets import load_diabetes
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import (
cross_val_score, GridSearchCV
)
from sklearn.metrics import mean_squared_error, r2_score
from sklearn.preprocessing import StandardScaler
# 加载糖尿病数据集
diabetes = load_diabetes()
X, y = diabetes.data, diabetes.target
# 线性回归
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)
reg = LinearRegression()
reg.fit(X_scaled, y)
y_pred = reg.predict(X_scaled)
print(f"MSE: {mean_squared_error(y, y_pred):.1f}")
print(f"R²: {r2_score(y, y_pred):.3f}")
# === 5折交叉验证 ===
cv_scores = cross_val_score(
reg, X_scaled, y, cv=5,
scoring="neg_mean_squared_error"
)
print(f"CV MSE均值: {-cv_scores.mean():.1f}")
print(f"CV MSE标准差: {cv_scores.std():.1f}")
# === 超参调优(GridSearchCV)===
from sklearn.ensemble import RandomForestClassifier
param_grid = {
"n_estimators": [50, 100, 200],
"max_depth": [None, 5, 10],
}
grid = GridSearchCV(
RandomForestClassifier(random_state=42),
param_grid, cv=5
)
grid.fit(X_train, y_train)
print(f"最佳参数: {grid.best_params_}")
print(f"最佳得分: {grid.best_score_:.3f}")

💡 小贴士:交叉验证如何工作?

5折交叉验证将数据分成5份,轮流用4份训练、1份验证,得到5个分数取均值。这样评估更稳定,不会因为一次随机划分就得到好/坏的结果。标准差小说明模型表现稳定。

七、实战:鸢尾花分类完整流程

最后用一个完整案例串联所有知识点——从数据加载到模型选择、评估和可视化:

Python 鸢尾花分类完整 Pipeline
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import load_iris
from sklearn.model_selection import (
train_test_split, cross_val_score
)
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import Pipeline
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import classification_report
from sklearn.metrics import ConfusionMatrixDisplay
# 1. 加载数据
iris = load_iris()
X, y = iris.data, iris.target
# 2. 划分数据
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2,
random_state=42, stratify=y
)
# 3. 构建Pipeline(预处理+模型串联)
pipe = Pipeline([
("scaler", StandardScaler()),
("clf", RandomForestClassifier(
n_estimators=100,
random_state=42
)),
])
# 4. 交叉验证评估
cv_scores = cross_val_score(
pipe, X_train, y_train, cv=5
)
print(f"CV准确率: {cv_scores.mean():.3f} ± {cv_scores.std():.3f}")
# 5. 最终训练和测试
pipe.fit(X_train, y_train)
y_pred = pipe.predict(X_test)
# 6. 输出评估报告
print(classification_report(
y_test, y_pred,
target_names=iris.target_names
))
# 7. 可视化混淆矩阵
fig, ax = plt.subplots(figsize=(6, 5))
ConfusionMatrixDisplay.from_predictions(
y_test, y_pred,
display_labels=iris.target_names,
cmap="Purples", ax=ax
)
plt.title("鸢尾花分类 - 混淆矩阵")
plt.tight_layout()
plt.show()
# 8. 特征重要性
importances = pipe["clf"].feature_importances_
for feat, imp in zip(iris.feature_names, importances):
print(f" {feat}: {imp:.3f}")

这段代码展示了机器学习工程的完整最佳实践:使用 Pipeline 将预处理和模型串联(避免数据泄露)、用 stratify=y 保持类别比例、用交叉验证获得可靠评估、用 classification_report 一次看清所有指标。

⚠️ 常见错误:过拟合的三大信号

1. 训练集准确率远高于测试集(差距>10%)

2. 交叉验证分数波动大(标准差>0.05)

3. 模型过于复杂(如决策树深度过大)

📝 本篇小结

核心知识点回顾:

✅ 机器学习核心:从数据中自动学习规律

✅ Scikit-learn 统一接口:fit → predict → score

✅ 数据预处理必须在训练集上 fit,测试集只 transform

✅ 不平衡数据要用 Precision/Recall/F1,不能只看 Accuracy

✅ Pipeline + 交叉验证 = 工程最佳实践

👉 下一篇预告

大模型应用开发:LangChain 入门

传统机器学习需要大量特征工程和模型选择。而大语言模型(LLM)的出现改变了这一切——你只需提供数据和提示词。下一篇我们将进入 AI 最前沿,用 LangChain 构建一个知识库问答系统。

第5篇 · 大模型应用开发

Python 数据分析与人工智能 · 系列学习文章

坚持原创,每一行代码均可运行

相关阅读
想动手实操?你需要一台服务器
学编程离不开动手实操。一台入门级云服务器是你最好的练习场,数据库、对象存储、CDN、短信也都能用上,入门配置很便宜,够你把学到的东西真跑一遍。
查看腾讯云优惠查看阿里云优惠
想系统入门?配一本书
看文章学的是零散知识点,想系统入门还得有一本书打底。
Python 入门书C 与 Python 入门Web 开发书