机器学习中的概率统计应用实践 | 更新完结

72 阅读5分钟

t045d6a21c3c0e6884d.jpg

机器学习中的概率统计应用实践 | 更新完结---youkeit.xyz/4823/

面向学习者的机器学习概率统计实践:核心应用与教学案例解析

1. 概率统计基础回顾

在机器学习中,概率统计是构建模型和理解数据的核心工具。让我们先回顾几个关键概念:

  • 随机变量:描述随机现象结果的变量
  • 概率分布:描述随机变量取不同值的概率
  • 期望与方差:衡量分布的中心位置和离散程度
  • 条件概率与贝叶斯定理:处理事件间依赖关系的基础
import numpy as np
import matplotlib.pyplot as plt
from scipy import stats

# 生成正态分布随机变量
mu, sigma = 0, 1 # 均值和标准差
normal_data = np.random.normal(mu, sigma, 1000)

# 绘制概率密度函数
count, bins, ignored = plt.hist(normal_data, 30, density=True)
plt.plot(bins, 1/(sigma * np.sqrt(2 * np.pi)) *
         np.exp(-(bins - mu)**2 / (2 * sigma**2)),
         linewidth=2, color='r')
plt.title("正态分布概率密度函数")
plt.show()

2. 机器学习中的概率模型应用

2.1 朴素贝叶斯分类器

朴素贝叶斯是基于贝叶斯定理的特征条件独立假设的分类方法。

from sklearn.datasets import load_iris
from sklearn.naive_bayes import GaussianNB
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score

# 加载鸢尾花数据集
iris = load_iris()
X = iris.data
y = iris.target

# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)

# 创建并训练朴素贝叶斯模型
gnb = GaussianNB()
gnb.fit(X_train, y_train)

# 预测并评估
y_pred = gnb.predict(X_test)
print(f"朴素贝叶斯分类准确率: {accuracy_score(y_test, y_pred):.2f}")

2.2 高斯混合模型(GMM)

GMM是一种概率模型,假设所有数据点都是从有限个高斯分布的混合中生成的。

from sklearn.mixture import GaussianMixture
from sklearn.datasets import make_blobs

# 生成模拟数据
X, y_true = make_blobs(n_samples=300, centers=4,
                       cluster_std=0.60, random_state=0)

# 创建并拟合GMM模型
gmm = GaussianMixture(n_components=4, random_state=42)
gmm.fit(X)
labels = gmm.predict(X)

# 可视化结果
plt.scatter(X[:, 0], X[:, 1], c=labels, s=40, cmap='viridis')
plt.title("高斯混合模型聚类结果")
plt.show()

3. 统计假设检验在模型评估中的应用

3.1 t检验比较模型性能

from scipy.stats import ttest_ind

# 假设有两个模型的准确率结果
model1_acc = np.random.normal(0.85, 0.05, 30)  # 模型1的30次实验准确率
model2_acc = np.random.normal(0.88, 0.05, 30)  # 模型2的30次实验准确率

# 执行独立样本t检验
t_stat, p_val = ttest_ind(model1_acc, model2_acc)

print(f"t统计量: {t_stat:.4f}")
print(f"p值: {p_val:.4f}")

if p_val < 0.05:
    print("两个模型性能有显著差异 (p < 0.05)")
else:
    print("两个模型性能无显著差异")

3.2 卡方检验用于特征选择

from sklearn.feature_selection import SelectKBest, chi2
from sklearn.datasets import load_breast_cancer

# 加载乳腺癌数据集
data = load_breast_cancer()
X, y = data.data, data.target

# 使用卡方检验选择最好的5个特征
chi2_selector = SelectKBest(chi2, k=5)
X_kbest = chi2_selector.fit_transform(X, y)

print("原始特征数:", X.shape[1])
print("选择后的特征数:", X_kbest.shape[1])

4. 贝叶斯优化在超参数调优中的应用

from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import cross_val_score
from bayes_opt import BayesianOptimization

# 定义目标函数
def rf_cv(n_estimators, max_depth, min_samples_split):
    model = RandomForestClassifier(
        n_estimators=int(n_estimators),
        max_depth=int(max_depth),
        min_samples_split=int(min_samples_split),
        random_state=42
    )
    return cross_val_score(model, X_train, y_train, cv=5, scoring='accuracy').mean()

# 设置参数范围
pbounds = {
    'n_estimators': (50, 250),
    'max_depth': (5, 30),
    'min_samples_split': (2, 25)
}

# 创建优化器
optimizer = BayesianOptimization(
    f=rf_cv,
    pbounds=pbounds,
    random_state=42,
)

# 执行优化
optimizer.maximize(init_points=5, n_iter=15)

# 输出最佳参数
print(optimizer.max)

5. 概率图模型实践:隐马尔可夫模型

from hmmlearn import hmm
import numpy as np

# 准备观测序列
observations = np.array([[0], [1], [0], [1], [0], [0], [1], [1], [0], [1]])

# 创建并训练HMM模型
model = hmm.GaussianHMM(n_components=2, covariance_type="diag", n_iter=100)
model.fit(observations)

# 预测隐藏状态
hidden_states = model.predict(observations)
print("预测的隐藏状态序列:", hidden_states)

# 生成新序列
new_observations, new_states = model.sample(5)
print("生成的新观测序列:", new_observations.flatten())

6. 教学案例:基于概率的推荐系统

import pandas as pd
from collections import defaultdict

# 模拟用户-物品交互数据
data = {
    'user_id': [1, 1, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4],
    'item_id': [101, 102, 103, 101, 103, 101, 102, 104, 105, 102, 103, 105]
}
df = pd.DataFrame(data)

# 计算物品共现矩阵
cooccurrence = defaultdict(lambda: defaultdict(int))
item_counts = defaultdict(int)

for user, group in df.groupby('user_id'):
    items = group['item_id'].tolist()
    for i in range(len(items)):
        item_counts[items[i]] += 1
        for j in range(i+1, len(items)):
            cooccurrence[items[i]][items[j]] += 1
            cooccurrence[items[j]][items[i]] += 1

# 计算条件概率(推荐概率)
def get_recommendations(target_item, n=3):
    recommendations = []
    for item, count in cooccurrence[target_item].items():
        prob = count / item_counts[target_item]
        recommendations.append((item, prob))
    
    # 按概率降序排序
    recommendations.sort(key=lambda x: -x[1])
    return recommendations[:n]

# 为物品101推荐相关物品
print("为物品101推荐的物品及概率:")
for item, prob in get_recommendations(101):
    print(f"物品{item}: {prob:.2f}")

7. 总结与进阶方向

本文介绍了机器学习中概率统计的核心应用和实践案例。关键要点包括:

  1. 概率模型(朴素贝叶斯、GMM、HMM)的构建与应用
  2. 统计假设检验在模型评估中的作用
  3. 贝叶斯方法在超参数优化中的应用
  4. 基于概率的推荐系统实现

进阶学习方向

  • 贝叶斯神经网络
  • 概率编程(Pyro、PyMC3)
  • 变分自编码器(VAE)
  • 马尔可夫链蒙特卡洛(MCMC)方法

概率统计为机器学习提供了坚实的理论基础和强大的建模工具,深入理解这些概念将帮助你构建更健壮、可解释的机器学习系统。