机器学习概念
机器学习核心概念
Section titled “机器学习核心概念”机器学习的三要素:数据、模型、优化。
flowchart LR A[训练数据] --> B[模型] B --> C[预测] C --> D[损失函数] D --> E[优化器] E -->|更新参数| B三种学习范式
Section titled “三种学习范式”| 范式 | 数据 | 目标 | 生活中的类比 |
|---|---|---|---|
| 监督学习 | 有标签 (x, y) | 学习 x→y 的映射 | 有答案的练习题 |
| 无监督学习 | 无标签 (x) | 发现数据结构 | 自己找规律 |
| 强化学习 | 环境交互 | 最大化累积奖励 | 玩游戏学策略 |
from sklearn.datasets import make_classificationfrom sklearn.model_selection import train_test_splitfrom sklearn.linear_model import LogisticRegression
# 生成分类数据X, y = make_classification(n_samples=500, n_features=4, random_state=42)
# 划分训练集和测试集X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.2, random_state=42)
# 训练model = LogisticRegression()model.fit(X_train, y_train)
# 评估print(f"训练集准确率: {model.score(X_train, y_train):.3f}")print(f"测试集准确率: {model.score(X_test, y_test):.3f}")from sklearn.cluster import KMeansfrom sklearn.datasets import make_blobs
# 生成聚类数据X, _ = make_blobs(n_samples=300, centers=3, random_state=42)
# K-Means 聚类kmeans = KMeans(n_clusters=3, random_state=42)labels = kmeans.fit_predict(X)
print(f"聚类中心坐标:\n{kmeans.cluster_centers_}")偏差-方差权衡
Section titled “偏差-方差权衡”这是机器学习中最核心的概念之一:
flowchart TD A[模型复杂度] --> B{平衡点} B -->|太简单| C[高偏差<br/>欠拟合] B -->|太复杂| D[高方差<br/>过拟合] B -->|刚好| E[最佳泛化]过拟合 vs 欠拟合
Section titled “过拟合 vs 欠拟合”import numpy as npfrom sklearn.preprocessing import PolynomialFeaturesfrom sklearn.linear_model import LinearRegressionfrom sklearn.pipeline import make_pipeline
np.random.seed(42)X = np.linspace(0, 10, 20).reshape(-1, 1)y = np.sin(X).ravel() + np.random.randn(20) * 0.2
# 欠拟合:一次多项式——模型太简单model1 = make_pipeline(PolynomialFeatures(1), LinearRegression())model1.fit(X, y)print(f"线性 (欠拟合): R² = {model1.score(X, y):.3f}")
# 过拟合:15 次多项式——模型太复杂model15 = make_pipeline(PolynomialFeatures(15), LinearRegression())model15.fit(X, y)print(f"15 次 (过拟合): R² = {model15.score(X, y):.3f}")
# 适中:3 次多项式model3 = make_pipeline(PolynomialFeatures(3), LinearRegression())model3.fit(X, y)print(f"3 次 (适中): R² = {model3.score(X, y):.3f}")数据量小时,单次划分不可靠。K 折交叉验证多次评估:
flowchart TD subgraph 数据 D1[折1] D2[折2] D3[折3] D4[折4] D5[折5] end
subgraph 第1轮 D1 --> T1[训练] D2 --> T1 D3 --> T1 D4 --> T1 D5 --> V1[验证] endfrom sklearn.model_selection import cross_val_score
scores = cross_val_score(LogisticRegression(), X, y, cv=5)print(f"5 折交叉验证: {scores}")print(f"平均准确率: {scores.mean():.3f} ± {scores.std():.3f}") 预测为正 预测为负实际为正 TP FN ← 漏报实际为负 FP TN ↑ 误报| 指标 | 公式 | 何时用 |
|---|---|---|
| 准确率 | 类别均衡时 | |
| 精确率 | 减少误报(如垃圾邮件检测) | |
| 召回率 | 减少漏报(如疾病筛查) | |
| F1 | 综合衡量(不均衡数据) |
from sklearn.metrics import classification_report
y_true = [1, 0, 1, 1, 0, 1, 0, 0, 1, 0]y_pred = [1, 0, 1, 0, 0, 1, 1, 0, 1, 0]
print(classification_report(y_true, y_pred, target_names=["负类", "正类"]))