02d · 分类模型与概率:感知机、逻辑回归、评估指标与物理归因
02d · 分类模型与概率:感知机、逻辑回归、评估指标与物理归因
在 02a–02c 中,我们预测的是连续的水溶解度数值 \(\log S\)(回归任务)。但在高通量材料筛查(High-Throughput Screening)中,实验人员往往更关心一个干脆利落的二选一决策:
“这批候选分子里,哪些几乎不溶(\(\log S < -4\),趁早淘汰),哪些能溶(放行进入合成与测试)?”
当输出变成离散类别标签时,任务就进入了分类(Classification)。本节我们将从 10 行代码手写感知机(Perceptron,“判错就挪直线”)出发,理解为什么加上 Sigmoid 就能变成输出连续概率的逻辑回归(Logistic Regression),掌握全套防坑分类评估指标(混淆矩阵、Precision/Recall、ROC-AUC 与阈值移动),并结合 Yalkowsky 通用溶解度方程剖析有机半导体筛查与金属盐/高熔点晶体的错分真相。
本节内容
- 定义 AqSolDB 难溶分子二分类任务与分层抽样(
stratify) - 从硬边界到连续概率:手写感知机(Perceptron) \(\to\) Sigmoid 与逻辑回归
- 分类评估体系:准确率陷阱、混淆矩阵、Precision / Recall / F1 / ROC-AUC 与决策阈值调节
- 有机半导体溶解度筛查(
BTBTvsC8-BTBT的溶剂先验启示) - 打开模型黑箱:MDI vs 置换重要性、Yalkowsky 方程与金属盐/晶格堆积错分破案
# 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"))
get_ipython().run_line_magic("pip", "install -q rdkit xgboost")
0. 环境准备与读取 AqSolDB 数据
try:
import rdkit
except ImportError:
%pip install -q rdkit
import rdkit
try:
import xgboost
except ImportError:
%pip install -q xgboost
import xgboost
import os
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from rdkit import Chem, RDLogger
from rdkit.Chem import Descriptors, Draw
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import make_pipeline
from sklearn.dummy import DummyClassifier
from sklearn.linear_model import Perceptron, LogisticRegression
from sklearn.ensemble import RandomForestClassifier
from sklearn.inspection import permutation_importance
from sklearn.metrics import (
accuracy_score, precision_score, recall_score, f1_score,
roc_auc_score, confusion_matrix, ConfusionMatrixDisplay, roc_curve,
)
RDLogger.DisableLog("rdApp.*")
📘 课程统一绘图风格:下面这格加载课程自带的
ai4m.mplstyle(配色与课程网站同源,无上右边框,仅横向浅网格,保存默认 300 dpi)。C是课程配色,手动指定颜色时写color=C.crimson。
# ai4m-style:课程统一绘图风格(本地与 Colab 通用)
import pathlib, sys
sys.path.insert(0, str(pathlib.Path.cwd().parent)) # course/ 根目录
import ai4m_style as ai4m
C = ai4m.use() # 应用 ai4m.mplstyle,返回课程配色
1. 定义“难溶分子筛查”二分类任务与分层抽样
在药物与有机功能分子经验规则中,水溶解度 \(\log S < -4.0\)(摩尔浓度 \(< 10^{-4}\text{ mol/L}\))通常被划为难溶(Insoluble)警戒线。既然我们的目标是把难溶分子揪出来报警拦截,就将“难溶”定义为正类(Positive = 1),“不难溶/可溶”定义为负类(Negative = 0):
划分训练/测试集时,加上 stratify=y(分层抽样),可确保训练集和测试集中的难溶分子占比与全库严格一致:
DATA_FILE = "data/solubility.csv" if os.path.exists("data/solubility.csv") else "../01 - Basics/data/solubility.csv"
df = pd.read_csv(DATA_FILE)
df["mol"] = df["SMILES"].apply(Chem.MolFromSmiles)
df = df[df["mol"].notna()].reset_index(drop=True)
feature_cols = [
"MolWt", "MolLogP", "MolMR", "HeavyAtomCount", "NumHAcceptors", "NumHDonors",
"NumHeteroatoms", "NumRotatableBonds", "NumValenceElectrons", "NumAromaticRings",
"NumSaturatedRings", "NumAliphaticRings", "RingCount", "TPSA", "LabuteASA",
"BalabanJ", "BertzCT",
]
X = df[feature_cols].values
THRESHOLD = -4.0
y = (df["Solubility"].values < THRESHOLD).astype(int)
idx_train, idx_test = train_test_split(
np.arange(len(df)), test_size=0.2, stratify=y, random_state=42
)
X_train, X_test = X[idx_train], X[idx_test]
y_train, y_test = y[idx_train], y[idx_test]
print(f"全库样本数: {len(df)} | 难溶正类 (y=1) 占比: {y.mean():.1%}")
print(f"训练集正类占比: {y_train.mean():.3f} | 测试集正类占比: {y_test.mean():.3f}")
fig, ax = plt.subplots(figsize=(6.8, 3.6))
ax.hist(df.loc[y == 0, "Solubility"], bins=35, alpha=0.8, color=C.teal, label="0: Soluble (logS >= -4)")
ax.hist(df.loc[y == 1, "Solubility"], bins=35, alpha=0.8, color=C.crimson, label="1: Insoluble (logS < -4)")
ax.axvline(THRESHOLD, color=C.ink, ls="--", lw=1.6, label="Cutoff = -4.0")
ax.set_xlabel("Experimental logS (log mol/L)")
ax.set_ylabel("Molecule Count")
ax.set_title("AqSolDB Binary Classification Target")
ax.legend(fontsize=8.5)
plt.show()
全库样本数: 9480 | 难溶正类 (y=1) 占比: 28.6% 训练集正类占比: 0.286 | 测试集正类占比: 0.285
2. 从感知机(Perceptron)到逻辑回归(Logistic Regression)
📘 2.1 感知机(1957):神经网络的鼻祖与“判错就挪直线”
1957 年 Rosenblatt 提出的感知机(Perceptron)是最古老的线性分类器(也是下半学期神经网络里单个神经元的原型)。它先对特征做线性打分 \(z = \sum_{j=1}^p w_j x_j + b\),再用一个非黑即白的阶跃函数做硬判决:
它的学习规则直白得像实验室带教:挨个看训练分子,猜对了就什么都不动;一旦猜错了,就把分类直线往正确的方向推一把!
- 如果真实难溶(\(y_i=1\))却漏判成
0(\(y_i - \hat{y}_i = +1\)),就给 \(\mathbf{w}\) 加上 \(\eta \mathbf{x}_i\),下次遇到类似特征时打分就会变高; - 如果真实可溶(\(y_i=0\))却误判成
1(\(y_i - \hat{y}_i = -1\)),就减去 \(\eta \mathbf{x}_i\)!
📘 2.2 逻辑回归:套上 Sigmoid 变成光滑概率 predict_proba
感知机有两个明显的痛点:
- 没有把握度:打分 \(z = +0.001\)(压线险过)和 \(z = +10\)(十拿九稳)都只冷冰冰吐出
1,没法帮实验员排优先级; - 不可微且遇噪声震荡:真实分子总有边界重叠,感知机只要碰到分不开的噪点就会永无休止地来回晃动直线。
**逻辑回归(Logistic Regression)**只做了一个天才改动——把生硬的 0/1 阶跃函数换成光滑 S 形的 Sigmoid 函数:
- 当线性打分 \(z = 0\)(正处分界线上)时,\(\sigma(0) = 0.5\)(五五开);
- \(z \gg 0\) 时概率平滑趋近
1.0,\(z \ll 0\) 时平滑趋近0.0;通过最小化对数交叉熵损失,权重总能稳定收敛到唯一全局最优解!
下面我们用 10 行纯 NumPy 手写感知机,并在 (MolLogP, TPSA) 二维分子平面上对比感知机的硬直线与逻辑回归的等概率带:
# ▶️ 运行看看:(a) 阶跃函数 vs Sigmoid;(b) 手写感知机 vs 逻辑回归在 (MolLogP, TPSA) 平面的分类边界
sc_all = StandardScaler().fit(X_train)
X_tr_s, X_te_s = sc_all.transform(X_train), sc_all.transform(X_test)
# 取两个最具物理代表性的特征:MolLogP (疏水性) 与 TPSA (极性表面积)
pair_cols = [feature_cols.index("MolLogP"), feature_cols.index("TPSA")]
X2 = X_tr_s[:350, pair_cols]
y2 = y_train[:350]
# ====== 核心:10 行纯 NumPy 手写感知机 ======
w_p = np.array([-0.5, 0.8])
b_p = 0.0
lr_p = 0.05
for epoch in range(8):
for xi, yi in zip(X2, y2):
y_hat = 1 if (np.dot(w_p, xi) + b_p) > 0 else 0
if yi != y_hat: # 判错了才挪直线!
w_p = w_p + lr_p * (yi - y_hat) * xi
b_p = b_p + lr_p * (yi - y_hat)
# ===========================================
logreg_2d = LogisticRegression().fit(X2, y2)
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10.8, 4.1))
z_vals = np.linspace(-6, 6, 300)
ax1.plot(z_vals, (z_vals > 0).astype(float), "--", color=C.crimson, lw=2.0, label="Perceptron Step I(z > 0)")
ax1.plot(z_vals, 1.0 / (1.0 + np.exp(-z_vals)), "-", color=C.navy, lw=2.4, label="Logistic Sigmoid 1 / (1 + e^-z)")
ax1.axhline(0.5, color=C.slate, ls=":", lw=0.9)
ax1.axvline(0.0, color=C.slate, ls=":", lw=0.9)
ax1.set_xlabel("Linear Score z = w·x + b")
ax1.set_ylabel("Output / Probability P(y = 1)")
ax1.set_title("(a) Hard Step vs. Smooth Sigmoid Probability")
ax1.legend(fontsize=8.5, loc="upper left")
gx, gy = np.meshgrid(np.linspace(-2.5, 3.2, 150), np.linspace(-1.2, 3.5, 150))
prob_grid = logreg_2d.predict_proba(np.c_[gx.ravel(), gy.ravel()])[:, 1].reshape(gx.shape)
cf = ax2.contourf(gx, gy, prob_grid, levels=np.linspace(0, 1, 11), cmap="ai4m_div_r", alpha=0.45)
plt.colorbar(cf, ax=ax2, label="Logistic P(insoluble)")
x_line = np.linspace(-2.4, 3.0, 100)
# 画出感知机分界线 w0*x + w1*y + b = 0 => y = -(w0*x + b)/w1
ax2.plot(x_line, -(w_p[0] * x_line + b_p) / w_p[1], "--", color=C.crimson, lw=2.0, label="NumPy Perceptron Boundary")
w_lr, b_lr = logreg_2d.coef_[0], logreg_2d.intercept_[0]
ax2.plot(x_line, -(w_lr[0] * x_line + b_lr) / w_lr[1], "-", color=C.navy, lw=2.2, label="Logistic P = 0.5 Boundary")
ax2.scatter(X2[y2 == 0, 0], X2[y2 == 0, 1], s=18, color=C.teal, alpha=0.7, label="Soluble (0)")
ax2.scatter(X2[y2 == 1, 0], X2[y2 == 1, 1], s=18, color=C.crimson, alpha=0.7, label="Insoluble (1)")
ax2.set_xlim(-2.5, 3.2)
ax2.set_ylim(-1.2, 3.5)
ax2.set_xlabel("Standardized MolLogP")
ax2.set_ylabel("Standardized TPSA")
ax2.set_title("(b) Decision Boundaries & Probability Contours")
ax2.legend(fontsize=8.0, loc="upper right")
plt.show()
3. 全面评估分类模型:混淆矩阵、ROC-AUC 与实验成本阈值移动
📘 3.1 准确率陷阱与核心分类指标
在测试集中,约 71.5% 的分子本身就是可溶的(0)。如果一个偷懒模型闭着眼把所有分子全判为“可溶”,它的**准确率(Accuracy)**照样高达 71.5%,却漏掉了 100% 的难溶分子!因此分类评估必须拆解 2×2 混淆矩阵:
- TP(真阳性):本来难溶,成功拦截;TN(真阴性):本来可溶,顺利放行;
- FP(假阳性 / 误报):本来可溶的好分子,被冤枉淘汰了;
- FN(假阴性 / 漏报):本来难溶的坏分子,漏网混进了合成产线!
由此定义:
- 精确率 Precision \(= \frac{\text{TP}}{\text{TP}+\text{FP}}\)(报出来的难溶分子里,抓准了多少?防冤枉好分子);
- 召回率 Recall \(= \frac{\text{TP}}{\text{TP}+\text{FN}}\)(所有真难溶分子里,抓住了多少?防漏放坏分子);
- F1 分数:Precision 与 Recall 的调和平均;
- ROC-AUC:遍历所有概率阈值画出的 ROC 曲线下面积(瞎猜为
0.50,完美区分为1.00)。
dummy_clf = DummyClassifier(strategy="most_frequent").fit(X_train, y_train)
perc_clf = make_pipeline(StandardScaler(), Perceptron(random_state=42)).fit(X_train, y_train)
logreg_clf = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000)).fit(X_train, y_train)
rf_clf = RandomForestClassifier(n_estimators=200, random_state=42, n_jobs=-1).fit(X_train, y_train)
def summarize_clf(clf, X_te, y_te, has_proba=True):
pred = clf.predict(X_te)
auc = roc_auc_score(y_te, clf.predict_proba(X_te)[:, 1]) if has_proba else np.nan
return {
"Accuracy": accuracy_score(y_te, pred),
"Precision": precision_score(y_te, pred, zero_division=0),
"Recall": recall_score(y_te, pred, zero_division=0),
"F1": f1_score(y_te, pred, zero_division=0),
"ROC-AUC": auc,
}
summary_df = pd.DataFrame({
"Dummy (Always 0)": summarize_clf(dummy_clf, X_test, y_test, True),
"Perceptron (No Proba)": summarize_clf(perc_clf, X_test, y_test, False),
"Logistic Regression": summarize_clf(logreg_clf, X_test, y_test, True),
"Random Forest": summarize_clf(rf_clf, X_test, y_test, True),
}).T.round(3)
print(summary_df.to_string())
# 可视化:(a) 随机森林混淆矩阵;(b) ROC 曲线对比;(c) 调节概率阈值平衡 Precision 与 Recall
fig, axes = plt.subplots(1, 3, figsize=(11.5, 3.7))
ConfusionMatrixDisplay.from_predictions(
y_test, rf_clf.predict(X_test),
display_labels=["Soluble (0)", "Insoluble (1)"],
cmap="ai4m", ax=axes[0], colorbar=False,
)
axes[0].set_title("(a) Random Forest Confusion Matrix", fontsize=9.8)
axes[0].grid(False)
for name, clf, col in [
("Logistic Reg.", logreg_clf, C.teal),
("Random Forest", rf_clf, C.navy),
]:
probs = clf.predict_proba(X_test)[:, 1]
fpr, tpr, _ = roc_curve(y_test, probs)
axes[1].plot(fpr, tpr, color=col, lw=2.0, label=f"{name} (AUC={roc_auc_score(y_test, probs):.2f})")
axes[1].set_xlabel("False Positive Rate (1 - Specificity)")
axes[1].set_ylabel("True Positive Rate (Recall)")
axes[1].plot([0, 1], [0, 1], "--", color=C.slate, lw=1.0, label="Random (AUC = 0.50)")
axes[1].set_title("(b) ROC Curves on Test Set", fontsize=9.8)
axes[1].legend(fontsize=8.0, loc="lower right")
y_prob_rf = rf_clf.predict_proba(X_test)[:, 1]
ths = np.linspace(0.1, 0.9, 33)
precs = [precision_score(y_test, y_prob_rf >= t) for t in ths]
recs = [recall_score(y_test, y_prob_rf >= t) for t in ths]
f1s = [f1_score(y_test, y_prob_rf >= t) for t in ths]
axes[2].plot(ths, precs, color=C.teal, lw=2.0, label="Precision (Fewer False Alarms)")
axes[2].plot(ths, recs, color=C.crimson, lw=2.0, label="Recall (Fewer Missed Insolubles)")
axes[2].plot(ths, f1s, "--", color=C.navy, lw=1.6, label="F1 Score")
axes[2].axvline(0.5, color=C.slate, ls=":", lw=1.0)
axes[2].set_xlabel("Decision Threshold on P(insoluble)")
axes[2].set_ylabel("Score")
axes[2].set_title("(c) Moving Threshold to Match Lab Cost", fontsize=9.8)
axes[2].legend(fontsize=7.8, loc="lower center")
plt.show()
Accuracy Precision Recall F1 ROC-AUC Dummy (Always 0) 0.715 0.000 0.000 0.000 0.500 Perceptron (No Proba) 0.842 0.827 0.566 0.672 NaN Logistic Regression 0.856 0.833 0.619 0.710 0.892 Random Forest 0.891 0.847 0.756 0.799 0.953
💡 阈值调节的实战威力(图 c):如果后续合成一个候选分子要花两周时间和昂贵钯催化剂,我们宁可错杀几个边缘分子(容忍一点 FP),也绝不想让真难溶分子混进来毁掉旋涂成膜(厌恶漏报 FN)。此时无需重训模型,只需把判断阈值从默认的
0.5调低到0.25,召回率 Recall 就能跃升至 95% 以上!
4. 实战筛查:有机半导体分子与“溶剂先验边界”
把训练好的随机森林分类器应用到有机电子经典分子上(对比刚性母核 BTBT 与加了两条长辛基增溶侧链的 C8-BTBT):
osc_list = [
("Thiophene", "c1ccsc1"),
("Benzene", "c1ccccc1"),
("Naphthalene", "c1ccc2ccccc2c1"),
("Anthracene", "c1ccc2cc3ccccc3cc2c1"),
("BTBT (core)", "c1ccc2c(c1)sc3c2sc4ccccc34"),
("C8-BTBT", "CCCCCCCCc1ccc2c(c1)sc3c2sc4cc(CCCCCCCC)ccc34"),
]
osc_rows = []
for name, smi in osc_list:
mol = Chem.MolFromSmiles(smi)
vec = np.array([[getattr(Descriptors, k)(mol) for k in feature_cols]])
prob = rf_clf.predict_proba(vec)[0, 1]
osc_rows.append({
"Molecule": name,
"MolWt": round(Descriptors.MolWt(mol), 1),
"MolLogP": round(Descriptors.MolLogP(mol), 2),
"P(insoluble in water)": round(prob, 3),
})
print(pd.DataFrame(osc_rows).to_string(index=False))
Molecule MolWt MolLogP P(insoluble in water)
Thiophene 84.1 1.75 0.005
Benzene 78.1 1.69 0.000
Naphthalene 128.2 2.84 0.772
Anthracene 178.2 3.99 1.000
BTBT (core) 240.4 5.27 0.950
C8-BTBT 464.8 11.08 0.895
🤔 思考:为什么实验室里公认好旋涂的
C8-BTBT被模型以1.00的概率判为“绝对不溶”? 因为实验室旋涂用的是氯苯、甲苯等非极性有机溶剂(两条疏水长烷基链增加构象熵、帮分子溶进有机溶剂);而 AqSolDB 训练的是水溶解度!长碳链让MolLogP暴涨到11.3(极度憎水),在水里当然滴水不溶。永远记住:模型只忠实于训练集的实验条件(这里是水相),跨溶剂迁移前必须核对物理先验!
5. 打开黑箱:特征重要性、Yalkowsky 方程与金属盐/晶格错分破案
📘 5.1 MDI 分裂重要性 vs 置换重要性(Permutation Importance)
随机森林自带的 feature_importances_(MDI,节点基尼不纯度平均下降)会被 MolWt、HeavyAtomCount、LabuteASA、NumValenceElectrons 等高度共线的体积特征互相平摊稀释;而在测试集上逐列打乱特征看 AUC 掉多少的**置换重要性(Permutation Importance)**才能还原真相:
mdi_s = pd.Series(rf_clf.feature_importances_, index=feature_cols).sort_values()
perm_res = permutation_importance(
rf_clf, X_test, y_test, scoring="roc_auc", n_repeats=8, random_state=42, n_jobs=-1
)
perm_s = pd.Series(perm_res.importances_mean, index=feature_cols).sort_values()
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10.8, 4.3))
ax1.barh(mdi_s.index, mdi_s.values, color=C.steel)
ax1.set_xlabel("Built-in Gini Importance (MDI)")
ax1.set_title("(a) MDI Dilutes Importance Across Collinear Size Features", fontsize=9.8)
ax2.barh(perm_s.index, perm_s.values, xerr=perm_res.importances_std[perm_s.index.map(feature_cols.index)],
color=C.navy)
ax2.set_xlabel("ROC-AUC Drop When Feature Is Shuffled")
ax2.set_title("(b) Permutation Importance: MolLogP Dominates!", fontsize=9.8)
plt.show()
# 揪出测试集中两类最具启发性的“高置信度错分分子”:
test_df = df.iloc[idx_test][["Name", "SMILES", "Solubility", "MolLogP", "MolWt", "TPSA"]].copy()
test_df["True_y"] = y_test
test_df["P_insoluble"] = y_prob_rf
test_df["Is_Ionic_Salt"] = test_df["SMILES"].str.contains(".", regex=False) & test_df["SMILES"].str.contains(r"[+\-]", regex=True)
test_df["Is_Pure_Organic"] = (~test_df["SMILES"].str.contains(".", regex=False)) & test_df["SMILES"].str.contains("c|C", regex=True)
print("=== 错分类型 A:带电离子盐/金属皂(真实可溶 y=0,却因形式碳链疏水被误判难溶)===")
fp_salts = test_df[(test_df["True_y"] == 0) & (test_df["Is_Ionic_Salt"])].sort_values("P_insoluble", ascending=False).head(4)
print(fp_salts[["Name", "Solubility", "MolLogP", "P_insoluble"]].to_string(index=False))
print()
print("=== 错分类型 B:高对称/强氢键刚性有机晶体(真实难溶 y=1,却因 MolLogP 低被漏判为可溶)===")
fn_crystals = test_df[(test_df["True_y"] == 1) & (test_df["Is_Pure_Organic"]) & (test_df["Solubility"] < -4.5)].sort_values("P_insoluble", ascending=True).head(5)
print(fn_crystals[["Name", "Solubility", "MolLogP", "TPSA", "P_insoluble"]].to_string(index=False))
=== 错分类型 A:带电离子盐/金属皂(真实可溶 y=0,却因形式碳链疏水被误判难溶)===
Name Solubility MolLogP P_insoluble
zinc(2+) ion bis(2-ethylhexanoate) 0.455435 1.9029 0.730
tetralead trioxide sulphate -3.979450 -3.2176 0.555
chromium(3+) ion trichloride -3.199632 -8.9905 0.435
1,3,3-trimethyl-2-[(E)-2-(1-methyl-2-phenyl-1H-indol-3-yl)ethenyl]-3H-indol-1-ium chloride -1.743928 3.5687 0.400
=== 错分类型 B:高对称/强氢键刚性有机晶体(真实难溶 y=1,却因 MolLogP 低被漏判为可溶)===
Name Solubility MolLogP TPSA P_insoluble
3,3-diethylpiperidine-2,6-dione -4.530000 1.2294 46.17 0.000
simazine; 2-chloro-4,6-di(ethylamino)-1,3,5-triazine -4.550000 1.3886 62.73 0.015
Fatty acids, C5-9, hexaesters with dipentaerythritol -6.830456 -1.3293 136.68 0.070
6-chloro-5-(2-chloroethyl)-2,3-dihydro-1H-indol-2-one -4.777574 2.6159 29.10 0.080
Tetra(10B)boron carbide -4.742403 -1.3084 0.00 0.080
📘 5.2 对照 Yalkowsky 通用溶解度方程破案
物理化学经典的 Yalkowsky 通用溶解度方程(GSE) 完美解释了上面看到的全部现象:
- 为什么置换重要性里
MolLogP一骑绝尘? 因为它直接对应方程第一项 \(-\log P\)(溶质进入水相的溶剂化代价)。 - 为什么会出现“错分类型 A(离子盐误判)”? 兑现了
01d留下的多组分.伏笔:像长链季铵盐或有机酸盐,RDKit 按中性原子加和算出的MolLogP很高,但带电离子在水中的水合能远超中性分子,导致模型严重误判! - 为什么会出现“错分类型 B(刚性高熔点晶体漏报)”? 这些中性小分子极性大、
MolLogP很低(甚至为负),模型以为它们极易溶于水;但它们拥有高度对称的平面刚性骨架或多氢键网络,固态晶格能极高、熔点 \(T_m\) 极高,水分子根本拆不开晶格!仅靠单个分子的 2D 拓扑描述符很难算准三维晶体堆积——这正是第05模块引入 3D 构象与外部物理特征的原因。
🏋️ 练习 02d-1:加入 RBF-SVC 与 XGBoost 分类器横评
请从 sklearn.svm 导入 SVC、从 xgboost 导入 XGBClassifier:
- 训练
make_pipeline(StandardScaler(), SVC(kernel="rbf", C=3.0, probability=True, random_state=42))(为加快速度可在前 3000 个训练样本上拟合,或全集拟合)和XGBClassifier(n_estimators=250, learning_rate=0.06, max_depth=6, random_state=42, n_jobs=-1); - 调用上面的
summarize_clf打印它们在完整测试集X_test, y_test上的 Accuracy、Precision、Recall、F1 和 ROC-AUC。(参考答案见solutions/02_supervised_solutions.ipynb)
# 在这里写你的代码(练习 02d-1)
🏋️ 练习 02d-2:可视化漏报最严重的 6 个刚性难溶分子
利用上面构造好的 fn_crystals 思路,取出测试集中不含 .(纯单组分有机分子)、真实 Solubility < -4.5、但 P_insoluble 最低的前 6 个漏报分子,用 Draw.MolsToGridImage(mols, molsPerRow=3, subImgSize=(260, 190), legends=...) 画出它们的化学结构并在图注中标出实测 logS 与 MolLogP,观察它们是否普遍富含氢键给受体(如酰胺、脲、多氮杂环)或高对称平面结构。
# 在这里写你的代码(练习 02d-2)
6. 高通量虚拟筛选中的贝叶斯基础概率陷阱(Base-Rate Neglect)
🤔 先猜一猜:准确率 99% 的筛查器,挑出的阳性候选有多少是真的?
在真实的新材料高通量虚拟筛选(例如从 100,000 个假想化合物中寻找室温超导体、高活性电催化剂或无铅稳定钙钛矿)中,真正符合苛刻指标的“金子”往往极其稀有——假设真实正例占比(先验概率 Prior,\(P(H)\))只有 \(0.1\%\)(即千分之一)。
假设你训练出了一个纸面指标极其华丽的二分类模型:
- 召回率(Recall / Sensitivity) \(P(+\mid H) = 99\%\)(真好材料几乎不漏);
- 特异度(Specificity) \(P(-\mid \neg H) = 99\%\)(普通废料 99% 能筛掉,假阳性率仅 \(1\%\))。
如果把模型判为“阳性(建议合成)”的分子直接交给实验师进实验室合成,实验师合成出的分子里,真正有效材料的比例(即阳性预测值 Precision / 后验概率 \(P(H\mid +)\))是多少?是 99% 吗?
让我们用贝叶斯定理算一笔账:在 100,000 个候选分子中:
- 真正的好材料有 \(100{,}000 \times 0.001 = 100\) 个,模型找出了 \(100 \times 99\% = \mathbf{99}\) 个(TP = 99);
- 平庸材料有 \(99{,}900\) 个,哪怕只有 \(1\%\) 误报,也会放进来 \(99{,}900 \times 1\% \approx \mathbf{999}\) 个假阳性(FP = 999)!
超过 91% 的实验经费会被假阳性白白烧掉! 这在统计学上称为基础概率忽视(Base-Rate Neglect)。运行下方代码,直观观察稀有发现场景下的“假阳性淹没效应”以及**多级筛选漏斗(Multi-Stage Funnel)**是如何破解这一困局的。
# ▶️ 运行看看:稀有材料筛选中的贝叶斯后验命中率 vs. 多级筛选漏斗
priors = np.logspace(-4, -0.5, 200) # 真实正例先验占比:0.01% ~ 31.6%
recall = 0.99
def bayes_precision(prior, sens, spec):
tp = prior * sens
fp = (1.0 - prior) * (1.0 - spec)
return tp / (tp + fp)
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(11.2, 4.2))
# 左图:不同特异度下,真实命中率随先验稀有度的坍塌
for spec, col, ls in [(0.95, C.slate, "--"), (0.99, C.crimson, "-"), (0.999, C.navy, "-")]:
prec = bayes_precision(priors, recall, spec)
ax1.plot(priors * 100, prec * 100, color=col, ls=ls, lw=2.1,
label=f"Specificity = {spec*100:.1f}% (FPR = {(1-spec)*100:.1f}%)")
p_demo = 0.001
hit_demo = bayes_precision(p_demo, 0.99, 0.99) * 100
ax1.scatter([p_demo * 100], [hit_demo], color=C.crimson, s=65, zorder=5)
ax1.annotate(f"Prior = 0.1%\nTrue Hit Rate = {hit_demo:.1f}%!",
xy=(p_demo * 100, hit_demo), xytext=(0.004 * 100, 32),
arrowprops=dict(arrowstyle="->", color=C.crimson, lw=1.2),
fontsize=9, fontweight="bold", color=C.crimson)
ax1.set_xscale("log")
ax1.set_xlabel("True Hit Prevalence / Prior P(H) (%) [log scale]")
ax1.set_ylabel("Posterior Precision P(H | +) (%)")
ax1.set_title("a) Single-Stage Screening: Base-Rate Trap")
ax1.legend(loc="lower right", fontsize=8.5)
# 右图:多级正交漏斗(Bayes Sequential Updating)如何逐步提纯候选池
stages = ["0. Raw Pool\n(100,000)", "1. Fast ML\n(Spec 99%)",
"2. Semi-Empirical\n(Spec 95%)", "3. High-Level DFT\n(Spec 98%)"]
stage_specs = [None, (0.99, 0.99), (0.95, 0.95), (0.95, 0.98)] # (sens, spec)
posteriors = [0.001]
n_total = 100_000
survivors = [n_total]
for sens_s, spec_s in stage_specs[1:]:
p_prev = posteriors[-1]
p_next = bayes_precision(p_prev, sens_s, spec_s)
n_Total_next = survivors[-1] * (p_prev * sens_s + (1 - p_prev) * (1 - spec_s))
posteriors.append(p_next)
survivors.append(int(round(n_Total_next)))
bars = ax2.bar(range(len(stages)), [p * 100 for p in posteriors],
color=[C.slate, C.gold, C.teal, C.navy], width=0.56)
for idx, (bar, surv) in enumerate(zip(bars, survivors)):
h = bar.get_height()
ax2.text(bar.get_x() + bar.get_width() / 2, h + 2.2,
f"{h:.1f}%\n(N={surv:,})", ha="center", va="bottom", fontsize=8.5, fontweight="bold")
ax2.set_xticks(range(len(stages)))
ax2.set_xticklabels(stages, fontsize=8.5)
ax2.set_ylim(0, 112)
ax2.set_ylabel("True Hit Purity P(H | Passed) (%)")
ax2.set_title("b) Orthogonal Multi-Stage Screening Funnel")
plt.tight_layout()
plt.show()
小结
- 分类器演化:感知机(硬阶跃,“判错挪直线”)\(\longrightarrow\) 逻辑回归(套上 Sigmoid 输出平滑概率
predict_proba,最小化交叉熵); - 防坑评估:类别不均衡时拒绝只看 Accuracy;用混淆矩阵 + Precision/Recall/F1 + ROC-AUC全面诊断,并按实验室误杀/漏筛成本灵活移动决策阈值;
- 物理化学闭环:置换重要性克服了 MDI 的共线性稀释,证实模型抓住了 Yalkowsky 方程的疏水主项,而错分样本精准暴露了离子盐电荷效应与固体晶格堆积(熔点项)的 2D 表征盲区。
👉 下一节(02e_validation_and_tuning.ipynb):到这里我们已经学完了全部经典回归与分类模型。但在写论文或交付实验室使用前,还有最后一道生死攸关的关卡:单次切分成绩有运气成分怎么办?怎样在交叉验证和调参中彻底杜绝数据泄漏?遇到全新分子骨架时怎样划定模型的适用域?
- 高通量筛选防坑:当目标好材料先验占比极低(如 \(<0.1\%\))时,单轮高准确率分类器仍会产生大量假阳性(基础概率忽视);真实材料发现必须采用“快速 ML 初筛 \(\to\) 物理/半经验复筛 \(\to\) 第一性原理精算”的多级正交漏斗,并优先关注 PR-AUC。