课件答案 05 — 特征工程、SHAP 与三维分子:随堂练习参考答案(Solutions)
直接阅读答案的学习效果远低于独立实现。建议至少尝试 20 分钟,卡住时先看习题里的 💡 提示,再展开本页。
展开状态只在当前浏览器标签页有效,关闭标签页后会重新折叠。
本 Notebook 汇总了第五讲 05a_feature_selection_and_shap.ipynb 与 05b_conformers_and_pubchem.ipynb 中全部 6 道随堂练习(05a-1 至 05b-3)的完整可运行参考代码与物理化学解析。
0. 公共环境与数据准备
下面这一格复现 05a 第 2 节的 29 列描述符矩阵,供后面各题直接使用。
import os
import time
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import (train_test_split, cross_val_predict,
KFold, LeaveOneOut)
from sklearn.ensemble import RandomForestRegressor
from sklearn.feature_selection import RFE, RFECV
from rdkit import Chem, RDLogger
from rdkit.Chem import (AllChem, Descriptors, Descriptors3D,
rdMolDescriptors, rdMolAlign)
RDLogger.DisableLog("rdApp.*")
plt.rcParams["figure.dpi"] = 110
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}")
📘 课程统一绘图风格:下面这格加载课程自带的
ai4m.mplstyle(配色与课程网站同源,无上右边框,仅横向浅网格,保存默认 300 dpi)。C是课程配色,手动指定颜色时写color=C.crimson。
# ai4m-style:课程统一绘图风格(solutions/ 子目录与 Colab 通用)
import pathlib, sys
for _p in (pathlib.Path.cwd().parent, pathlib.Path.cwd().parent.parent):
sys.path.insert(0, str(_p)) # course/ 根目录
import ai4m_style as ai4m
C = ai4m.use() # 应用 ai4m.mplstyle,返回课程配色
df_all = pd.read_csv(find_file("solubility.csv"))
df_all = df_all[(df_all["MolWt"] > 20) & (df_all["MolWt"] < 800)].reset_index(drop=True)
sub = df_all.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,
}
rows, keep_idx = [], []
for i, smi in enumerate(sub["SMILES"]):
mol = Chem.MolFromSmiles(smi)
if mol is None:
continue
try:
rows.append({k: fn(mol) for k, fn in EXTRA_DESC.items()})
except Exception:
continue
keep_idx.append(i)
sub = sub.loc[keep_idx].reset_index(drop=True)
BASE_COLS = [c for c in df_all.columns if c not in ("Name", "SMILES", "Solubility")]
X_full = pd.concat([sub[BASE_COLS], pd.DataFrame(rows).reset_index(drop=True)], axis=1)
X_full = X_full.fillna(X_full.median())
y = sub["Solubility"].values
X_tr, X_te, y_tr, y_te = train_test_split(X_full, y, test_size=0.2, random_state=42)
top_share = X_tr.apply(lambda s: s.value_counts(normalize=True).iloc[0])
print(f"X_full: {X_full.shape[0]} 个分子 × {X_full.shape[1]} 个描述符")
05a — 特征选择与 SHAP 归因练习答案
练习 05a-1:方差过滤阈值的敏感性分析
题目回顾:把“最高频取值占比”的阈值依次取 0.95 ~ 0.50,统计保留的特征数与测试集 \(R^2\),画出折线图。
CUTOFFS = [0.95, 0.90, 0.85, 0.80, 0.70, 0.60, 0.50]
sens = []
for thr in CUTOFFS:
cols = [c for c in X_full.columns if top_share[c] <= thr]
model = RandomForestRegressor(n_estimators=200, random_state=0, n_jobs=-1).fit(X_tr[cols], y_tr)
sens.append({"cutoff": thr, "n_kept": len(cols),
"test_r2": round(model.score(X_te[cols], y_te), 4)})
sens = pd.DataFrame(sens)
print(sens.to_string(index=False))
fig, ax = plt.subplots(figsize=(7.2, 4.2))
ax.plot(sens["n_kept"], sens["test_r2"], "o-", lw=1.8, ms=8, color=C.navy)
for _, r in sens.iterrows():
ax.annotate(f"{r['cutoff']:.2f}", (r["n_kept"], r["test_r2"]),
textcoords="offset points", xytext=(5, 7), fontsize=8)
ax.set_xlabel("Number of descriptors kept")
ax.set_ylabel("Test R2")
ax.set_title("Variance-filter Cutoff Sensitivity (labels = cutoff value)")
plt.show()
解析:这条曲线几乎是水平的——从 28 个特征一路砍到 24 个,测试集 \(R^2\) 的波动都在 \(\pm 0.002\) 以内,完全淹没在随机森林自身的随机性里。
这正是方差过滤的真实定位:它是一个安全但收益有限的清理步骤。被它扔掉的 NumRadicalElectrons、NumSaturatedRings 等列在树模型里本来就很少被选中做分裂,删不删都一样。它真正的价值体现在:
- 把特征表缩短,便于人工检查与汇报;
- 为后续昂贵的步骤(RFE、SHAP)减负;
- 对线性模型 / kNN / 神经网络而言,准常量列会带来实实在在的数值问题。
注意阈值降到 0.70 以下后保留数不再变化——因为这个数据集里就没有占比落在 0.5–0.7 区间的描述符。
练习 05a-2:用 RFECV 自动确定该保留几个特征
题目回顾:用 RFECV 在每个候选特征数上做 3 折交叉验证,打印最优特征数与入选特征,并画出“特征数 vs CV \(R^2\)”曲线。
t0 = time.time()
rfecv = 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=3,
).fit(X_tr, y_tr)
print(f"RFECV 用时 {time.time() - t0:.1f} s")
print(f"\n交叉验证选出的最优特征数 n_features_ = {rfecv.n_features_}")
print("入选特征:", list(X_full.columns[rfecv.support_]))
scores = rfecv.cv_results_["mean_test_score"]
stds = rfecv.cv_results_["std_test_score"]
sizes = 3 + 2 * np.arange(len(scores)) # min_features_to_select + k * step
fig, ax = plt.subplots(figsize=(7.6, 4.3))
ax.errorbar(sizes, scores, yerr=stds, fmt="o-", capsize=3, lw=1.6, color=C.navy)
ax.axvline(rfecv.n_features_, color=C.crimson, ls="--", lw=1.6,
label=f"best = {rfecv.n_features_} features")
ax.set_xlabel("Number of features selected")
ax.set_ylabel("3-fold CV R2")
ax.set_title("RFECV: Cross-validated Score vs Number of Features")
ax.legend()
plt.show()
解析:曲线在 10 个特征左右就已经基本爬到平台期,之后一路平坦——这与 05a 第 6 节的横评结论完全一致。
RFECV 挑出的“最优”特征数往往明显偏大(这里是 25),因为它只认交叉验证分数的最高点,而平台期上各点的差异完全落在折间标准差之内。实践中更稳妥的做法是采用 one-standard-error 规则:在所有得分不低于“最高分 − 1 个标准误”的候选里,选特征数最少的那一个。这样既保住了精度,又拿到了最简洁的模型。
练习 05a-3:对比三个并苯类有机半导体分子的 SHAP 归因
题目回顾:为萘、蒽、并五苯计算 cols_rfe 中的描述符,用 shap.TreeExplainer 得到它们的 SHAP 值,整理成表并用分组柱状图对比。
try:
import shap
except ImportError:
import subprocess, sys as _sys
subprocess.run([_sys.executable, "-m", "pip", "install", "-q", "shap"], check=True)
import shap
# 复现 05a 第 5 节的 RFE 选择与第 9 节的解释器
rfe = RFE(RandomForestRegressor(n_estimators=100, random_state=0, n_jobs=-1),
n_features_to_select=10, step=2).fit(X_tr, y_tr)
cols_rfe = list(X_full.columns[rfe.support_])
model_shap = RandomForestRegressor(n_estimators=200, random_state=0, n_jobs=-1).fit(X_tr[cols_rfe], y_tr)
explainer = shap.TreeExplainer(model_shap)
base_value = float(np.ravel(explainer.expected_value)[0])
# 统一的描述符计算字典:CSV 自带列 + 我们补算的列,名字都与 RDKit 函数同名
ALL_DESC = {**{c: getattr(Descriptors, c) for c in BASE_COLS}, **EXTRA_DESC}
ACENES = {
"Naphthalene": "c1ccc2ccccc2c1",
"Anthracene": "c1ccc2cc3ccccc3cc2c1",
"Pentacene": "c1ccc2cc3cc4cc5ccccc5cc4cc3cc2c1",
}
X_acene = pd.DataFrame(
{name: {c: ALL_DESC[c](Chem.MolFromSmiles(smi)) for c in cols_rfe}
for name, smi in ACENES.items()}
).T[cols_rfe]
sv_acene = explainer.shap_values(X_acene)
table = pd.DataFrame(sv_acene, index=X_acene.index, columns=cols_rfe)
table["base_value"] = base_value
table["pred_logS"] = model_shap.predict(X_acene)
print("三个并苯分子的描述符取值:")
print(X_acene.round(2).to_string())
print("\n各描述符的 SHAP 贡献(单位:log S):")
print(table.round(3).to_string())
fig, ax = plt.subplots(figsize=(10.5, 4.4))
width = 0.26
xs = np.arange(len(cols_rfe))
for k, (name, color) in enumerate(zip(table.index, [C.navy, C.gold, C.crimson])):
ax.bar(xs + (k - 1) * width, table.loc[name, cols_rfe].values, width,
label=f"{name} (pred logS = {table.loc[name, 'pred_logS']:.2f})", color=color)
ax.axhline(0, color="#555555", lw=1)
ax.set_xticks(xs)
ax.set_xticklabels(cols_rfe, rotation=35, ha="right", fontsize=8)
ax.set_ylabel("SHAP value [log S]")
ax.set_title(f"SHAP Attribution across the Acene Series (base value = {base_value:.2f})")
ax.legend(fontsize=9)
plt.show()
解析:从萘到蒽再到并五苯,预测 \(\log S\) 一路从约 \(-3.5\) 掉到约 \(-8.2\),而这近 5 个对数单位的下降几乎全部由 MolLogP 一根柱子贡献(其 SHAP 值从约 \(-0.4\) 一路压到约 \(-3.8\))。
这正是 05a 全局蜂群图在单分子尺度上的再现:模型学到的核心规律就是“疏水性越强越难溶”。每多一个稠合苯环,MolLogP 就增加约 1.1,SHAP 贡献随之线性加深。
与此同时,BertzCT(结构复杂度)、Kappa2(形状指数)、FractionCSP3(\(sp^3\) 碳占比)等描述符也都在朝“更难溶”方向小幅推动,但量级只有 MolLogP 的十分之一。
这个结果同时暴露了模型的盲区:真实的并苯溶解度下降不只是疏水性的问题——并五苯极高的熔点意味着极稳定的 herringbone 晶格,而模型的 10 个描述符里没有任何一个携带熔点信息。这正是 05b 要解决的问题。
05b — 三维构象与 PubChem API 练习答案
练习 05b-1:构象数与可旋转键数的关系
题目回顾:对苯、联苯、邻苯二甲酸二丁酯、C8-BTBT 各生成 50 个构象,按 RMSD > 0.5 Å 去重,画出“可旋转键数 vs 独立构象数”。
SMI_C8BTBT = "CCCCCCCCc1ccc2c(c1)sc1c2sc2cc(CCCCCCCC)ccc21"
PROBES = {
"Benzene": "c1ccccc1",
"Biphenyl": "c1ccc(-c2ccccc2)cc1",
"Dibutyl phthalate": "CCCCOC(=O)c1ccccc1C(=O)OCCCC",
"C8-BTBT": SMI_C8BTBT,
}
N_CONFS, RMS_THRESH = 50, 0.5
def conformer_census(smi, n_confs=N_CONFS, rms_thresh=RMS_THRESH, seed=42):
"""生成系综、MMFF 优化、按 RMSD 去重,返回 (独立构象数, 能量跨度)。"""
mol = Chem.AddHs(Chem.MolFromSmiles(smi))
ps = AllChem.ETKDGv3()
ps.randomSeed = seed
ps.pruneRmsThresh = -1.0
AllChem.EmbedMultipleConfs(mol, numConfs=n_confs, params=ps)
res = AllChem.MMFFOptimizeMoleculeConfs(mol, maxIters=800)
E = np.array([e for _c, e in res])
order = np.argsort(E)
no_h = Chem.RemoveHs(mol)
unique = []
for cid in order:
cid = int(cid)
if all(rdMolAlign.GetBestRMS(no_h, no_h, prbId=cid, refId=u) > rms_thresh
for u in unique):
unique.append(cid)
return len(unique), float(E.max() - E.min())
census = []
for name, smi in PROBES.items():
t0 = time.time()
n_uniq, span = conformer_census(smi)
census.append({
"molecule": name,
"n_rot": Descriptors.NumRotatableBonds(Chem.MolFromSmiles(smi)),
"n_embedded": N_CONFS,
"n_unique": n_uniq,
"E_span_kcal": round(span, 2),
"seconds": round(time.time() - t0, 1),
})
census = pd.DataFrame(census)
print(census.to_string(index=False))
fig, ax = plt.subplots(figsize=(7, 4.3))
ax.plot(census["n_rot"], census["n_unique"], "o-", lw=1.8, ms=10, color=C.crimson)
for _, r in census.iterrows():
ax.annotate(r["molecule"], (r["n_rot"], r["n_unique"]),
textcoords="offset points", xytext=(8, -4), fontsize=9)
ax.axhline(N_CONFS, color="#999999", ls="--", lw=1.2, label=f"numConfs = {N_CONFS} (ceiling)")
ax.set_xlabel("Number of rotatable bonds")
ax.set_ylabel(f"Unique conformers (RMSD > {RMS_THRESH} A)")
ax.set_title("Conformational Flexibility vs Rotatable Bond Count")
ax.legend(fontsize=9)
plt.show()
解析:结果呈现出教科书般的单调上升:
| 分子 | 可旋转键 | 独立构象数 | 能量跨度 |
|---|---|---|---|
| 苯 | 0 | 1 | 0 kcal/mol |
| 联苯 | 1 | 2 | 约 0 kcal/mol |
| 邻苯二甲酸二丁酯 | 8 | 约 40 | 约 4 kcal/mol |
| C8-BTBT | 14 | 50(全部) | 约 9 kcal/mol |
三条可以直接用到自己课题里的结论:
- 刚性稠环体系(苯、蒽、并五苯、BTBT 母核)用单构象近似完全安全——50 次嵌入只得到 1–2 个独立构象,多算纯属浪费。
- 柔性分子的
numConfs远远不够:C8-BTBT 的 50 个构象一个都没被合并,说明我们连它构象空间的边都没摸到。对这类分子,Ebejer 规则建议的 300 个也只是起点。 - 能量跨度随柔性增长:苯的所有构象能量完全相同;C8-BTBT 的跨度达到 9 kcal/mol,是 \(k_B T\)(0.59 kcal/mol)的 15 倍——意味着高能构象在室温下的 Boltzmann 布居可以忽略,但低能的那十几个必须一起算。
练习 05b-2:构象系综会让 3D 描述符飘多少?
题目回顾:对邻苯二甲酸二丁酯生成 50 个构象,统计 RadiusOfGyration、Asphericity、NPR1 在系综中的分布,并比较简单平均与 Boltzmann 加权平均。
KT_298 = 0.593
SMI_DBP = "CCCCOC(=O)c1ccccc1C(=O)OCCCC"
mol = Chem.AddHs(Chem.MolFromSmiles(SMI_DBP))
ps = AllChem.ETKDGv3()
ps.randomSeed = 42
ps.pruneRmsThresh = -1.0
cids = AllChem.EmbedMultipleConfs(mol, numConfs=50, params=ps)
res = AllChem.MMFFOptimizeMoleculeConfs(mol, maxIters=800)
E = np.array([e for _c, e in res])
E_rel = E - E.min()
w = np.exp(-E_rel / KT_298)
w /= w.sum()
ens = pd.DataFrame({
"RadiusOfGyration": [Descriptors3D.RadiusOfGyration(mol, confId=int(c)) for c in cids],
"Asphericity": [Descriptors3D.Asphericity(mol, confId=int(c)) for c in cids],
"NPR1": [Descriptors3D.NPR1(mol, confId=int(c)) for c in cids],
})
summary = pd.DataFrame({
"min": ens.min(),
"max": ens.max(),
"range": ens.max() - ens.min(),
"std": ens.std(),
"mean": ens.mean(),
"boltzmann": (ens.T * w).T.sum(),
})
summary["mean - boltzmann"] = summary["mean"] - summary["boltzmann"]
print(summary.round(3).to_string())
fig, axes = plt.subplots(1, 3, figsize=(12, 3.8))
for ax, col in zip(axes, ens.columns):
ax.hist(ens[col], bins=14, color=C.navy, alpha=0.8)
ax.axvline(ens[col].mean(), color=C.gold, lw=2, label="simple mean")
ax.axvline(float((ens[col] * w).sum()), color=C.crimson, lw=2, ls="--", label="Boltzmann")
ax.set_xlabel(col)
ax.set_ylabel("Count")
axes[0].legend(fontsize=8)
fig.suptitle("Conformer-dependence of 3D Descriptors (Dibutyl phthalate, 50 conformers)",
fontsize=11)
plt.show()
解析:三个描述符在同一个分子的系综内波动都很可观:
RadiusOfGyration从约 3.2 Å 跨到约 3.9 Å——相差 0.6 Å 以上,比许多 QSAR 模型中该描述符的全数据集标准差还大;NPR1从约 0.19 跨到约 0.58,相当于这个分子在形状三角里从“棒状”一路晃到“盘状”;- Boltzmann 加权值与简单平均值也有明显差异(低能构象往往更伸展,被加权后把均值往那个方向拉)。
结论直接而严厉:如果一篇论文只写“用 RDKit 计算了 3D 描述符”而不交代
- 生成了多少个构象(
numConfs)、用了什么随机种子, - 是取能量最低的单构象、简单平均,还是 Boltzmann 加权,
- 用了什么力场(MMFF94 还是 UFF)、优化了多少步,
那么它的 3D 描述符部分在原则上就是不可复现的——换一个人跑,拿到的数值可以差出一个标准差。这也是 3D 描述符在实践中远不如 2D 描述符普及的根本原因之一。
练习 05b-3:把熔点加进机器学习模型
题目回顾:在 79 个分子的熔点数据集上,用留一交叉验证比较 A(仅 2D 描述符)、B(2D + \(T_m\))、C(仅 \(\log P\) + \(T_m\))三个随机森林。
mp_df = pd.read_csv(find_file("melting_points.csv"))
D2_FUNCS = {
"MolWt": Descriptors.MolWt,
"MolLogP": Descriptors.MolLogP,
"TPSA": Descriptors.TPSA,
"NumAromaticRings": Descriptors.NumAromaticRings,
"NumHDonors": Descriptors.NumHDonors,
"NumHAcceptors": Descriptors.NumHAcceptors,
"BertzCT": Descriptors.BertzCT,
"NumRotatableBonds": Descriptors.NumRotatableBonds,
}
X_2d = pd.DataFrame([{k: fn(Chem.MolFromSmiles(s)) for k, fn in D2_FUNCS.items()}
for s in mp_df["SMILES"]])
y_mp = mp_df["logS"].values
VARIANTS = {
"A: 2D only (8)": X_2d,
"B: 2D + Tm (9)": X_2d.assign(Tm_C=mp_df["Tm_C"].values),
"C: logP + Tm (2)": pd.DataFrame({"MolLogP": X_2d["MolLogP"],
"Tm_C": mp_df["Tm_C"].values}),
}
loo_pred, report = {}, []
for name, Xv in VARIANTS.items():
pred = cross_val_predict(
RandomForestRegressor(n_estimators=300, random_state=0, n_jobs=-1),
Xv, y_mp, cv=LeaveOneOut(),
)
loo_pred[name] = pred
rmse = np.sqrt(np.mean((pred - y_mp) ** 2))
r2 = 1 - np.sum((pred - y_mp) ** 2) / np.sum((y_mp - y_mp.mean()) ** 2)
report.append({"model": name, "n_features": Xv.shape[1],
"LOO_RMSE": round(rmse, 3), "LOO_R2": round(r2, 3)})
report = pd.DataFrame(report)
print(report.to_string(index=False))
best = "B: 2D + Tm (9)"
pred_b = loo_pred[best]
fig, axes = plt.subplots(1, 2, figsize=(11, 4.4))
sc = axes[0].scatter(y_mp, pred_b, c=mp_df["Tm_C"], cmap="plasma", s=48, edgecolor="none")
lims = [-9.5, 1.5]
axes[0].plot(lims, lims, "--", color="#888888", lw=1.2)
axes[0].set_xlim(lims)
axes[0].set_ylim(lims)
axes[0].set_xlabel("Measured logS")
axes[0].set_ylabel("LOO predicted logS")
axes[0].set_title(f"{best}\nLOO RMSE = {np.sqrt(np.mean((pred_b - y_mp) ** 2)):.3f}", fontsize=10)
plt.colorbar(sc, ax=axes[0], label="Melting point / degC")
axes[1].bar(report["model"], report["LOO_RMSE"], color=[C.navy, C.crimson, C.gold], width=0.55)
for i, r in report.iterrows():
axes[1].text(i, r["LOO_RMSE"] + 0.012, f"{r['LOO_RMSE']:.3f}", ha="center", fontsize=10)
axes[1].set_ylabel("LOO RMSE [log units]")
axes[1].set_title("Lower is better")
axes[1].tick_params(axis="x", labelrotation=12, labelsize=8)
plt.show()
解析:三个模型的 LOO 表现非常接近,但对比方式本身给出了三条有价值的结论:
- 加入 \(T_m\) 确有收益:B 比 A 的 RMSE 更低——在只有 79 个样本的小数据集上,一列真实的实验物理量比再多几个相互冗余的拓扑描述符更有信息量。
- 模型 C 用两个变量就逼近了模型 B:仅凭 \(\log P\) 和 \(T_m\),随机森林就能达到与 8 个 2D 描述符相当的精度。这不是巧合——Yalkowsky 方程早就告诉我们这两个变量就是溶解度的物理主因,机器学习只是把这个结论重新发现了一遍。
- 小样本上随机森林并不比线性模型强:回看
05b第 7.1 节,同一批数据上一个两变量的线性回归拿到了同等甚至更好的 LOO 成绩。当样本只有几十个、而物理机制又近似线性时,线性模型往往是更好的选择——它参数少、不易过拟合,而且系数本身就有物理意义(可以直接和 \(-1\)、\(-0.01\) 对比)。
📌 带走的方法论:与其在同一批 2D 描述符上反复调参刷 \(R^2\),不如去找一列模型目前完全没有的物理量(熔点、介电常数、晶体密度、器件工艺参数)。信息增益来自新的物理维度,而不是新的超参数。