蓝色天空网mbsky.com · 知识 · 实践 · 创造机器学习 · 本地阅读预览
教程 / AI / 智能开发 / 机器学习

逻辑回归

核对 Sigmoid 概率映射、对数损失与梯度下降,复现 Iris 二分类与混淆矩阵、验证标准化管道、三分类概率与正则化强度 C,并绘制实测决策边界图。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

Sigmoid 概率映射、对数损失与梯度下降

逻辑回归(Logistic Regression)虽名称带有“回归”,本质上却是面向二分类与多分类任务的判别式概率分类算法,广泛用于垃圾邮件检测、疾病风险预测与客户流失预警。其核心是用 Sigmoid 函数 σ(z) = 1 / (1 + e⁻ᶻ) 将线性得分 z = w·x + b 映射至 (0, 1) 区间表示正类概率:本站实测 σ(0) = 0.5、σ(-4) = 0.0180、σ(4) = 0.9820,严格满足对称恒等式 σ(-z) = 1 - σ(z)。

逻辑回归不采用 MSE(与 Sigmoid 复合后会形成非凸表面),而是最小化二元交叉熵即对数损失函数 L = -(1/m) * Σ[y_i*log(p_i) + (1 - y_i)*log(1 - p_i)]。本站核对手算公式与 sklearn.metrics.log_loss 误差 <1e-12:高置信正确预测对数损失仅 0.1230,而高置信错误预测损失飙升逾 15 倍至 1.9560。

最小化对数损失可通过梯度下降(或 scikit-learn 默认拟牛顿求解器 lbfgs)迭代更新权重 w 与偏置 b:∂L/∂w = (1/m) * Xᵀ(p - y),∂L/∂b = (1/m) * Σ(p - y)。本站在标准化后的 Iris 二分类训练集运行 400 步手动批量梯度下降(lr = 0.5),对数损失由 0.6931 单调降至 0.0362,留出测试集准确率达 100%。

Iris 二分类评估、多分类扩展与决策边界实测

采用内置 Iris 数据集(150 条样本)的前两特征(花萼长、花萼宽)构造二分类标签 y = (target != 0),按 70/30(random_state=42)划分为 105 训练与 45 测试样本(正类 26 条、负类 19 条)。原生 LogisticRegression 与 StandardScaler+LogisticRegression 管道在留出测试集均取得准确率 1.00、正类精确率/召回率/F1 均 1.00、ROC-AUC = 1.00,混淆矩阵为 [[19, 0], [0, 26]],且 predict_proba() 每行概率之和严格为 1.0、以 0.5 为阈值与 predict() 完全一致。

同时验证完整 4 特征三分类 Iris 分层切分与正则化强度 C(C 越小 L2 惩罚越强):C = 1.0 管道留出准确率 0.9111、宏平均 F1 = 0.9107,输出 (45, 3) 概率矩阵行和恒为 1;当 C 由 10.0 降至 0.05 时,权重矩阵 L2 范数由 8.6089 显著收缩至 1.2514。勘误提示:来源总结句中“参数 www 和 bbb”系公式粘贴重复笔误,实际应为权重 w 和偏置 b;来源决策边界图绘制了全量数据且未区分训练/测试集,本站下方独立实测图以不同标记区分训练集与留出测试集并叠加概率等高线。

左图为 Sigmoid 概率映射曲线及 0.5 阈值,右图为 Iris 前两特征逻辑回归概率等高线与训练/测试样本分布。
本站 scikit-learn 1.9.1 实测的 Sigmoid 曲线与 Iris 二分类决策边界图(区分训练集与留出测试集)。

运行逻辑回归 Sigmoid/Log Loss、手动梯度下降、二分类与多分类正则化实测

python · 阅读源码
"""Independent scikit-learn 1.9.1 lab for Logistic Regression (Sigmoid, Log Loss, GD, Iris Binary & Multiclass)."""
import argparse
import hashlib
import json
import platform
from pathlib import Path

import numpy as np
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import (
    accuracy_score,
    confusion_matrix,
    f1_score,
    log_loss,
    precision_score,
    recall_score,
    roc_auc_score,
)
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler


def sha(path: Path) -> str:
    return hashlib.sha256(path.read_bytes()).hexdigest()


def sigmoid(z: np.ndarray) -> np.ndarray:
    return 1.0 / (1.0 + np.exp(-np.clip(z, -500.0, 500.0)))


def run_cases(fig_dir: Path | None):
    cases = []
    figures = {}

    # 1. Sigmoid properties & binary cross-entropy (Log Loss) verification
    z_pts = np.array([-4.0, -1.0, 0.0, 1.0, 4.0])
    s_pts = sigmoid(z_pts)
    sym_err = float(np.max(np.abs((s_pts + s_pts[::-1]) - 1.0)))
    y_true = np.array([1, 0, 1, 0])
    p_good = np.array([0.92, 0.08, 0.85, 0.15])
    p_bad = np.array([0.10, 0.90, 0.20, 0.80])
    manual_ll = float(-np.mean(y_true * np.log(p_good) + (1 - y_true) * np.log(1 - p_good)))
    sk_ll = float(log_loss(y_true, p_good))
    bad_ll = float(log_loss(y_true, p_bad))

    c1_ok = abs(float(s_pts[2]) - 0.5) < 1e-12 and sym_err < 1e-12 and abs(manual_ll - sk_ll) < 1e-12 and bad_ll > sk_ll * 10
    cases.append(dict(
        name="sigmoid_and_log_loss_math",
        inputs=dict(z_points=[-4.0, -1.0, 0.0, 1.0, 4.0]),
        prerequisites="核对 Sigmoid 概率映射对称性与二元交叉熵(Log Loss)对高置信错误预测的重惩罚特性。",
        action="验证 σ(0)=0.5、σ(-z)=1-σ(z)、手算对数损失与 sklearn log_loss 一致且错误预测损失远高于正确预测。",
        expected=dict(sigmoid_zero_half=True, symmetry_exact=True, log_loss_exact=True, bad_pred_penalized=True),
        actual=dict(
            sigmoid_zero_half=abs(float(s_pts[2]) - 0.5) < 1e-12,
            symmetry_exact=sym_err < 1e-12,
            log_loss_exact=abs(manual_ll - sk_ll) < 1e-12,
            bad_pred_penalized=bad_ll > sk_ll * 10,
        ),
        measurements=dict(
            good_log_loss=round(sk_ll, 4),
            bad_log_loss=round(bad_ll, 4),
            sig_m4=round(float(s_pts[0]), 4),
            sig_p4=round(float(s_pts[4]), 4),
        ),
        passed=c1_ok,
    ))

    # Binary Iris setup (first 2 features, class 0 vs rest)
    iris = load_iris()
    x_bin = iris.data[:, :2]
    y_bin = (iris.target != 0).astype(int)
    xb_tr, xb_te, yb_tr, yb_te = train_test_split(x_bin, y_bin, test_size=0.3, random_state=42)

    # 2. Manual batch gradient descent for Logistic Regression on standardized train set
    scaler = StandardScaler().fit(xb_tr)
    xs_tr = scaler.transform(xb_tr)
    xs_te = scaler.transform(xb_te)
    w = np.zeros(xs_tr.shape[1])
    b = 0.0
    lr = 0.5
    gd_losses = []
    for _ in range(400):
        p = sigmoid(xs_tr @ w + b)
        p_clip = np.clip(p, 1e-12, 1 - 1e-12)
        gd_losses.append(float(-np.mean(yb_tr * np.log(p_clip) + (1 - yb_tr) * np.log(1 - p_clip))))
        err = p - yb_tr
        w -= lr * (xs_tr.T @ err) / len(yb_tr)
        b -= lr * float(np.mean(err))
    gd_pred_te = (sigmoid(xs_te @ w + b) >= 0.5).astype(int)
    gd_acc = float(accuracy_score(yb_te, gd_pred_te))
    monotone = all(gd_losses[i + 1] <= gd_losses[i] + 1e-12 for i in range(len(gd_losses) - 1))
    c2_ok = monotone and gd_losses[-1] < gd_losses[0] * 0.1 and gd_acc >= 0.95
    cases.append(dict(
        name="manual_gd_vs_sklearn_logistic",
        inputs=dict(lr=0.5, steps=400, train_samples=len(xb_tr), test_samples=len(xb_te)),
        prerequisites="在仅由训练集拟合的 StandardScaler 空间运行手动批量梯度下降最小化 Log Loss。",
        action="验证对数损失单调收敛至初值 10% 以下,且留出测试集二分类准确率 >=95%。",
        expected=dict(loss_monotone=True, loss_converged=True, gd_test_acc_ge_095=True),
        actual=dict(loss_monotone=monotone, loss_converged=gd_losses[-1] < gd_losses[0] * 0.1, gd_test_acc_ge_095=gd_acc >= 0.95),
        measurements=dict(
            init_log_loss=round(gd_losses[0], 4),
            final_log_loss=round(gd_losses[-1], 4),
            gd_test_acc=round(gd_acc, 4),
            w_gd=[round(float(v), 4) for v in w],
            b_gd=round(float(b), 4),
        ),
        passed=c2_ok,
    ))

    # 3. Iris binary classification with sklearn LogisticRegression (raw & scaled pipeline) + metrics
    clf_raw = LogisticRegression().fit(xb_tr, yb_tr)
    pred_raw = clf_raw.predict(xb_te)
    proba_raw = clf_raw.predict_proba(xb_te)
    acc_raw = float(accuracy_score(yb_te, pred_raw))
    cm_raw = confusion_matrix(yb_te, pred_raw).tolist()
    prec = float(precision_score(yb_te, pred_raw, pos_label=1))
    rec = float(recall_score(yb_te, pred_raw, pos_label=1))
    f1 = float(f1_score(yb_te, pred_raw, pos_label=1))
    auc = float(roc_auc_score(yb_te, proba_raw[:, 1]))

    clf_scaled = make_pipeline(StandardScaler(), LogisticRegression()).fit(xb_tr, yb_tr)
    acc_scaled = float(accuracy_score(yb_te, clf_scaled.predict(xb_te)))
    prob_sum_ok = bool(np.allclose(proba_raw.sum(axis=1), 1.0, atol=1e-12))
    thresh_matches = bool(np.array_equal((proba_raw[:, 1] >= 0.5).astype(int), pred_raw))

    c3_ok = acc_raw == 1.0 and acc_scaled == 1.0 and prob_sum_ok and thresh_matches and cm_raw == [[19, 0], [0, 26]]
    cases.append(dict(
        name="iris_binary_classification_and_metrics",
        inputs=dict(features="sepal_length, sepal_width", positive_class="target != 0", test_size=0.3, random_state=42),
        prerequisites="复现 Iris 二分类划分(45 条测试集:19 负类、26 正类)并对照带标准化管道。",
        action="验证测试集准确率 1.00、混淆矩阵 [[19,0],[0,26]]、概率行和为 1 且 0.5 阈值与 predict 一致。",
        expected=dict(raw_acc=1.0, scaled_acc=1.0, confusion_matrix=[[19, 0], [0, 26]], prob_contract_ok=True),
        actual=dict(raw_acc=acc_raw, scaled_acc=acc_scaled, confusion_matrix=cm_raw, prob_contract_ok=(prob_sum_ok and thresh_matches)),
        measurements=dict(precision_pos1=prec, recall_pos1=rec, f1_pos1=f1, roc_auc=auc),
        passed=c3_ok,
    ))

    # 4. Multiclass (3-class Iris, 4 features) & regularization strength C effect on weight norm
    xm_tr, xm_te, ym_tr, ym_te = train_test_split(
        iris.data, iris.target, test_size=0.3, random_state=42, stratify=iris.target
    )
    pipe_weak_reg = make_pipeline(StandardScaler(), LogisticRegression(C=10.0)).fit(xm_tr, ym_tr)
    pipe_strong_reg = make_pipeline(StandardScaler(), LogisticRegression(C=0.05)).fit(xm_tr, ym_tr)
    norm_c10 = float(np.linalg.norm(pipe_weak_reg.named_steps["logisticregression"].coef_))
    norm_c005 = float(np.linalg.norm(pipe_strong_reg.named_steps["logisticregression"].coef_))

    pipe_mc = make_pipeline(StandardScaler(), LogisticRegression(C=1.0)).fit(xm_tr, ym_tr)
    mc_proba = pipe_mc.predict_proba(xm_te)
    mc_pred = pipe_mc.predict(xm_te)
    mc_acc = float(accuracy_score(ym_te, mc_pred))
    mc_macro_f1 = float(f1_score(ym_te, mc_pred, average="macro"))
    mc_cm = confusion_matrix(ym_te, mc_pred)

    c4_ok = mc_proba.shape == (45, 3) and bool(np.allclose(mc_proba.sum(axis=1), 1.0)) and norm_c005 < norm_c10 * 0.5 and mc_acc >= 0.90
    cases.append(dict(
        name="multiclass_softmax_and_regularization_c",
        inputs=dict(classes=3, features=4, C_values=[0.05, 1.0, 10.0]),
        prerequisites="在完整 4 特征三分类 Iris 分层切分上验证多项逻辑回归概率与正则化强度 C。",
        action="验证三分类概率行和为 1、测试准确率 >=90%,且更小 C(更强 L2 惩罚)大幅压低权重 L2 范数。",
        expected=dict(proba_shape=[45, 3], strong_reg_shrinks_weights=True, multiclass_acc_ge_090=True),
        actual=dict(
            proba_shape=list(mc_proba.shape),
            strong_reg_shrinks_weights=norm_c005 < norm_c10 * 0.5,
            multiclass_acc_ge_090=mc_acc >= 0.90,
        ),
        measurements=dict(
            mc_test_acc=round(mc_acc, 4),
            mc_macro_f1=round(mc_macro_f1, 4),
            cm_shape=list(mc_cm.shape),
            weight_norm_c10=round(norm_c10, 4),
            weight_norm_c005=round(norm_c005, 4),
        ),
        passed=c4_ok,
    ))

    # 5. Clean Matplotlib PNG chart: Sigmoid curve + Binary Iris decision boundary (train vs test distinct)
    mpl_ver = None
    if fig_dir is not None:
        import matplotlib
        matplotlib.use("Agg")
        import matplotlib.pyplot as plt

        fig_dir.mkdir(parents=True, exist_ok=True)
        fig, axes = plt.subplots(1, 2, figsize=(9.8, 3.9), dpi=140)

        zs = np.linspace(-6.0, 6.0, 200)
        axes[0].plot(zs, sigmoid(zs), color="#174d79", lw=2.2, label="Sigmoid sigma(z)")
        axes[0].axhline(0.5, color="#ae511d", ls="--", lw=1.1, label="Threshold p=0.5 (z=0)")
        axes[0].axvline(0.0, color="#666666", ls=":", lw=1.0)
        axes[0].set_title("Sigmoid Probability Mapping", fontsize=10)
        axes[0].set_xlabel("Linear score z = w*x + b")
        axes[0].set_ylabel("Probability P(y=1 | x)")
        axes[0].grid(True, alpha=0.3)
        axes[0].legend(fontsize=8)

        x_min, x_max = xb_tr[:, 0].min() - 0.6, xb_tr[:, 0].max() + 0.6
        y_min, y_max = xb_tr[:, 1].min() - 0.6, xb_tr[:, 1].max() + 0.6
        xx, yy = np.meshgrid(np.linspace(x_min, x_max, 180), np.linspace(y_min, y_max, 180))
        grid_p = clf_scaled.predict_proba(np.c_[xx.ravel(), yy.ravel()])[:, 1].reshape(xx.shape)
        axes[1].contourf(xx, yy, grid_p, levels=np.linspace(0, 1, 11), cmap="RdBu_r", alpha=0.45)
        axes[1].contour(xx, yy, grid_p, levels=[0.5], colors=["#111111"], linewidths=1.8)
        axes[1].scatter(xb_tr[:, 0], xb_tr[:, 1], c=yb_tr, cmap="bwr", edgecolors="k", s=24, alpha=0.8, label="Train (n=105)")
        axes[1].scatter(xb_te[:, 0], xb_te[:, 1], c=yb_te, cmap="bwr", marker="^", edgecolors="#111111", s=42, label="Test (n=45)")
        axes[1].set_title("Binary Iris Decision Boundary (Test Acc=1.00)", fontsize=10)
        axes[1].set_xlabel("Sepal length (cm)")
        axes[1].set_ylabel("Sepal width (cm)")
        axes[1].legend(fontsize=8, loc="upper right")

        fig.tight_layout()
        out_png = fig_dir / "logistic-decision-boundary.png"
        fig.savefig(out_png)
        plt.close(fig)
        figures["logistic-decision-boundary.png"] = sha(out_png)
        mpl_ver = matplotlib.__version__

    cases.append(dict(
        name="observed_logistic_boundary_plot",
        inputs=dict(train_samples=len(xb_tr), test_samples=len(xb_te)),
        prerequisites="基于训练集拟合的标准化逻辑回归绘制 Sigmoid 曲线与留出区分的决策边界图。",
        action="输出 Sigmoid 与 Iris 二分类概率等高线图并核对样本范围。",
        expected=dict(train_plus_test=150),
        actual=dict(train_plus_test=len(xb_tr) + len(xb_te)),
        measurements=dict(figure_generated="logistic-decision-boundary.png" in figures),
        passed=(len(xb_tr) + len(xb_te) == 150),
    ))

    payload = dict(version=platform.python_version(), system=platform.system(), cases=cases)
    if mpl_ver:
        payload["matplotlib"] = mpl_ver
        payload["figures"] = figures
    print(json.dumps(payload, ensure_ascii=False))


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("--figures", type=Path, default=None)
    args = parser.parse_args()
    run_cases(args.figures)
预期结果 · 待实际运行核验
  • 核对 Sigmoid 对称性与 log_loss 精确公式、手动 GD 单调收敛至 0.0362、Iris 二分类混淆矩阵 [[19,0],[0,26]]、三分类概率与 C 收缩权重范数,并绘制 Sigmoid 与决策边界双联图。
运行逻辑回归 Sigmoid/Log Loss、手动梯度下降、二分类与多分类正则化实测

所需环境: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。

当前源码 SHA256:ecde2c0bb31987a731fc6f133661e1ce87837ca13d7862baa22928648cf546c4

下载本站示例源码

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载逻辑回归实验

所需环境: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。

ZIP SHA256:a9c43bcbfff06563ea8dc93252d4c6e932cb6a400176165cdb737c44de371d53

常见错误与边界

  • 实际端口、文档资源与应用配置都应和测试条件一致。

练习与解答

为什么逻辑回归的正则化超参数 C 调小时,模型权重范数会变小且更不易过拟合?

展开参考解答

scikit-learn 中 C 表示正则化强度的倒数(优化目标近似为 C * LogLoss + 0.5 * ||w||₂²),因此 C 越小意味着对大权重的 L2 惩罚越重,迫使参数收缩以降低方差。

规范与官方依据