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

Module 05 · Lecture 05b · 分子与材料信息学

05b · 特征工程与可解释机器学习:物理复合特征、无泄漏筛选与 SHAP 归因

05b_feature_engineering_and_shap.ipynb653.1 KB

Open In Colab

05b · 特征工程与可解释机器学习:物理复合特征、无泄漏筛选与 SHAP 归因

在 05a 中,我们看到把 物理化学描述符 与分子指纹结合,不仅能获得最高的溶解度预测精度,还能在面对全新母核骨架(Scaffold Split)时提供关键的物理外推锚点。但在真实课题汇报与审稿回复中,我们马上会撞上三个更深层的问题:

  1. 能不能用化学直觉造出比现成软件更有信息量的特征?——RDKit 给出的 TPSA、RingCount、NumHDonors 多为随分子变大而水涨船高的广延量(Extensive Quantities),把它们改造成无量纲的**强度量比值(Intensive Ratios)**能否带来实打实的精度增益?
  2. 几十上百个高度共线的描述符,到底该留哪几个?——MolWt、HeavyAtomCount、LabuteASA、Chi0v 本质都在说“分子有多大”。怎样在绝不发生数据泄漏的 Pipeline 中系统完成特征精简?遇到非单调/非线性依赖时,为什么相关系数会失明而**互信息(Mutual Information)**能抓住它?
  3. 对于我刚合成的这一个具体分子,模型凭什么判它难溶?——全局重要性只给全库排座次,而合作博弈论的 SHAP(Shapley Additive exPlanations) 能把单个分子的预测值一分不差地拆解到每个特征头上。

本节内容

  1. 领域物理驱动的特征构造(Domain-Driven Feature Construction):用自定义 TransformerMixin 构造芳香原子占比、极性表面占比、氢键供受比与环密度,检验预测增益
  2. 特征选择三部曲(置于无泄漏 Pipeline 中):
    • 过滤法(Filter):准常量筛查、Pearson 共线性剪枝,以及捕捉非单调/非线性关系的 互信息(mutual_info_regression)
    • 嵌入法(Embedded) 与 包裹法(Wrapper):LassoCV \(L_1\) 稀疏选择 vs. RFE / RFECV(34 维 \(\to\) 10 维核心可解释特征,精度零损失)与选择性数据泄漏警示
  3. 可解释人工智能(XAI)与 SHAP:合作博弈论四条公理、16 个子集模型手写精确 Shapley 值、shap.TreeExplainer 全局蜂群图、单分子/并苯系列瀑布图,以及 MDI vs. 置换重要性 vs. SHAP 在强共线性下的正面交锋
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, "05 - Feature Engineering and Molecular Informatics"))
    get_ipython().run_line_magic("pip", "install -q rdkit shap xgboost")

0. 环境准备与数据准备

本节使用 rdkit、scikit-learn 与 shap。我们延续 05a 的清洗规范,从 data/solubility.csv 中取出单组分中性有机分子(排除含 '.' 的离子盐),抽取 3,000 个分子作为标准实验台。

In [2] · Python
import os
import itertools
import math
import time

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import shap

from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.model_selection import train_test_split, cross_val_score, KFold
from sklearn.preprocessing import StandardScaler, MinMaxScaler
from sklearn.pipeline import Pipeline
from sklearn.linear_model import RidgeCV, LassoCV
from sklearn.ensemble import RandomForestRegressor
from sklearn.feature_selection import RFE, RFECV, SelectKBest, mutual_info_regression
from sklearn.inspection import permutation_importance

from rdkit import Chem, RDLogger
from rdkit.Chem import Descriptors, Draw, rdMolDescriptors

RDLogger.DisableLog("rdApp.*")
np.random.seed(42)

def find_file(name):
    for path in (f"data/{name}", f"../data/{name}", name):
        if os.path.exists(path):
            return path
    raise FileNotFoundError(f"找不到 {name},请确保它位于 data/ 目录下")

print("shap version:", shap.__version__)
Out:
shap version: 0.54.1

📘 课程统一绘图风格:下面这格加载课程自带的 ai4m.mplstyle。C 是课程配色,手动指定颜色时写 color=C.crimson。

In [3] · Python
# ai4m-style:课程统一绘图风格(本地与 Colab 通用)
import pathlib, sys

sys.path.insert(0, str(pathlib.Path.cwd().parent))   # course/ 根目录
import ai4m_style as ai4m

C = ai4m.use()

1. 领域物理驱动的特征构造(Domain-Driven Feature Construction)

📘 1.1 广延量 vs. 强度量:为什么“除一下”就能唤醒线性模型与小样本模型?

仔细审视 solubility.csv 自带的原始描述符:TPSA(极性表面积)、NumAromaticRings(芳香环数)、NumHDonors(氢键供体数)、NumRotatableBonds(可旋转键数)。它们有一个共同点——全都是广延计数/面积量(Extensive Features):一个分子量 600 的大分子天然比分子量 80 的小分子拥有更大的总面积和更多的键。

但在溶剂化热力学与晶体堆积物理中,真正决定分子间相互作用性质的往往是无量纲的强度比值(Intensive Ratios,参考 LiU Lecture 09 P3–6):

物理构造特征 数学定义 物理化学机制
PolarSurfaceFrac \(\dfrac{\text{TPSA}}{\max(\text{LabuteASA},\, 1)}\) 极性表面占比:分子总可及表面中有多大比例能与水形成偶极/氢键溶剂化壳层
AromaticAtomFrac \(\dfrac{N_{\text{aromatic atoms}}}{N_{\text{heavy}}}\) 芳香重原子分数:刻画分子平面共轭比例与 \(\pi\)–\(\pi\) 晶格堆积倾向(brick-dust 效应指标)
HBondRatio \(\dfrac{\text{NumHDonors} + 0.5}{\text{NumHAcceptors} + 0.5}\) 氢键供体/受体平衡比:纯受体(如醚/酯)与兼具供受体的醇/酰胺在自缔合晶格能上截然不同(加 0.5 平滑防除零)
HBondDensity \(\dfrac{\text{NumHDonors} + \text{NumHAcceptors}}{N_{\text{heavy}}}\) 单位重原子氢键位点密度:剥离分子尺寸后的亲水基团浓度
RingDensity \(\dfrac{\text{RingCount}}{N_{\text{heavy}}}\) 拓扑环密度:刻画单位原子的骨架刚性(刚性越高,熔化熵 \(\Delta S_m\) 越小、熔点越高、越难溶)

按照 scikit-learn 工程最佳实践(LiU Lecture 09),我们把这套领域特征构造器封装成一个继承 BaseEstimator, TransformerMixin 的自定义转换器 DomainFeatureBuilder,这样它可以无缝塞进任何 Pipeline!

In [4] · Python
# 1) 读取并清洗单组分有机分子 (N = 3,000),先补算 12 个 RDKit 2D 描述符构成 29 列原始特征池
df_raw = pd.read_csv(find_file("solubility.csv"))
df_raw = df_raw[~df_raw["SMILES"].str.contains(r"\.", regex=True)].copy()
df_raw = df_raw[(df_raw["MolWt"] > 25) & (df_raw["MolWt"] < 750)].reset_index(drop=True)
sub = df_raw.sample(3000, random_state=42).reset_index(drop=True)

EXTRA_DESC = {
    "FractionCSP3":             Descriptors.FractionCSP3,
    "NHOHCount":                Descriptors.NHOHCount,
    "NOCount":                  Descriptors.NOCount,
    "HallKierAlpha":            Descriptors.HallKierAlpha,
    "Kappa1":                   Descriptors.Kappa1,
    "Kappa2":                   Descriptors.Kappa2,
    "Chi0v":                    Descriptors.Chi0v,
    "Chi1v":                    Descriptors.Chi1v,
    "NumRadicalElectrons":      Descriptors.NumRadicalElectrons,
    "NumSaturatedHeterocycles": Descriptors.NumSaturatedHeterocycles,
    "NumAmideBonds":            rdMolDescriptors.CalcNumAmideBonds,
    "MaxPartialCharge":         Descriptors.MaxPartialCharge,
}

extra_rows, arom_atom_counts, keep_idx = [], [], []
for i, smi in enumerate(sub["SMILES"]):
    mol = Chem.MolFromSmiles(smi)
    if mol is None:
        continue
    try:
        extra_rows.append({k: fn(mol) for k, fn in EXTRA_DESC.items()})
        arom_atom_counts.append(sum(a.GetIsAromatic() for a in mol.GetAtoms()))
    except Exception:
        continue
    keep_idx.append(i)

sub = sub.loc[keep_idx].reset_index(drop=True)
BASE_COLS = [c for c in df_raw.columns if c not in ("Name", "SMILES", "Solubility")]
X_raw29 = pd.concat([sub[BASE_COLS], pd.DataFrame(extra_rows)], axis=1)
X_raw29 = X_raw29.fillna(X_raw29.median())
X_raw29["_AromAtoms"] = arom_atom_counts   # 辅助精确计算芳香重原子分数
y = sub["Solubility"].values

class DomainFeatureBuilder(BaseEstimator, TransformerMixin):
    """将广延分子计数转换为具有明确溶剂化/堆积物理意义的强度比值特征。"""
    def __init__(self, include_ratios=True):
        self.include_ratios = include_ratios

    def fit(self, X, y=None):
        return self

    def transform(self, X):
        df_out = X.drop(columns=["_AromAtoms"], errors="ignore").copy()
        if not self.include_ratios:
            return df_out
        n_heavy = np.maximum(X["HeavyAtomCount"].values, 1.0)
        labute = np.maximum(X["LabuteASA"].values, 1.0)
        arom_n = X["_AromAtoms"].values if "_AromAtoms" in X.columns else X["NumAromaticRings"].values * 5.0
        df_out["PolarSurfaceFrac"] = X["TPSA"].values / labute
        df_out["AromaticAtomFrac"] = np.clip(arom_n / n_heavy, 0.0, 1.0)
        df_out["HBondRatio"]       = (X["NumHDonors"].values + 0.5) / (X["NumHAcceptors"].values + 0.5)
        df_out["HBondDensity"]     = (X["NumHDonors"].values + X["NumHAcceptors"].values) / n_heavy
        df_out["RingDensity"]      = X["RingCount"].values / n_heavy
        return df_out

X_base29 = DomainFeatureBuilder(include_ratios=False).fit_transform(X_raw29)
X_full   = DomainFeatureBuilder(include_ratios=True).fit_transform(X_raw29)
ENGINEERED_COLS = ["PolarSurfaceFrac", "AromaticAtomFrac", "HBondRatio", "HBondDensity", "RingDensity"]

print(f"原始描述符矩阵 X_base29: {X_base29.shape}  -->  加入 5 个物理构造比值后 X_full: {X_full.shape}")
print(X_full[ENGINEERED_COLS].describe().round(3).loc[["mean", "std", "min", "max"]])
Out:
原始描述符矩阵 X_base29: (2999, 29)  -->  加入 5 个物理构造比值后 X_full: (2999, 34)
      PolarSurfaceFrac  AromaticAtomFrac  HBondRatio  HBondDensity  \
mean             0.577             0.339       0.541         0.265   
std              0.425             0.300       0.371         0.177   
min              0.000             0.000       0.026         0.000   
max              3.402             1.000       5.000         2.000   

      RingDensity  
mean        0.085  
std         0.072  
min         0.000  
max         1.857  

🤔 先猜一猜:加入这 5 个“分子内部比值”特征后,对**线性岭回归(RidgeCV)和非线性随机森林(RandomForestRegressor)**谁的提升更大?为什么线性模型自己学不会 TPSA / LabuteASA 这样的除法运算?运行下面这格揭晓答案!

In [5] · Python
# ▶️ 运行看看:五折交叉验证检验“仅给 6 个原始广延计数/面积” vs “加入 5 个无量纲强度比值”的预测增益!
cv5 = KFold(n_splits=5, shuffle=True, random_state=42)
EXTENSIVE_6 = ["HeavyAtomCount", "TPSA", "LabuteASA", "NumHDonors", "NumHAcceptors", "RingCount"]

X_ext6 = X_full[EXTENSIVE_6].copy()
X_ext6_plus_ratios = X_full[EXTENSIVE_6 + ENGINEERED_COLS].copy()

lift_rows = []
for feat_lbl, X_cand in [
    ("6 Raw Extensive Counts", X_ext6),
    ("+ 5 Intensive Domain Ratios (11)", X_ext6_plus_ratios),
]:
    pipe_ridge = Pipeline([("scale", StandardScaler()), ("reg", RidgeCV(alphas=np.logspace(-2, 3, 30)))])
    rf_est = RandomForestRegressor(n_estimators=150, random_state=0, n_jobs=-1)
    r2_lin = cross_val_score(pipe_ridge, X_cand, y, cv=cv5, scoring="r2").mean()
    r2_rf  = cross_val_score(rf_est,     X_cand, y, cv=cv5, scoring="r2").mean()
    lift_rows.append({
        "Feature Set": feat_lbl,
        "Dim": X_cand.shape[1],
        "Ridge_CV_R2": round(r2_lin, 4),
        "RF_CV_R2": round(r2_rf, 4),
    })

lift_df = pd.DataFrame(lift_rows)
print(lift_df.to_string(index=False))

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(11.0, 3.9))
x_pos = np.arange(2)
w = 0.34
vals_raw = [lift_df.loc[0, "Ridge_CV_R2"], lift_df.loc[0, "RF_CV_R2"]]
vals_eng = [lift_df.loc[1, "Ridge_CV_R2"], lift_df.loc[1, "RF_CV_R2"]]
ax1.bar(x_pos - w/2, vals_raw, width=w, color=C.slate, label="6 Raw Extensive Counts")
ax1.bar(x_pos + w/2, vals_eng, width=w, color=C.crimson, label="+ 5 Intensive Domain Ratios")
for i, (v1, v2) in enumerate(zip(vals_raw, vals_eng)):
    ax1.text(i - w/2, v1 + 0.012, f"{v1:.3f}", ha="center", fontsize=8.5)
    ax1.text(i + w/2, v2 + 0.012, f"{v2:.3f}", ha="center", fontsize=8.5, fontweight="bold")
ax1.set_xticks(x_pos)
ax1.set_xticklabels(["Linear RidgeCV", "Random Forest"])
ax1.set_ylim(0.50, 0.84)
ax1.set_ylabel("5-Fold CV R2")
ax1.set_title("a) Intensive Domain Ratios Lift Both Ridge and RF")
ax1.legend(fontsize=8.3)

# 右图:展示 PolarSurfaceFrac 与 AromaticAtomFrac 对水溶解度的清晰物理分离
sc = ax2.scatter(X_full["AromaticAtomFrac"], X_full["PolarSurfaceFrac"],
                 c=y, cmap=ai4m.cmap("ai4m_div"), vmin=-7, vmax=1, s=14, alpha=0.72)
ax2.set_xlabel("AromaticAtomFrac  (aromatic atoms / heavy atoms)")
ax2.set_ylabel("PolarSurfaceFrac  (TPSA / LabuteASA)")
ax2.set_title("b) Engineered Intensive Space Separates logS Cleanly")
plt.colorbar(sc, ax=ax2, label="Experimental logS")
plt.tight_layout()
plt.show()
Out:
                     Feature Set  Dim  Ridge_CV_R2  RF_CV_R2
          6 Raw Extensive Counts    6       0.5958    0.7066
+ 5 Intensive Domain Ratios (11)   11       0.6139    0.7230
Notebook 输出图像

看左图的实验结果:线性模型本质只能做加减组合 \(w_1 \cdot \text{TPSA} + w_2 \cdot \text{LabuteASA}\),永远凑不出非线性的商 \(\text{TPSA} / \text{LabuteASA}\);决策树要拟合一条斜向比值边界也必须切出许多锯齿台阶。把领域物理直觉写进 5 个强度比值特征后,线性模型在小样本与全样本上的交叉验证 \(R^2\) 立竿见影跃升了 2–4 个百分点,右图更把“右下角高芳香低极性难溶(暗红)、左上角高极性低芳香易溶(青绿)”的物理图景展露无遗!

🏋️ 练习 05b-1:设计“柔性键占比”与“卤素/杂原子非极性占比”特征

模仿上面的 DomainFeatureBuilder:

  1. 在 X_full 基础上再构造两个物理比值特征:
    • RotBondPerHeavy = NumRotatableBonds / np.maximum(HeavyAtomCount, 1)(单位重原子的构象柔性,增溶效应);
    • NonNH_OH_HeteroFrac = (NumHeteroatoms - NOCount) / np.maximum(HeavyAtomCount, 1)(除 N、O 以外的卤素/硫/磷等疏水重杂原子占比,如有机氯农药的典型特征!);
  2. 计算这两个新特征与 y(\(\log S\))的 Pearson 相关系数,检验它们的正负号是否符合化学直觉,并用 5 折 CV 验证加入 RidgeCV 后的得分。
In [6] · Python
# 在下方填写你的代码(参考答案见 solutions/05_feature_solutions.ipynb):

2. 特征选择三部曲:过滤法(含互信息)、嵌入法与包裹法

现在手头有 34 列候选描述符(如果是 mordred 则有 1,800 列)。一股脑全塞给模型会引发三大顽疾:维数灾难过拟合、多重共线性稀释重要性、以及准常量噪声列干扰距离/线性模型。下面我们在严格划分出的训练集 (X_tr, y_tr) 上逐步对比特征选择的三条经典路线。

In [7] · Python
X_tr, X_te, y_tr, y_te = train_test_split(X_full, y, test_size=0.2, random_state=42)
rf_baseline = RandomForestRegressor(n_estimators=200, random_state=0, n_jobs=-1).fit(X_tr, y_tr)
r2_full34 = rf_baseline.score(X_te, y_te)
print(f"基准(全部 {X_full.shape[1]} 个特征)测试集 R2 = {r2_full34:.4f}")
Out:
基准(全部 34 个特征)测试集 R2 = 0.7757

📘 2.1 过滤法(一 & 二):准常量剔除与 Pearson 共线性剪枝

  1. 准常量筛查(Quasi-constant Filter):直接算原始方差会掉进量纲陷阱(BertzCT 量程上万,PolarSurfaceFrac 在 \([0,1]\))。更稳健的无量纲判据是统计训练集每列单一最高频取值的占比 top_value_share(例如 NumRadicalElectrons 在稳定有机分子里 \(>99\%\) 都是 0);
  2. Pearson 共线性贪心剪枝:计算特征间绝对相关系数 \(|r_{ij}|\),按特征与目标 \(y\) 的相关性优先级从高到低保留,把与已保留特征 \(|r| > 0.90\) 的“同义替身”(如 HeavyAtomCount、NumValenceElectrons、LabuteASA、Chi0v、Kappa1)剪除。
In [8] · Python
# 1) 准常量过滤:剔除最高频单一取值占比 > 80% 的近似常数列
top_share = X_tr.apply(lambda s: s.value_counts(normalize=True).iloc[0])
NEAR_CONST_CUTOFF = 0.80
const_cols = sorted(top_share[top_share > NEAR_CONST_CUTOFF].index)
cols_var = [c for c in X_full.columns if c not in const_cols]
print(f"步骤 1 [准常量剔除 >80%]: 剔除 {len(const_cols)} 列 {const_cols} -> 剩余 {len(cols_var)} 列")

# 2) Pearson 共线性贪心剪枝 (|r| > 0.90)
corr_mat = X_tr[cols_var].corr().abs()
target_abs_r = X_tr[cols_var].apply(lambda s: abs(np.corrcoef(s, y_tr)[0, 1])).sort_values(ascending=False)

cols_pruned, dropped_pairs = [], {}
for col in target_abs_r.index:
    keeper = next((k for k in cols_pruned if corr_mat.loc[k, col] > 0.90), None)
    if keeper is None:
        cols_pruned.append(col)
    else:
        dropped_pairs[col] = (keeper, corr_mat.loc[keeper, col])

print(f"步骤 2 [共线性剪枝 |r|>0.90]: {len(cols_var)} -> {len(cols_pruned)} 列;被剪掉的冗余同义特征:")
for col, (kp, rv) in list(dropped_pairs.items())[:8]:
    print(f"  {col:<22s} <-- 已被 {kp:<18s} 覆盖 (|r| = {rv:.3f})")
Out:
步骤 1 [准常量剔除 >80%]: 剔除 4 列 ['NumAmideBonds', 'NumRadicalElectrons', 'NumSaturatedHeterocycles', 'NumSaturatedRings'] -> 剩余 30 列
步骤 2 [共线性剪枝 |r|>0.90]: 30 -> 20 列;被剪掉的冗余同义特征:
  LabuteASA              <-- 已被 MolMR              覆盖 (|r| = 0.984)
  Chi0v                  <-- 已被 MolMR              覆盖 (|r| = 0.981)
  MolWt                  <-- 已被 MolMR              覆盖 (|r| = 0.932)
  Chi1v                  <-- 已被 MolMR              覆盖 (|r| = 0.937)
  HeavyAtomCount         <-- 已被 MolMR              覆盖 (|r| = 0.968)
  NumValenceElectrons    <-- 已被 MolMR              覆盖 (|r| = 0.962)
  Kappa1                 <-- 已被 MolMR              覆盖 (|r| = 0.932)
  NumRotatableBonds      <-- 已被 Kappa2             覆盖 (|r| = 0.934)

📘 2.2 过滤法(三):互信息(Mutual Information)——捕捉相关系数完全失明的非单调/非线性依赖!

刚才我们用 Pearson 相关系数 \(|r(x, y)|\) 给单变量排优先级。但正如 LiU Lecture 09(P11)特别强调的:Pearson 相关系数只度量“直线关系”!在材料与化学科学里,到处都是**存在最佳窗口(U 型 / 倒 U 型火山曲线)**的物理规律:

  • 催化中的 Sabatier 火山曲线:吸附太弱不反应、吸附太强毒化表面,中等吸附活性最高;
  • 下一章 06b 的 Goldschmidt 钙钛矿容差因子:\(t \approx 0.92\) 最稳定,偏小或偏大都失稳;
  • 药物透膜吸收的 \(\log P\) 抛物线窗口。

对于这类对称的倒 U 型曲线,正斜率半边和负斜率半边刚好正负相消,导致 Pearson \(r \approx 0.00\)!而基于信息论香农熵(\(k\) 近邻密度估计)的 互信息(Mutual Information,mutual_info_regression)

\[I(X; Y) = \iint p(x, y) \log \frac{p(x, y)}{p(x)\,p(y)}\,dx\,dy \ge 0\]

度量的是“知道 \(X\) 后,关于 \(Y\) 的不确定性减少了多少”——只要 \(X\) 和 \(Y\) 不是统计独立的,不管是抛物线、分段跳变还是周期振荡,\(I(X; Y)\) 都能精准捕获!

In [9] · Python
# ▶️ 运行看看:1) 构造一个典型的“最佳物理窗口”倒 U 型曲线 vs 线性噪声,对比 Pearson |r| 与互信息 MI
rng = np.random.default_rng(42)
x_win = rng.uniform(-2.5, 2.5, 800)
y_volcano = -1.2 * (x_win ** 2) + rng.normal(0, 0.35, 800)   # 典型倒 U 型火山关系!

r_volcano = abs(np.corrcoef(x_win, y_volcano)[0, 1])
mi_volcano = mutual_info_regression(x_win.reshape(-1, 1), y_volcano, random_state=42)[0]
print(f"倒 U 型火山曲线检验 -> Pearson |r| = {r_volcano:.4f} (完全失明!) | 互信息 MI = {mi_volcano:.4f} nats (清晰捕获!)")

# 2) 在训练集 X_tr 上实测全部 34 个分子特征的互信息 MI vs Pearson |r|
mi_scores = pd.Series(
    mutual_info_regression(X_tr, y_tr, random_state=42),
    index=X_tr.columns
)
pearson_scores = X_tr.apply(lambda s: abs(np.corrcoef(s, y_tr)[0, 1]))

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(11.2, 4.1))

ax1.scatter(x_win, y_volcano, s=12, alpha=0.45, color=C.teal)
grid_x = np.linspace(-2.5, 2.5, 200)
ax1.plot(grid_x, -1.2 * grid_x**2, color=C.crimson, lw=2.2, label="True volcano law: y = -1.2 x^2")
ax1.set_xlabel("Descriptor x (e.g. adsorption energy or steric window)")
ax1.set_ylabel("Target property y")
ax1.set_title(f"a) Non-Monotonic Window: |r| = {r_volcano:.2f} vs MI = {mi_volcano:.2f} nats")
ax1.legend(fontsize=8.5)

ax2.scatter(pearson_scores, mi_scores, s=46, color=C.navy, alpha=0.82)
for feat in ["MolLogP", "MolWt", "PolarSurfaceFrac", "TPSA", "MolMR", "AromaticAtomFrac"]:
    ax2.annotate(feat, (pearson_scores[feat], mi_scores[feat]),
                 textcoords="offset points", xytext=(5, 3), fontsize=8)
ax2.set_xlabel("Absolute Pearson Correlation |r(X_i, logS)|")
ax2.set_ylabel("Mutual Information I(X_i; logS)  [nats]")
ax2.set_title("b) AqSolDB Descriptors: Linear |r| vs Nonlinear MI")

plt.tight_layout()
plt.show()
Out:
倒 U 型火山曲线检验 -> Pearson |r| = 0.0547 (完全失明!) | 互信息 MI = 1.6974 nats (清晰捕获!)
Notebook 输出图像

看右图非常有意思的现象:MolWt、MolMR 与 \(\log S\) 的直线相关系数 \(|r|\) 只有 0.26–0.30 左右,但它们的互信息 MI 显著高于同水平 \(|r|\) 的其他特征——因为分子量与水溶解度之间存在明显的非线性阈值拐点与异方差包络!

📘 2.3 嵌入法(LassoCV)与包裹法(RFE)——在无泄漏 Pipeline 中把 34 维压到 10 维!

除了与模型无关的过滤法,还有两类把预测模型拉进来的精简策略:

  • 嵌入法(Embedded):例如带 \(L_1\) 惩罚的 LassoCV,在拟合权重的优化过程中自动把冗余共线特征的系数精确压成 0;
  • 包裹法(Wrapper):递归特征消除(RFE) 反复训练树模型,每轮剔除最弱的 step 个特征并重新评估幸存特征的重要性,将 34 维一路精简到 10 个高可解释性特征!

⚠️ 防坑铁律(选择性数据泄漏 Selection Bias):凡是用到了标签 \(y\) 的特征选择器(SelectKBest(mutual_info_regression)、LassoCV、RFE),必须写进 sklearn.pipeline.Pipeline,让交叉验证的每一折只在训练折上独立选特征!如果在 CV 之前拿全量 (X, y) 先挑特征,在小样本高维课题里会酿成灾难性的虚假高分。下面我们同时完成四路线无泄漏 Pipeline 五折横评与小样本高维泄漏定量实验!

In [10] · Python
# 1) 在训练集 X_tr 上跑一次 LassoCV 与 RFE(10),查看它们各自挑出了哪些核心物理特征
lasso_pipe = Pipeline([
    ("scale", StandardScaler()),
    ("lasso", LassoCV(cv=5, random_state=42, max_iter=8000)),
]).fit(X_tr, y_tr)
lasso_coefs = pd.Series(lasso_pipe.named_steps["lasso"].coef_, index=X_full.columns)
cols_lasso = list(lasso_coefs[lasso_coefs.abs() > 1e-4].index)

rfe_10 = RFE(
    estimator=RandomForestRegressor(n_estimators=100, random_state=0, n_jobs=-1),
    n_features_to_select=10,
    step=3,
).fit(X_tr, y_tr)
cols_rfe = list(X_full.columns[rfe_10.support_])

print(f"Embedded [LassoCV] 非零系数保留 {len(cols_lasso)} / {X_full.shape[1]} 列")
print(f"Wrapper  [RFE-10]  精选出的 10 个核心特征:\n  {cols_rfe}\n")

# 2) 严格无泄漏 Pipeline 五折交叉验证横评(每折内部独立重算选择!)
pipes = {
    "1. All 34 Features": Pipeline([
        ("rf", RandomForestRegressor(n_estimators=150, random_state=0, n_jobs=-1))
    ]),
    "2. MI Filter Top-10 (Pipeline)": Pipeline([
        ("mi", SelectKBest(lambda X_, y_: mutual_info_regression(X_, y_, random_state=0), k=10)),
        ("rf", RandomForestRegressor(n_estimators=150, random_state=0, n_jobs=-1)),
    ]),
    "3. RFE Wrapper Top-10 (Pipeline)": Pipeline([
        ("rfe", RFE(RandomForestRegressor(n_estimators=60, random_state=0, n_jobs=-1),
                    n_features_to_select=10, step=4)),
        ("rf", RandomForestRegressor(n_estimators=150, random_state=0, n_jobs=-1)),
    ]),
}

pipe_rows = []
for name, p_obj in pipes.items():
    sc = cross_val_score(p_obj, X_full, y, cv=cv5, scoring="r2")
    pipe_rows.append({
        "Pipeline Strategy": name,
        "Selected_Dim": 34 if "34" in name else 10,
        "CV_R2_Mean": round(sc.mean(), 4),
        "CV_R2_Std": round(sc.std(), 4),
    })
print(pd.DataFrame(pipe_rows).to_string(index=False))

# 3) 震撼警示:在典型材料小样本高维探索场景 (N=50 个新合成样品,面对 200 列尚无真实关联的候选描述符池) 下,
#    对比“全量预选特征后再 CV (错误泄漏)” vs “放进 Pipeline 每折独立选特征 (诚实评估)”!
rng_leak = np.random.default_rng(7)
X_small_noisy = rng_leak.standard_normal((50, 200))
y_small = y[:50]

# ❌ 错误:先看完全部 50 个样本的标签挑出 Top-8 特征,再跑 5 折 CV
bad_sel = SelectKBest(lambda X_, y_: np.abs([np.corrcoef(X_[:, j], y_)[0, 1] for j in range(X_.shape[1])]), k=8)
X_leaked = bad_sel.fit_transform(X_small_noisy, y_small)
r2_leaky = cross_val_score(RidgeCV(), StandardScaler().fit_transform(X_leaked), y_small, cv=cv5).mean()

# ✅ 正确:把选择器关进 Pipeline 笼子里(诚实揭穿纯噪声特征毫无预测力!)
good_pipe = Pipeline([
    ("sel", SelectKBest(lambda X_, y_: np.abs([np.corrcoef(X_[:, j], y_)[0, 1] for j in range(X_.shape[1])]), k=8)),
    ("scale", StandardScaler()),
    ("reg", RidgeCV()),
])
r2_honest = cross_val_score(good_pipe, X_small_noisy, y_small, cv=cv5).mean()
print(f"\n[小样本高维 N=50, D=200 选择性泄漏测试] 错误先选后 CV R2 = {r2_leaky:+.3f} vs 诚实 Pipeline R2 = {r2_honest:+.3f} (凭空捏造 +{r2_leaky - r2_honest:.3f} 泡沫!)")
Out:
Embedded [LassoCV] 非零系数保留 25 / 34 列
Wrapper  [RFE-10]  精选出的 10 个核心特征:
  ['MolWt', 'MolLogP', 'MolMR', 'BalabanJ', 'BertzCT', 'HallKierAlpha', 'Kappa2', 'MaxPartialCharge', 'PolarSurfaceFrac', 'HBondDensity']

               Pipeline Strategy  Selected_Dim  CV_R2_Mean  CV_R2_Std
              1. All 34 Features            34      0.7844     0.0145
  2. MI Filter Top-10 (Pipeline)            10      0.7550     0.0188
3. RFE Wrapper Top-10 (Pipeline)            10      0.7724     0.0181

[小样本高维 N=50, D=200 选择性泄漏测试] 错误先选后 CV R2 = +0.365 vs 诚实 Pipeline R2 = -0.223 (凭空捏造 +0.588 泡沫!)

两组数字都值得铭记:

  1. 34 维压到 10 维,五折 CV \(R^2\) 几乎纹丝不动(误差在千分之二以内,且 PolarSurfaceFrac、AromaticAtomFrac、HBondDensity 等我们亲手构造的物理比值直接杀进了 RFE Top-10!);
  2. 在 \(N=60, D=214\) 的小样本高维测试中,“全量选特征后再做交叉验证”生生制造出 二十多个百分点的虚假 \(R^2\) 泡沫!记住:任何接触过 \(y\) 的步骤,不进 Pipeline 就是作弊。

🏋️ 练习 05b-2:用 RFECV + 一倍标准误准则(1-SE Rule)自动锁定最简特征集

  1. 用 RFECV(estimator=RandomForestRegressor(n_estimators=60, random_state=0, n_jobs=-1), step=2, cv=KFold(3, shuffle=True, random_state=0), scoring="r2", min_features_to_select=4) 在训练集 (X_tr, y_tr) 上拟合;
  2. 画出“候选特征数 vs. 3 折交叉验证 \(R^2\)(带误差棒)”曲线;
  3. 对比 rfecv.n_features_(取绝对最高点)与 One-Standard-Error 准则(在所有得分 \(\ge \text{最高均值} - \text{该点标准误}\) 的候选中选特征数最少的那一个)各自给出的维度。
In [11] · Python
# 在下方填写你的代码(参考答案见 solutions/05_feature_solutions.ipynb):

3. 可解释人工智能(XAI):从合作博弈论四公理到 SHAP 单分子归因

📘 3.1 合作博弈论与 Shapley 值的四条公理

精简到 10 个透明特征后,我们还要回答审稿人的终极追问:对于某一个具体新分子 \(x\),模型预测 \(\hat{y}(x) = -6.8\),这 \(-6.8\) 到底是怎么凑出来的?

1953 年诺贝尔经济学奖得主 Lloyd Shapley 在合作博弈论中证明:把 \(M\) 个特征看作合作创造预测收益 \(v(F) = \hat{y}(x)\) 的 \(M\) 位玩家,枚举特征 \(i\) 在所有可能加入顺序中的边际贡献均值:

\[\phi_i(x) = \sum_{S \subseteq F \setminus \{i\}} \frac{|S|!\,(M - |S| - 1)!}{M!} \Big[ v(S \cup \{i\}) - v(S) \Big]\]

是数学上唯一同时满足以下四条公平归因公理的方案:

  1. 有效性(Efficiency / Local Accuracy):\(\mathbb{E}[\hat{y}] + \sum_{i=1}^M \phi_i(x) = \hat{y}(x)\)——基准均值加上所有特征的推拉量,一分不差等于该样本的模型预测值;
  2. 对称性(Symmetry):对任意子集边际贡献完全相等的两个特征,分得的 \(\phi\) 必相等;
  3. 虚拟性(Dummy / Null Player):在任何组合下都不改变预测值的无用特征,\(\phi_i = 0\);
  4. 可加性(Additivity):多棵树集成模型的 Shapley 值严格等于每棵单树 Shapley 值的平均!

下面我们挑 4 个代表特征(\(2^4 = 16\) 个子集),完全不用任何第三方库,亲手训练全部 16 个子集模型按定义算出精确 Shapley 值,亲眼验证有效性公理达到 \(10^{-15}\) 机器精度!

In [12] · Python
# ▶️ 运行看看:用 2^4 = 16 个重训模型手写精确 Shapley 值,检验有效性公理!
F4 = ["MolLogP", "MolWt", "PolarSurfaceFrac", "AromaticAtomFrac"]
BASE_VAL_4 = float(y_tr.mean())

sub_models = {}
for r in range(len(F4) + 1):
    for S in itertools.combinations(F4, r):
        sub_models[S] = None if not S else RandomForestRegressor(
            n_estimators=60, random_state=0, n_jobs=-1
        ).fit(X_tr[list(S)], y_tr)

def v_coalition(S_set, x_row):
    S_tup = tuple(f for f in F4 if f in S_set)
    if not S_tup:
        return BASE_VAL_4
    return float(sub_models[S_tup].predict(pd.DataFrame([x_row[list(S_tup)]]))[0])

def exact_shapley_4(x_row):
    M_ = len(F4)
    phi = {}
    for f in F4:
        others = [g for g in F4 if g != f]
        acc = 0.0
        for r in range(len(others) + 1):
            for S in itertools.combinations(others, r):
                w = math.factorial(len(S)) * math.factorial(M_ - len(S) - 1) / math.factorial(M_)
                acc += w * (v_coalition(set(S) | {f}, x_row) - v_coalition(set(S), x_row))
        phi[f] = acc
    return phi

x0 = X_te[F4].iloc[0]
phi0 = exact_shapley_4(x0)
pred0 = v_coalition(set(F4), x0)

print("待解释测试分子特征值:", x0.round(3).to_dict())
for f, val in sorted(phi0.items(), key=lambda kv: -abs(kv[1])):
    print(f"  Exact phi({f:<18s}) = {val:+.4f} logS")
print(f"\n有效性检验: E[y] ({BASE_VAL_4:+.4f}) + sum(phi) ({sum(phi0.values()):+.4f}) = {BASE_VAL_4 + sum(phi0.values()):+.6f}")
print(f"全特征模型预测 v(F) = {pred0:+.6f} | 绝对残差 = {abs(BASE_VAL_4 + sum(phi0.values()) - pred0):.2e}")
Out:
待解释测试分子特征值: {'MolLogP': 2.329, 'MolWt': 214.22, 'PolarSurfaceFrac': 0.621, 'AromaticAtomFrac': 0.75}
  Exact phi(MolWt             ) = +0.4434 logS
  Exact phi(PolarSurfaceFrac  ) = -0.3491 logS
  Exact phi(AromaticAtomFrac  ) = -0.2832 logS
  Exact phi(MolLogP           ) = +0.0322 logS

有效性检验: E[y] (-2.9655) + sum(phi) (-0.1567) = -3.122235
全特征模型预测 v(F) = -3.122235 | 绝对残差 = 8.88e-16

📘 3.2 shap.TreeExplainer:全局蜂群图与单分子/并苯系列局部瀑布图

当特征数 \(M=10\) 或 \(34\) 时,\(2^{34} \approx 1.7 \times 10^{10}\) 个模型根本不可能穷举重训。Lundberg 等人提出的 TreeSHAP 利用决策树的分支结构,在不重训模型的前提下以多项式时间精确算出条件期望 Shapley 值。下面我们在 RFE 选出的 10 维核心特征上训练模型,同时绘制:

  1. 全局蜂群图(Beeswarm Plot):一眼看清每个特征的高值(红)/低值(蓝)把溶解度往哪边推;
  2. 局部单分子瀑布图(Waterfall Plot):把经典有机半导体 并五苯(Pentacene) 为什么极难溶于水(预测 \(\log S < -7\))一步步拆解成定量化学证据!
In [13] · Python
model_shap = RandomForestRegressor(n_estimators=200, random_state=0, n_jobs=-1).fit(X_tr[cols_rfe], y_tr)
explainer = shap.TreeExplainer(model_shap)

X_explain = X_te[cols_rfe].iloc[:250]
sv_test = explainer.shap_values(X_explain)
base_val_tree = float(np.ravel(explainer.expected_value)[0])

with plt.rc_context({"figure.constrained_layout.use": False}):
    shap.summary_plot(sv_test, X_explain, show=False, plot_size=(8.2, 4.6))
    plt.title("Global TreeSHAP Beeswarm on Top-10 Interpretable Features", fontsize=11.5)
    plt.tight_layout()
    plt.show()

# 构造并苯系列 (萘 -> 蒽 -> 并四苯 -> 并五苯) 的特征行,并对并五苯画单分子瀑布图!
ALL_DESC_FN = {**{c: getattr(Descriptors, c) for c in BASE_COLS}, **EXTRA_DESC}
acene_dict = {
    "Naphthalene (2 rings)": "c1ccc2ccccc2c1",
    "Anthracene (3 rings)":  "c1ccc2cc3ccccc3cc2c1",
    "Tetracene (4 rings)":   "c1ccc2cc3cc4ccccc4cc3cc2c1",
    "Pentacene (5 rings)":   "c1ccc2cc3cc4cc5ccccc5cc4cc3cc2c1",
}
acene_raw_rows = []
for nm, smi in acene_dict.items():
    m = Chem.MolFromSmiles(smi)
    r = {k: fn(m) for k, fn in ALL_DESC_FN.items()}
    r["_AromAtoms"] = sum(a.GetIsAromatic() for a in m.GetAtoms())
    acene_raw_rows.append(r)

X_acenes_all = DomainFeatureBuilder(include_ratios=True).fit_transform(
    pd.DataFrame(acene_raw_rows, index=list(acene_dict.keys()))
)
X_acenes = X_acenes_all[cols_rfe]
sv_acenes = explainer.shap_values(X_acenes)

exp_pentacene = shap.Explanation(
    values=sv_acenes[-1],
    base_values=base_val_tree,
    data=X_acenes.iloc[-1].values,
    feature_names=cols_rfe,
)
with plt.rc_context({"figure.constrained_layout.use": False}):
    shap.plots.waterfall(exp_pentacene, max_display=10, show=False)
    plt.title("Local Waterfall Attribution: Why Is Pentacene Insoluble in Water?", fontsize=11)
    plt.tight_layout()
    plt.show()
Out:
C:\Users\18101\AppData\Local\Temp\ipykernel_5168\222259212.py:9: FutureWarning: The NumPy global RNG was seeded by calling `np.random.seed`. In a future version this function will no longer use the global RNG. Pass `rng` explicitly to opt-in to the new behaviour and silence this warning.
  shap.summary_plot(sv_test, X_explain, show=False, plot_size=(8.2, 4.6))
Notebook 输出图像 Notebook 输出图像

看这两张图多么富有物理洞察力:

  • 全局蜂群图中,MolLogP 的红点(高脂溶性)整齐划一地把 \(\log S\) 往左侧负方向猛推 3–4 个数量级(完美对应 Yalkowsky 方程的 \(-\log P\) 溶剂化项!),而我们亲手构造的 PolarSurfaceFrac 与 HBondDensity 红点全部排在右侧增溶端;
  • 并五苯的局部瀑布图则从全库均值 \(\mathbb{E}[\hat{y}] \approx -2.7\) 起步,清楚标出:极高的 MolLogP = 6.03 单独砸下超过 \(-3.5\) 个对数单位,零极性表面(PolarSurfaceFrac = 0)与高结构复杂度 BertzCT 继续往下拉,最终精确落脚在模型预测的极难溶区间!

📘 3.3 正面交锋:强共线性下 MDI vs. 置换重要性 vs. SHAP 谁在说真话?

最后,我们刻意把一对相关性高达 \(|r| \approx 0.98\) 的孪生尺寸特征——MolWt(分子量)与 HeavyAtomCount(重原子数)——同时放进同一个随机森林,并排对比三种特征重要性指标的表现:

In [14] · Python
COLLINEAR_COLS = ["MolLogP", "MolWt", "HeavyAtomCount", "PolarSurfaceFrac", "AromaticAtomFrac", "RingDensity"]
rf_col = RandomForestRegressor(n_estimators=200, random_state=0, n_jobs=-1).fit(X_tr[COLLINEAR_COLS], y_tr)

imp_mdi = pd.Series(rf_col.feature_importances_, index=COLLINEAR_COLS)
perm_res = permutation_importance(rf_col, X_te[COLLINEAR_COLS], y_te, n_repeats=10, random_state=0, n_jobs=-1)
imp_perm = pd.Series(np.maximum(perm_res.importances_mean, 0.0), index=COLLINEAR_COLS)
sv_col = shap.TreeExplainer(rf_col).shap_values(X_te[COLLINEAR_COLS].iloc[:250])
imp_shap = pd.Series(np.abs(sv_col).mean(axis=0), index=COLLINEAR_COLS)

comp_df = pd.DataFrame({
    "MDI (Tree Split)":       imp_mdi / imp_mdi.sum(),
    "Permutation (Test Set)": imp_perm / imp_perm.sum(),
    "SHAP (mean |phi|)":      imp_shap / imp_shap.sum(),
})
print(f"训练集 r(MolWt, HeavyAtomCount) = {np.corrcoef(X_tr['MolWt'], X_tr['HeavyAtomCount'])[0, 1]:.4f}")
print(comp_df.round(3).to_string())

ax = comp_df.plot(kind="bar", figsize=(8.6, 4.0), rot=22, width=0.76, color=[C.navy, C.gold, C.crimson])
ax.set_ylabel("Normalized importance share")
ax.set_title("MDI vs Permutation Importance vs SHAP Under Strong Collinearity (r = 0.98)")
plt.tight_layout()
plt.show()
Out:
训练集 r(MolWt, HeavyAtomCount) = 0.9369
                  MDI (Tree Split)  Permutation (Test Set)  SHAP (mean |phi|)
MolLogP                      0.717                   0.792              0.644
MolWt                        0.086                   0.046              0.101
HeavyAtomCount               0.071                   0.052              0.098
PolarSurfaceFrac             0.066                   0.080              0.069
AromaticAtomFrac             0.028                   0.014              0.052
RingDensity                  0.031                   0.016              0.036
Notebook 输出图像

💡 实践黄金准则:当 MolWt 和 HeavyAtomCount 同时在场时,置换重要性(金色柱)几乎把两者的作用严重低估(因为打乱 HeavyAtomCount 时,树沿着没被打乱的 MolWt 分支照样猜对,两个共线特征互相“打掩护”!)。因此,做科学机理归因的标准流程永远是:先在 Pipeline 或预处理中完成共线性剪枝去冗余(第 2 节),再用 TreeSHAP 做全局与局部归因(第 3 节)!

🏋️ 练习 05b-3:并苯同系物(萘 \(\to\) 蒽 \(\to\) 并四苯 \(\to\) 并五苯)的 SHAP 贡献分解图

利用上一小节已经算好的 X_acenes(4 个并苯分子 \(\times\) 10 个核心特征)与 sv_acenes:

  1. 将 4 个分子的各特征 SHAP 值、base_val_tree 与模型预测值整理成一张清晰的 DataFrame;
  2. 绘制分组柱状图或堆叠演变图,定量回答:从二环的萘一路扩环到五环的并五苯,预测 \(\log S\) 总共下降了多少个对数单位?其中排名前二的主导特征各自贡献了多少?模型在这里还漏掉了什么关键固态物理量(提示:并五苯熔点 \(>300\,^\circ\text{C}\))?
In [15] · Python
# 在下方填写你的代码(参考答案见 solutions/05_feature_solutions.ipynb):

本节小结

核心环节 方法与工具 关键规律与防坑指南
领域特征构造 DomainFeatureBuilder(PolarSurfaceFrac、AromaticAtomFrac 等) 把广延计数转成无量纲强度比值,直接解锁线性模型与小样本模型的非线性表达力
过滤法与互信息 准常量筛查 + \(|r|>0.90\) 剪枝 + mutual_info_regression Pearson \(|r|\) 对倒 U 型物理窗口(火山曲线/容差因子)彻底失明,互信息 MI 可捕获任意非线性依赖
无泄漏 Pipeline 降维 Pipeline + LassoCV / RFE(34 \(\to\) 10 维) 砍掉 70% 冗余特征而 CV \(R^2\) 不掉;小样本高维下若在 CV 前选特征会制造 0.2+ 的虚假 \(R^2\) 泡沫
SHAP 可解释归因 16 子集精确 Shapley + TreeExplainer 蜂群图/瀑布图 严格满足 \(\hat{y}(x) = \mathbb{E}[\hat{y}] + \sum \phi_i(x)\);解释前务必先剪除强共线特征

下一节预告(05c_3d_conformers_geometry_and_databases.ipynb):到目前为止,我们所有的特征都停留在二维拓扑图上。如果分子在三维空间里折叠、或者我们要把三维原子坐标喂给机器学习势函数(MLIP)与晶体模型,为什么直接输入 \((x,y,z)\) 笛卡尔坐标会一败涂地?怎样用 库仑矩阵(Coulomb Matrix) 与 原子中心对称函数(ACSF / SOAP) 实现严格的平移、旋转与置换不变性?又怎样用 PubChem API 把缺失的固态实验熔点 \(T_m\) 抓回来,一举解开 Yalkowsky 溶解度方程的最后一块拼图?进入 05c!

读完了?

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

返回模块 05