"""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)
本例需在 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-logistic-regression-lab/explore-logistic-regression.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-logistic-regression.py,或下载右侧课程工程包。 - 确认本地已准备 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。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联58章) · 含当前章节或实例 · mbskycom202612a449.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a481.zip