AI4M
AI for Materials Science 材料人工智能实战课程 · 研究生课程门户

Module 02 · Lecture 02a · 经典机器学习与探索

02a · 线性回归与正则化:正规方程、梯度下降、偏差–方差与共线性驯服

02a_regression_and_regularization.ipynb733.0 KB

Open In Colab

02a · 线性回归与正则化:正规方程、梯度下降、偏差–方差与共线性驯服

在第一模块(01a–01d)中,我们已经完成了 AqSolDB 水溶解度数据集的纯字符串去盐清洗,得到了 8,438 个纯净单组分有机分子及其预计算的 17 个物理化学描述符。从本节开始,我们正式进入监督学习(Supervised Learning),不把模型当黑箱,而是亲手揭开回归算法底层的三个核心问题:

  1. 模型参数到底是怎么求出来的?——矩阵解析解**正规方程(Normal Equations)与深度学习通用的梯度下降(Gradient Descent)**各有什么优劣?
  2. 为什么模型自由度太高反而预测更差?——怎样从数学和图像上彻底看懂多项式扩展与偏差–方差分解(Bias–Variance Decomposition)?
  3. 当 17 个分子描述符之间高度共线时,为什么普通最小二乘(OLS)权重会正负颠倒失控?——怎样用 Ridge (\(L_2\))、Lasso (\(L_1\)) 与 ElasticNet 给失控权重套上缰绳?

本节内容

  1. 纯净单组分 AqSolDB 数据构建、8:2 闭卷测试集划分与回归三大指标(MAE / RMSE / \(R^2\))
  2. 最小二乘法的两条求解路径:正规方程解析解 \((\mathbf{X}^\top\mathbf{X})^{-1}\mathbf{X}^\top\mathbf{y}\) vs 8 行 NumPy 手写梯度下降
  3. 多项式特征扩展与偏差–方差误差分解(Bias–Variance Trade-off)
  4. 17 维多元线性回归、对角线图(Parity Plot)与多重共线性权重反转破案
  5. Ridge (\(L_2\))、Lasso (\(L_1\)) 与 ElasticNet:几何约束直觉与正则化路径对比
In [1] · Python
# colab-setup (本地运行时自动跳过)
import os, sys

if "google.colab" in sys.modules:
    _repo_dir = "/content/ai-for-materials"
    if not os.path.exists(_repo_dir):
        os.system("git clone --depth 1 https://github.com/Zeshengliu213/ai-for-materials.git " + _repo_dir)
    os.chdir(os.path.join(_repo_dir, "02 - Supervised Learning"))

0. 环境准备与课程统一绘图风格

In [2] · Python
import os, pathlib, sys
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import sklearn
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler, PolynomialFeatures
from sklearn.pipeline import make_pipeline
from sklearn.linear_model import LinearRegression, Ridge, Lasso, ElasticNet
from sklearn.metrics import mean_absolute_error, root_mean_squared_error, r2_score

sys.path.insert(0, str(pathlib.Path.cwd().parent))
import ai4m_style as ai4m
C = ai4m.use()
print(f"scikit-learn: {sklearn.__version__} | Environment ready!")
Out:
scikit-learn: 1.8.0 | Environment ready!

1. 数据准备、训练/测试划分与回归评估基线

遵循 01c 建立的数据清洗规范,我们用纯 Pandas 字符串过滤 ~df["SMILES"].str.contains(r"\.", na=False) 剥离多组分盐类与水合物,保留 8,438 个单组分有机分子,提取 17 列物理化学描述符构成特征矩阵 \(\mathbf{X} \in \mathbb{R}^{8438 \times 17}\),实测室温水溶解度 \(\log S\) 构成目标向量 \(\mathbf{y} \in \mathbb{R}^{8438}\),并固定 train_test_split(..., test_size=0.2, random_state=42) 留出 20% 闭卷测试集。

连续性质预测最核心的三个评估指标:

  • MAE(平均绝对误差):\(\frac{1}{n}\sum_{i=1}^n |y_i - \hat{y}_i|\);
  • RMSE(均方根误差):\(\sqrt{\frac{1}{n}\sum_{i=1}^n (y_i - \hat{y}_i)^2}\),对预测错得离谱的极端异常点惩罚更严厉(\(\text{RMSE}=1.0\) 约对应摩尔溶解度误差 \(10^1 = 10\) 倍);
  • \(R^2\)(决定系数):\(1 - \frac{\sum (y_i - \hat{y}_i)^2}{\sum (y_i - \bar{y})^2}\),完美预测为 1.0,与瞎猜均值持平为 0.0,严重过拟合或外推崩盘时甚至跌成负数!
In [3] · Python
DATA_FILE = "data/solubility.csv" if os.path.exists("data/solubility.csv") else "../01 - Basics/data/solubility.csv"
df_raw = pd.read_csv(DATA_FILE)

feature_cols = [
    "MolWt", "MolLogP", "MolMR", "HeavyAtomCount", "NumHAcceptors", "NumHDonors",
    "NumHeteroatoms", "NumRotatableBonds", "NumValenceElectrons", "NumAromaticRings",
    "NumSaturatedRings", "NumAliphaticRings", "RingCount", "TPSA", "LabuteASA",
    "BalabanJ", "BertzCT",
]

df = df_raw[~df_raw["SMILES"].str.contains(r"\.", na=False)].dropna(
    subset=feature_cols + ["Solubility"]
).reset_index(drop=True)

X = df[feature_cols].values
y = df["Solubility"].values
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
print(f"纯净单组分有机分子数: {len(df)} | 训练集: {len(X_train)} | 测试集: {len(X_test)}")

y_dummy = np.full_like(y_test, fill_value=y_train.mean())
print(
    f"瞎猜均值基线              | MAE = {mean_absolute_error(y_test, y_dummy):.3f} | "
    f"RMSE = {root_mean_squared_error(y_test, y_dummy):.3f} | R² = {r2_score(y_test, y_dummy):.3f}"
)

def evaluate_reg(model, X_tr, y_tr, X_te, y_te, label="Model"):
    model.fit(X_tr, y_tr)
    tr_rmse = root_mean_squared_error(y_tr, model.predict(X_tr))
    te_pred = model.predict(X_te)
    te_mae = mean_absolute_error(y_te, te_pred)
    te_rmse = root_mean_squared_error(y_te, te_pred)
    te_r2 = r2_score(y_te, te_pred)
    print(f"{label:25s} | Train RMSE = {tr_rmse:.3f} | Test MAE = {te_mae:.3f} | Test RMSE = {te_rmse:.3f} | R² = {te_r2:.3f}")
    return te_pred
Out:
纯净单组分有机分子数: 8438 | 训练集: 6750 | 测试集: 1688
瞎猜均值基线              | MAE = 1.845 | RMSE = 2.338 | R² = -0.000

2. 最小二乘法的两条求解路径:正规方程 vs 梯度下降

给定增广特征矩阵 \(\tilde{\mathbf{X}} = [\mathbf{1}, \mathbf{X}] \in \mathbb{R}^{n \times (d+1)}\),线性模型写作 \(\hat{\mathbf{y}} = \tilde{\mathbf{X}}\boldsymbol{\theta}\),均方误差损失为 \(\mathcal{L}(\boldsymbol{\theta}) = \frac{1}{n}\lVert \tilde{\mathbf{X}}\boldsymbol{\theta} - \mathbf{y} \rVert_2^2\):

  1. 正规方程闭式解(Normal Equations):令梯度为零,当 \(\tilde{\mathbf{X}}^\top\tilde{\mathbf{X}}\) 满秩可逆时,一步求得 \(\boldsymbol{\theta}^* = (\tilde{\mathbf{X}}^\top \tilde{\mathbf{X}})^{-1} \tilde{\mathbf{X}}^\top \mathbf{y}\)(无需调学习率,但求逆复杂度 \(O(d^3)\) 且遇严格共线性会奇异不可逆);
  2. 梯度下降迭代法(Gradient Descent):沿负梯度更新 \(\boldsymbol{\theta}^{(t+1)} = \boldsymbol{\theta}^{(t)} - \eta \cdot \frac{2}{n}\tilde{\mathbf{X}}^\top(\tilde{\mathbf{X}}\boldsymbol{\theta}^{(t)} - \mathbf{y})\),是深度学习唯一通用的优化方式。
In [4] · Python
# ▶️ 运行看看 / ✏️ 改一改:对比正规方程闭式解 vs 8 行手写梯度下降轨迹
logp_idx = feature_cols.index("MolLogP")
x_tr_1d = (X_train[:, logp_idx] - X_train[:, logp_idx].mean()) / X_train[:, logp_idx].std()

# 路线 A:正规方程闭式解 (X^T X)^(-1) X^T y
X_aug = np.column_stack([np.ones_like(x_tr_1d), x_tr_1d])
theta_normal = np.linalg.inv(X_aug.T @ X_aug) @ (X_aug.T @ y_train)
b_exact, w_exact = theta_normal[0], theta_normal[1]

# 路线 B:8 行纯 NumPy 手写梯度下降
lr = 0.15          # ✏️ 试试改成 0.03(下山慢)或 0.96(在碗壁来回震荡)
w, b = 1.2, 1.5
history = [(w, b)]
for _ in range(30):
    err = (w * x_tr_1d + b) - y_train
    dw, db = 2.0 * np.mean(err * x_tr_1d), 2.0 * np.mean(err)
    w, b = w - lr * dw, b - lr * db
    history.append((w, b))

history = np.array(history)
print(f"正规方程闭式精确解 : w = {w_exact:.5f}, b = {b_exact:.5f}")
print(f"梯度下降 30 步结果 : w = {w:.5f}, b = {b:.5f}")

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10.8, 4.1))
wg, bg = np.meshgrid(np.linspace(-2.5, 1.6, 100), np.linspace(-4.5, 2.0, 100))
loss_grid = np.mean((wg[..., None] * x_tr_1d + bg[..., None] - y_train) ** 2, axis=-1)
cs = ax1.contour(wg, bg, loss_grid, levels=16, cmap="viridis", alpha=0.75)
ax1.clabel(cs, inline=True, fontsize=7.5, fmt="%.1f")
ax1.plot(history[:, 0], history[:, 1], "o-", color=C.crimson, markersize=4, lw=1.6, label="Gradient Descent Path")
ax1.scatter([w_exact], [b_exact], marker="*", s=160, color=C.gold, edgecolors="black", zorder=6, label="Normal Eq. Optimum")
ax1.set_xlabel("Slope w (Standardized MolLogP)")
ax1.set_ylabel("Intercept b")
ax1.set_title("(a) MSE Loss Contours & Optimization Path")
ax1.legend(loc="lower left", fontsize=8.2)

ax2.scatter(x_tr_1d[:800], y_train[:800], s=8, alpha=0.28, color=C.slate, label="Training Molecules")
x_line = np.linspace(-3.0, 3.5, 100)
ax2.plot(x_line, w_exact * x_line + b_exact, color=C.navy, lw=2.2, label=f"OLS Line: y = {w_exact:.2f}x + ({b_exact:.2f})")
ax2.set_xlabel("Standardized MolLogP")
ax2.set_ylabel("Experimental logS")
ax2.set_title("(b) 1D Linear Fit on Clean AqSolDB")
ax2.legend(loc="upper right", fontsize=8.2)

plt.tight_layout()
plt.show()
Out:
正规方程闭式精确解 : w = -1.72746, b = -3.01263
梯度下降 30 步结果 : w = -1.72740, b = -3.01253
Notebook 输出图像

3. 多项式特征与偏差–方差误差分解(Bias–Variance Decomposition)

统计学习理论证明,未见测试点上的期望均方误差可严格分解为:

\[\mathbb{E}\!\left[(y - \hat{f}(x))^2\right] = \underbrace{\left(\text{Bias}[\hat{f}(x)]\right)^2}_{\text{偏差平方(模型太僵硬)}} + \underbrace{\text{Var}[\hat{f}(x)]}_{\text{方差(换批样本曲线乱晃)}} + \underbrace{\sigma_{\text{noise}}^2}_{\text{不可约实验噪声}}\]

下面我们通过 6 次小样本(\(N=35\))重采样对比 \(d=1\)(高偏差、低方差) 与 \(d=8\)(低偏差、极高方差),并绘制验证误差的经典 U 型曲线:

In [5] · Python
# ▶️ 运行看看:6 次小样本重采样直观对比高偏差 vs 高方差,以及阶数扫描 U 型曲线
rng_bv = np.random.default_rng(24)
x_te_1d = (X_test[:, logp_idx] - X_train[:, logp_idx].mean()) / X_train[:, logp_idx].std()
in_box = (x_te_1d >= -1.8) & (x_te_1d <= 1.8)
x_val_bv, y_val_bv = x_te_1d[in_box].reshape(-1, 1), y_test[in_box]
in_tr_box = np.where((x_tr_1d >= -2.0) & (x_tr_1d <= 2.0))[0]

fig, axes = plt.subplots(1, 3, figsize=(12.2, 3.8))
xg = np.linspace(-1.9, 1.9, 200).reshape(-1, 1)

for ax, deg, title, col in [
    (axes[0], 1, "(a) Degree=1: High Bias, Low Variance", C.teal),
    (axes[1], 8, "(b) Degree=8: Low Bias, Huge Variance!", C.crimson),
]:
    for _ in range(6):
        sub = rng_bv.choice(in_tr_box, size=35, replace=False)
        mp = make_pipeline(PolynomialFeatures(degree=deg), LinearRegression()).fit(x_tr_1d[sub].reshape(-1, 1), y_train[sub])
        ax.plot(xg, mp.predict(xg), color=col, alpha=0.55, lw=1.5)
    ax.scatter(x_val_bv[:120], y_val_bv[:120], s=8, alpha=0.25, color=C.slate)
    ax.set_ylim(-9.5, 2.0)
    ax.set_xlabel("Standardized MolLogP")
    ax.set_title(title, fontsize=9.5)
axes[0].set_ylabel("Predicted logS")

degs = list(range(1, 10))
tr_errs, val_errs = [], []
sub_fixed = np.random.default_rng(12).choice(in_tr_box, size=45, replace=False)
for d in degs:
    mp = make_pipeline(PolynomialFeatures(degree=d), LinearRegression()).fit(
        x_tr_1d[sub_fixed].reshape(-1, 1), y_train[sub_fixed]
    )
    tr_errs.append(root_mean_squared_error(y_train[sub_fixed], mp.predict(x_tr_1d[sub_fixed].reshape(-1, 1))))
    val_errs.append(root_mean_squared_error(y_val_bv, mp.predict(x_val_bv)))

axes[2].plot(degs, tr_errs, "o--", color=C.slate, label="Train RMSE")
axes[2].plot(degs, val_errs, "s-", color=C.navy, lw=2.0, label="Validation RMSE (U-curve)")
axes[2].set_yscale("log")
axes[2].set_xlabel("Polynomial Degree d")
axes[2].set_ylabel("RMSE (log scale)")
axes[2].set_title("(c) Bias-Variance Trade-off", fontsize=9.5)
axes[2].legend(fontsize=8.0)

plt.tight_layout()
plt.show()
Out:
Notebook 输出图像

4. 17 维多元线性回归与“多重共线性权重反转”破案

在全部 17 个标准化描述符上拟合普通最小二乘(OLS),画出**对角线图(Parity Plot)**并诊断权重符号反转:

  • RingCount 在数学定义上严格等于 NumAliphaticRings + NumAromaticRings(导致条件数破 \(10^{15}\)!);
  • MolWt、HeavyAtomCount、NumValenceElectrons 与 LabuteASA 衡量同一分子体积事实(相关系数 \(>0.95\)),无约束 OLS 给它们分配了一正一负相互抵消的异常大权重!
In [6] · Python
scaler = StandardScaler().fit(X_train)   # 只在训练集上 fit!
X_train_s = scaler.transform(X_train)
X_test_s = scaler.transform(X_test)

_ = evaluate_reg(LinearRegression(), X_train_s[:, [logp_idx]], y_train, X_test_s[:, [logp_idx]], y_test, "1-Feature OLS (MolLogP)")
y_pred_ols = evaluate_reg(LinearRegression(), X_train_s, y_train, X_test_s, y_test, "17-Feature OLS Linear")

ols_full = LinearRegression().fit(X_train_s, y_train)
print(f"\n标准化特征矩阵条件数 cond(X_train_s) = {np.linalg.cond(X_train_s):,.1e}")

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(11.0, 4.3))
ax1.scatter(y_test, y_pred_ols, s=9, alpha=0.28, color=C.navy, rasterized=True)
ax1.plot([-13, 2], [-13, 2], "--", color=C.crimson, lw=1.3, label="Ideal y = x")
ax1.set_xlim(-13, 2)
ax1.set_ylim(-13, 2)
ax1.set_xlabel("Experimental logS")
ax1.set_ylabel("OLS Predicted logS")
ax1.set_title("(a) 17-Feature OLS Parity Plot")
ax1.legend(loc="upper left")

order_w = np.argsort(ols_full.coef_)
bar_cols = [C.crimson if abs(ols_full.coef_[i]) > 0.8 else C.steel for i in order_w]
ax2.barh(np.array(feature_cols)[order_w], ols_full.coef_[order_w], color=bar_cols)
ax2.axvline(0, color=C.ink, lw=0.9)
ax2.set_xlabel("Standardized OLS Coefficient w_j")
ax2.set_title("(b) Collinearity Causes Opposing Giant Weights!")

plt.tight_layout()
plt.show()
Out:
1-Feature OLS (MolLogP)   | Train RMSE = 1.543 | Test MAE = 1.159 | Test RMSE = 1.528 | R² = 0.573
17-Feature OLS Linear     | Train RMSE = 1.357 | Test MAE = 1.016 | Test RMSE = 1.379 | R² = 0.652

标准化特征矩阵条件数 cond(X_train_s) = 9.9e+15
Notebook 输出图像

5. Ridge (\(L_2\))、Lasso (\(L_1\)) 与 ElasticNet 正则化路径

正则化模型 优化目标函数 特征约束特性
Ridge 岭回归 (\(L_2\)) \(\text{MSE} + \alpha \sum w_j^2\) 保证矩阵 \((\mathbf{X}^\top\mathbf{X} + n\alpha \mathbf{I})\) 严格满秩可逆;强共线特征均匀分摊稳定小权重
Lasso 套索回归 (\(L_1\)) \(\text{MSE} + \alpha \sum |w_j|\) 菱形尖角约束将次要/冗余特征权重精确压为 0(稀疏特征选择)
ElasticNet 弹性网络 \(\text{MSE} + \alpha\rho\sum |w_j| + \frac{\alpha(1-\rho)}{2}\sum w_j^2\) 兼顾 \(L_1\) 稀疏精简与 \(L_2\) 共线特征成组稳定效应(Grouping Effect)
In [7] · Python
# ▶️ 运行看看:对比 Ridge、Lasso 与 ElasticNet 的测试表现及正则化路径
_ = evaluate_reg(Ridge(alpha=50.0), X_train_s, y_train, X_test_s, y_test, "Ridge (alpha=50)")
_ = evaluate_reg(Lasso(alpha=0.02, max_iter=6000), X_train_s, y_train, X_test_s, y_test, "Lasso (alpha=0.02)")
_ = evaluate_reg(ElasticNet(alpha=0.02, l1_ratio=0.5, max_iter=6000), X_train_s, y_train, X_test_s, y_test, "ElasticNet (a=0.02, r=0.5)")

alphas_r = np.logspace(-1, 4.5, 40)
alphas_l = np.logspace(-3.5, 0.4, 40)
alphas_e = np.logspace(-3.5, 0.6, 40)

coefs_r = np.array([Ridge(alpha=a).fit(X_train_s, y_train).coef_ for a in alphas_r])
coefs_l = np.array([Lasso(alpha=a, max_iter=8000).fit(X_train_s, y_train).coef_ for a in alphas_l])
coefs_e = np.array([ElasticNet(alpha=a, l1_ratio=0.5, max_iter=8000).fit(X_train_s, y_train).coef_ for a in alphas_e])

highlight = {
    "MolLogP": (C.navy, "MolLogP"),
    "HeavyAtomCount": (C.crimson, "HeavyAtomCount"),
    "NumValenceElectrons": (C.gold, "NumValenceElectrons"),
    "LabuteASA": (C.teal, "LabuteASA"),
}

fig, axes = plt.subplots(1, 3, figsize=(12.6, 3.9), sharey=True)
for ax, al_grid, cf_mat, title in [
    (axes[0], alphas_r, coefs_r, "(a) Ridge (L2) Path"),
    (axes[1], alphas_l, coefs_l, "(b) Lasso (L1) Path"),
    (axes[2], alphas_e, coefs_e, "(c) ElasticNet (L1+L2) Path"),
]:
    for j, cname in enumerate(feature_cols):
        if cname in highlight:
            col, lbl = highlight[cname]
            ax.plot(al_grid, cf_mat[:, j], color=col, lw=2.0, label=lbl)
        else:
            ax.plot(al_grid, cf_mat[:, j], color=C.slate, alpha=0.30, lw=1.0)
    ax.axhline(0, color=C.ink, ls=":", lw=0.8)
    ax.set_xscale("log")
    ax.set_xlabel("Regularization Strength alpha")
    ax.set_title(title, fontsize=9.8)

axes[0].set_ylabel("Standardized Coefficient w_j")
axes[0].legend(loc="lower right", fontsize=7.8)
plt.tight_layout()
plt.show()
Out:
Ridge (alpha=50)          | Train RMSE = 1.366 | Test MAE = 1.022 | Test RMSE = 1.388 | R² = 0.648
Lasso (alpha=0.02)        | Train RMSE = 1.384 | Test MAE = 1.026 | Test RMSE = 1.394 | R² = 0.644
ElasticNet (a=0.02, r=0.5) | Train RMSE = 1.380 | Test MAE = 1.028 | Test RMSE = 1.395 | R² = 0.644
Notebook 输出图像

🏋️ 练习 02a-1:小样本二阶多项式交叉特征崩溃 vs Ridge 正则化拯救

用 PolynomialFeatures(degree=2, include_bias=False) 将 17 个描述符扩充为包含平方项与两两交互项的 170 维特征,在小样本材料场景(仅取前 250 个训练分子 X_train[:250], y_train[:250])下:

  1. 用 make_pipeline(StandardScaler(), PolynomialFeatures(degree=2, include_bias=False), LinearRegression()) 拟合并在完整测试集 X_test, y_test 上计算 RMSE;
  2. 将最后一步替换为 Ridge(alpha=120.0) 重复实验,观察正则化如何拯救小样本高维过拟合!
In [8] · Python
# 🏋️ 练习 02a-1:在这里编写你的代码

🏋️ 练习 02a-2:对比 Lasso 与 ElasticNet 在共线特征上的筛选行为

在标准化全量训练集 X_train_s, y_train 上分别拟合 Lasso(alpha=0.05, max_iter=6000) 与 ElasticNet(alpha=0.05, l1_ratio=0.5, max_iter=6000),统计两者被精确置零的特征数 np.sum(model.coef_ == 0),打印非零特征权重并对比测试集 RMSE。

In [9] · Python
# 🏋️ 练习 02a-2:在这里编写你的代码

小结

  • 正规方程 vs 梯度下降:满秩小矩阵可闭式一步求解,高维或深度模型依赖梯度下降迭代;
  • 偏差–方差分解:自由度过高在小样本上导致高方差震荡;
  • 三大正则化:Ridge 平滑抑制共线对冲权重,Lasso 自动归零冗余列,ElasticNet 兼顾稀疏筛选与共线成组稳定性。

👉 下一节(02b_classification_knn_and_svm.ipynb):进入二分类/三分类 Softmax 判别体系、基础概率陷阱以及距离与核边界模型(kNN & SVM/SVR)!

读完了?

标记为已学完,进度会同步到课程大纲与首页的元素周期表。

返回模块 02