蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

运行稀有病贝叶斯序贯更新、朴素贝叶斯、MLE/MAP 与贝叶斯置信区间实测

PYTHONWindows x64 CPU、CPython 3.12.14、NumPy 2.5.4、SciPy 1.18.1、scikit-learn 1.9.1、pandas 3.1.0、Matplotlib 3.11.2。explore-probabilistic-thinking.py
explore-probabilistic-thinking.py223 行
"""Independent offline lab for ML Ch 17: Probabilistic Thinking (Bayes, Naive Bayes, MLE vs MAP, Uncertainty)."""
import json
import platform

import numpy as np
from sklearn.datasets import load_iris
from sklearn.linear_model import BayesianRidge, LinearRegression, LogisticRegression, Ridge
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import MultinomialNB


def main():
    cases = []

    # 1. Medical screening Bayes' theorem & sequential Bayesian updating
    p_disease = 0.001
    p_pos_given_dis = 0.99
    p_neg_given_healthy = 0.99
    p_healthy = 1.0 - p_disease
    p_pos_given_healthy = 1.0 - p_neg_given_healthy
    p_pos = p_pos_given_dis * p_disease + p_pos_given_healthy * p_healthy
    post1 = (p_pos_given_dis * p_disease) / p_pos

    # Second independent positive test uses post1 as new prior
    p_pos2 = p_pos_given_dis * post1 + p_pos_given_healthy * (1.0 - post1)
    post2 = (p_pos_given_dis * post1) / p_pos2

    c1_ok = (
        abs(p_pos - 0.01098) < 1e-12
        and abs(post1 - (0.00099 / 0.01098)) < 1e-12
        and 0.09 < post1 < 0.091
        and post2 > 0.90
    )
    cases.append(
        dict(
            name="bayes_medical_test_and_sequential_update",
            inputs=dict(prior_disease=p_disease, sensitivity=p_pos_given_dis, specificity=p_neg_given_healthy),
            prerequisites="罕见病基础发病率 P(病)=0.001,灵敏度与特异度均为 0.99。",
            action="按全概率公式与贝叶斯定理计算单次阳性后验概率,并继续计算第二次独立阳性后的序贯更新后验。",
            expected=dict(p_positive_exact=0.01098, post1_pct_approx_902=True, post2_gt_90pct=True),
            actual=dict(
                p_positive_exact=round(p_pos, 5),
                post1_pct_approx_902=(round(post1, 4) == 0.0902),
                post2_gt_90pct=(post2 > 0.90),
            ),
            measurements=dict(
                p_positive=round(p_pos, 6),
                posterior_after_1_pos=round(post1, 6),
                posterior_after_2_pos=round(post2, 6),
            ),
            passed=c1_ok,
        )
    )

    # 2. Naive Bayes manual score + sklearn MultinomialNB & LogisticRegression predict_proba
    score_spam = 0.8 * 0.1 * 0.3
    score_ham = 0.1 * 0.9 * 0.7
    z_norm = score_spam + score_ham
    p_spam_norm = round(score_spam / z_norm, 4)
    p_ham_norm = round(score_ham / z_norm, 4)

    # Real MultinomialNB on synthetic 2-feature bag-of-words counts [free_count, meeting_count]
    X_bow = np.array(
        [
            [3, 0], [2, 0], [4, 1], [3, 0], [2, 1],  # spam (1)
            [0, 3], [0, 2], [1, 4], [0, 3], [1, 2],  # ham (0)
        ]
    )
    y_bow = np.array([1, 1, 1, 1, 1, 0, 0, 0, 0, 0])
    mnb = MultinomialNB(alpha=1.0).fit(X_bow, y_bow)
    nb_probs = mnb.predict_proba(np.array([[3, 0], [0, 3]]))

    iris = load_iris()
    X_bin, y_bin = iris.data[iris.target != 2], iris.target[iris.target != 2]
    X_tr, X_te, y_tr, y_te = train_test_split(X_bin, y_bin, test_size=0.2, stratify=y_bin, random_state=42)
    lr = LogisticRegression(max_iter=500, random_state=42).fit(X_tr, y_tr)
    lr_probs = lr.predict_proba(X_te)
    probs_valid = bool(
        np.allclose(nb_probs.sum(axis=1), 1.0)
        and np.allclose(lr_probs.sum(axis=1), 1.0)
        and (lr_probs >= 0.0).all()
        and (lr_probs <= 1.0).all()
    )
    c2_ok = (
        round(score_spam, 4) == 0.024
        and round(score_ham, 4) == 0.063
        and score_ham > score_spam
        and int(mnb.predict(np.array([[3, 0]]))[0]) == 1
        and int(mnb.predict(np.array([[0, 3]]))[0]) == 0
        and probs_valid
    )
    cases.append(
        dict(
            name="naive_bayes_and_logistic_probabilities",
            inputs=dict(manual_words=["免费", "会议"], bow_train_docs=10, iris_binary_test=len(X_te)),
            prerequisites="核对正文手算贝叶斯邮件判别得分与 sklearn MultinomialNB / LogisticRegression 概率输出。",
            action="验证手算 score_垃圾=0.024 < score_正常=0.063,归一化后验和为 1,两类 sklearn 模型输出合法概率分布。",
            expected=dict(
                manual_spam_score=0.024,
                manual_ham_score=0.063,
                manual_pred="ham",
                sklearn_probs_valid=True,
            ),
            actual=dict(
                manual_spam_score=round(score_spam, 4),
                manual_ham_score=round(score_ham, 4),
                manual_pred=("spam" if score_spam > score_ham else "ham"),
                sklearn_probs_valid=probs_valid,
            ),
            measurements=dict(
                normalized_spam_prob=p_spam_norm,
                normalized_ham_prob=p_ham_norm,
                mnb_spam_doc_prob=round(float(nb_probs[0, 1]), 4),
                mnb_ham_doc_prob=round(float(nb_probs[1, 0]), 4),
                lr_test_accuracy=round(float(lr.score(X_te, y_te)), 4),
            ),
            passed=c2_ok,
        )
    )

    # 3. MLE vs MAP estimation (Bernoulli Beta prior & Gaussian linear regression OLS vs Ridge)
    k_heads, n_flips = 4, 5
    p_mle = k_heads / n_flips
    alpha_prior, beta_prior = 3.0, 3.0  # symmetric prior centered at 0.5
    p_map = (k_heads + alpha_prior - 1.0) / (n_flips + alpha_prior + beta_prior - 2.0)

    rng = np.random.default_rng(202617)
    X_reg = rng.normal(0.0, 1.0, size=(24, 6))
    X_reg[:, 1] = X_reg[:, 0] + rng.normal(0.0, 0.05, size=24)  # collinearity makes OLS weights larger
    true_w = np.array([1.5, 1.5, -1.0, 0.5, 0.0, 0.0])
    y_reg = X_reg @ true_w + rng.normal(0.0, 0.8, size=24)
    ols = LinearRegression().fit(X_reg, y_reg)
    ridge = Ridge(alpha=5.0).fit(X_reg, y_reg)
    ols_norm = float(np.linalg.norm(ols.coef_))
    ridge_norm = float(np.linalg.norm(ridge.coef_))

    c3_ok = (
        abs(p_mle - 0.8) < 1e-12
        and abs(p_map - (6.0 / 9.0)) < 1e-12
        and abs(p_map - 0.5) < abs(p_mle - 0.5)
        and ridge_norm < ols_norm
    )
    cases.append(
        dict(
            name="mle_vs_map_estimation",
            inputs=dict(coin_heads=4, coin_flips=5, beta_prior=[3, 3], ridge_alpha=5.0),
            prerequisites="对比小样本抛硬币的 MLE 与 Beta(3,3) 先验 MAP,以及共线性回归中 OLS(MLE) 与 Ridge(高斯先验 MAP)。",
            action="验证 MAP 将硬币正面概率由 MLE=0.8000 向先验 0.5 拉回至 0.6667,且 Ridge 权重 L2 范数严格小于 OLS。",
            expected=dict(
                coin_mle=0.8,
                coin_map=0.6667,
                map_closer_to_prior=True,
                ridge_shrinks_l2_norm=True,
            ),
            actual=dict(
                coin_mle=round(p_mle, 4),
                coin_map=round(p_map, 4),
                map_closer_to_prior=(abs(p_map - 0.5) < abs(p_mle - 0.5)),
                ridge_shrinks_l2_norm=(ridge_norm < ols_norm),
            ),
            measurements=dict(
                ols_weight_l2_norm=round(ols_norm, 4),
                ridge_weight_l2_norm=round(ridge_norm, 4),
            ),
            passed=c3_ok,
        )
    )

    # 4. Decision thresholding on classification probabilities & BayesianRidge predictive intervals
    X_clf = rng.normal(0.0, 1.0, size=(300, 2))
    logits = 1.8 * X_clf[:, 0] - 1.2 * X_clf[:, 1]
    y_clf = (rng.random(300) < (1.0 / (1.0 + np.exp(-logits)))).astype(int)
    X_ctr, X_cte, y_ctr, y_cte = train_test_split(X_clf, y_clf, test_size=0.3, stratify=y_clf, random_state=42)
    clf = LogisticRegression(random_state=42).fit(X_ctr, y_ctr)
    proba_te = clf.predict_proba(X_cte)
    max_p = proba_te.max(axis=1)
    preds = proba_te.argmax(axis=1)
    all_acc = float((preds == y_cte).mean())
    hi_mask = max_p >= 0.8
    hi_acc = float((preds[hi_mask] == y_cte[hi_mask]).mean())

    X_br = np.linspace(0.0, 10.0, 120).reshape(-1, 1)
    y_br = 2.5 * X_br[:, 0] + 10.0 + rng.normal(0.0, 2.0, size=120)
    Xb_tr, Xb_te, yb_tr, yb_te = train_test_split(X_br, y_br, test_size=0.25, random_state=42)
    br = BayesianRidge().fit(Xb_tr, yb_tr)
    y_mean, y_std = br.predict(Xb_te, return_std=True)
    within_95 = float(np.mean(np.abs(yb_te - y_mean) <= 1.96 * y_std))

    c4_ok = hi_mask.sum() > 10 and hi_acc > all_acc and bool((y_std > 0).all()) and within_95 >= 0.85
    cases.append(
        dict(
            name="confidence_threshold_and_bayesian_regression",
            inputs=dict(prob_threshold=0.8, bayes_reg_samples=120),
            prerequisites="分类任务按置信度阈值 0.8 拒识低信心样本;回归任务用 BayesianRidge 输出均值与预测标准差。",
            action="验证高置信度子集准确率高于全量测试集,且 BayesianRidge 95% 预测区间有效覆盖留出真实值。",
            expected=dict(high_conf_improves_acc=True, predictive_std_positive=True, interval_coverage_ge_85pct=True),
            actual=dict(
                high_conf_improves_acc=(hi_acc > all_acc),
                predictive_std_positive=bool((y_std > 0).all()),
                interval_coverage_ge_85pct=(within_95 >= 0.85),
            ),
            measurements=dict(
                all_test_acc=round(all_acc, 4),
                high_conf_count=int(hi_mask.sum()),
                high_conf_acc=round(hi_acc, 4),
                mean_predictive_std=round(float(y_std.mean()), 4),
                empirical_95pct_coverage=round(within_95, 4),
            ),
            passed=c4_ok,
        )
    )

    payload = dict(
        version=platform.python_version(),
        system=platform.system(),
        cases=cases,
    )
    print(json.dumps(payload, ensure_ascii=False))


if __name__ == "__main__":
    main()
本例需在 Windows x64 CPU、CPython 3.12.14、NumPy 2.5.4、SciPy 1.18.1、scikit-learn 1.9.1、pandas 3.1.0、Matplotlib 3.11.2。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64 CPU、CPython 3.12.14、NumPy 2.5.4、SciPy 1.18.1、scikit-learn 1.9.1、pandas 3.1.0、Matplotlib 3.11.2。

入口文件:projects/ml-probabilistic-thinking-lab/explore-probabilistic-thinking.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-probabilistic-thinking.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64 CPU、CPython 3.12.14、NumPy 2.5.4、SciPy 1.18.1、scikit-learn 1.9.1、pandas 3.1.0、Matplotlib 3.11.2。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:机器学习

课程关联工程包(登记关联58章) · 含当前章节或实例 · mbskycom202612a449.zip

下载课程关联工程包:机器学习

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a493.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习