数据挖掘与机器学习理论基础:从零构建认知框架的实战指南

1次阅读
没有评论

共计 2094 个字符,预计需要花费 6 分钟才能阅读完成。

image.webp

理论认知框架构建

数据挖掘 2.3 理论体系可以抽象为有向无环图(DAG),核心模块依赖关系如下:

数据挖掘与机器学习理论基础:从零构建认知框架的实战指南

graph LR
A[数据预处理] --> B[特征工程]
B --> C[模型训练]
C --> D[模型评估]
D --> E[部署优化]
  • 数据预处理:包括缺失值处理(Missing Value)、异常值检测(Outlier Detection)等
  • 特征工程:含特征选择(Feature Selection)、特征转换(Feature Transformation)等
  • 模型训练:涉及监督学习(Supervised Learning)、无监督学习(Unsupervised Learning)

关键数学工具实战

1. 信息熵计算

信息熵(Entropy)是衡量系统不确定性的重要指标:

$$H(X) = -\sum_{i=1}^n p(x_i) \log_2 p(x_i)$$

Python 实现示例:

import numpy as np

def entropy(probabilities: np.ndarray) -> float:
    """计算信息熵"""
    return -np.sum(probabilities * np.log2(probabilities))

# 示例:公平硬币抛掷的熵
prob = np.array([0.5, 0.5])
print(f"Entropy: {entropy(prob):.4f} bits")  # 输出 1.0

2. 梯度下降可视化

通过 Matplotlib 实现梯度下降(Gradient Descent)过程展示:

import matplotlib.pyplot as plt

def gradient_descent(
    f: Callable, df: Callable, 
    x0: float, lr: float = 0.1, 
    epochs: int = 50
) -> list:
    """梯度下降过程记录"""
    trajectory = []
    x = x0
    for _ in range(epochs):
        x -= lr * df(x)
        trajectory.append((x, f(x)))
    return trajectory

# 绘制优化路径
plt.plot(*zip(*traj), 'ro-', label='Optimization Path')
plt.contour(X, Y, Z, levels=20)
plt.legend()

生产级特征工程实战

完整 sklearn 流水线示例

from sklearn.pipeline import Pipeline
from sklearn.impute import SimpleImputer, KNNImputer
from sklearn.preprocessing import (
    StandardScaler, 
    KBinsDiscretizer,
    MinMaxScaler
)

# 构建特征处理流水线
feature_pipeline = Pipeline([
    # 缺失值处理策略对比
    ('imputer', SimpleImputer(strategy='median')),  # 中位数填充
    # ('imputer', KNNImputer(n_neighbors=5)),  # KNN 填充
    # ('imputer', SimpleImputer(strategy='constant', fill_value=-1)),  # 常量填充

    # 特征离散化
    ('discretizer', KBinsDiscretizer(
        n_bins=5, 
        encode='ordinal', 
        strategy='quantile'
    )),

    # 特征缩放(标准化适用于高斯分布,归一化适用于有界特征)('scaler', StandardScaler()),  # 标准化
    # ('scaler', MinMaxScaler())    # 归一化
])

避坑指南

数据泄漏预防

  • 始终先拆分训练 / 测试集再做预处理
  • 使用 Pipeline 封装所有转换步骤
  • 避免使用全局统计量(如全体数据的均值)

评估指标陷阱

  • 准确率(Accuracy)在类别不平衡时失效
  • 推荐使用混淆矩阵(Confusion Matrix)+ F1-score 组合

类别不平衡处理

  1. 过采样(Oversampling):SMOTE 算法
  2. 欠采样(Undersampling):Tomek Links
  3. 类别权重(Class Weight):调整损失函数
  4. 异常检测(Anomaly Detection):单类学习
  5. 集成方法(Ensemble):EasyEnsemble

延伸思考:朴素贝叶斯假设

朴素贝叶斯(Naive Bayes)的 ” 朴素 ” 体现在特征条件独立性假设:

$$P(X|Y) = \prod_{i=1}^n P(x_i|Y)$$

证明该假设合理性可考虑:
1. 当特征相关性较低时,近似误差可接受
2. 通过互信息(Mutual Information)量化特征依赖性
3. 实际应用中即使违反假设仍表现良好(参考论文《Naive Bayes at Forty》)

实践建议

建议在 Jupyter Notebook 中逐步运行本文代码示例,配合 %timeit 测量各步骤耗时。对于大于 1GB 的数据集,推荐使用 sklearnpartial_fit方法进行增量学习,避免内存溢出(OOM)。理论理解后,可尝试在 Kaggle 竞赛数据集上实践完整流程。

正文完
 0
评论(没有评论)