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

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

02d · 异构数据流水线、严谨验证与适用域:从论文高分到真实泛化

02d_pipelines_validation_and_ad.ipynb347.7 KB

Open In Colab

02d · 异构数据流水线、严谨验证与适用域:从论文高分到真实泛化

在 02a–02c 中,我们在干净纯数值矩阵上掌握了线性模型、kNN/SVM 与树集成。但要把机器学习真正用到课题组实验表并经受顶刊审稿人的检验,必须跨越最后四道实战工程与验证关卡:

  1. 真实脏表格怎么直接喂给模型?——当表格同时包含连续数值列、文本类别列(如化学家族/溶剂类别)与缺失值 NaN 时,如何用 SimpleImputer + OneHotEncoder + ColumnTransformer + Pipeline 搭出零泄漏工业级流水线?
  2. 怎样高效调参并判断该不该补实验数据?——5 折交叉验证、网格搜索 GridSearchCV vs 随机搜索 RandomizedSearchCV,以及 learning_curve 数据瓶颈诊断;
  3. 随机打乱切分太温柔怎么办?——对比随机划分 vs 按芳环/杂原子结构家族分组的 GroupKFold vs 跨分子尺寸外推划分(HeavyAtomCount <= 22 \(\to\) > 22);
  4. 模型面对陌生分子如何主动报警?——基于标准化 17 维欧氏 kNN 距离的**适用域(Applicability Domain, AD)**定量预警!

本节内容

  1. 真实异构材料表格防泄漏流水线:SimpleImputer + OneHotEncoder + ColumnTransformer + Pipeline(现场抓包预处理泄漏假阳性!)
  2. K 折交叉验证、GridSearchCV vs RandomizedSearchCV 超参数寻优与学习曲线(learning_curve)
  3. 严苛泛化与外推大考:随机划分 vs 结构家族 GroupKFold vs 跨分子量/重原子数外推划分
  4. 适用域(Applicability Domain):标准化 17 维欧氏近邻距离阈值与有机半导体越界自动拦截
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"))
In [2] · Python
import os, time, pathlib, sys
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy.stats import randint

from sklearn.model_selection import (
    train_test_split, KFold, GroupKFold, cross_val_score,
    GridSearchCV, RandomizedSearchCV, learning_curve,
)
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import StandardScaler, OneHotEncoder
from sklearn.compose import ColumnTransformer
from sklearn.feature_selection import SelectKBest, f_regression
from sklearn.pipeline import Pipeline, make_pipeline
from sklearn.linear_model import Ridge
from sklearn.neighbors import NearestNeighbors, KNeighborsRegressor
from sklearn.ensemble import RandomForestRegressor
from sklearn.metrics import root_mean_squared_error, r2_score

sys.path.insert(0, str(pathlib.Path.cwd().parent))
import ai4m_style as ai4m
C = ai4m.use()

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
idx_train, idx_test = train_test_split(np.arange(len(df)), test_size=0.2, 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)} | Train: {len(X_train)} | Test: {len(X_test)}")
Out:
纯净单组分有机分子数: 8438 | Train: 6750 | Test: 1688

1. 真实脏表格防泄漏工程:SimpleImputer + OneHotEncoder + ColumnTransformer + Pipeline

📘 1.1 为什么不能用 1, 2, 3 直接编码化学类别,更不能在切分前填补缺失值?

真实的实验室材料研发台账几乎从来不是纯数字矩阵,往往同时混杂着:

  1. 连续数值特征(带缺失值 NaN):比如部分样品没测比表面积或偶极矩,需用训练集**中位数/均值插补(SimpleImputer(strategy="median"))**再做 StandardScaler 缩放;
  2. 无序文本类别特征(Categorical Features):比如化学结构大类("aromatic_hydrocarbon"、"heteroaromatic"、"halogenated"、"polar_aliphatic")或旋涂溶剂名称。若错误地映射成整数 0, 1, 2, 3,线性模型与欧氏距离会误以为“卤代物 = 芳香烃 + 极性脂肪族”!正确做法是使用独热编码 OneHotEncoder(handle_unknown="ignore") 拆成互不干扰的 0/1 指示列;
  3. 审稿人头号拒稿雷区——预处理数据泄漏(Data Leakage):如果在 train_test_split 或 KFold 之前对整张表做插补、标准化或特征挑选,验证折的信息就已经提前泄露进了训练过程!使用 ColumnTransformer + Pipeline 将分列预处理与模型锁成一体,每一折都会严格只用当前训练折拟合插补器与编码器!
In [3] · Python
# ▶️ 运行看看:(1) 构造含缺失值与文本类别列的真实材料溶解度脏表格并用 ColumnTransformer 建模;(2) 现场抓包预处理泄漏!
rng_dirty = np.random.default_rng(42)

# 利用纯 Pandas 规则构造真实的化学大类文本列与分子链刚性等级列(零外部化学库)
has_halogen = df["SMILES"].str.contains(r"F|Cl|Br|I", na=False)
chem_class = np.select(
    [
        (df["NumAromaticRings"] > 0) & (df["NumHeteroatoms"] == 0),
        has_halogen,
        (df["NumAromaticRings"] > 0) & (df["NumHeteroatoms"] > 0),
    ],
    ["aromatic_hydrocarbon", "halogenated", "heteroaromatic"],
    default="polar_aliphatic",
)
flex_grade = np.where(df["NumRotatableBonds"] == 0, "rigid", np.where(df["NumRotatableBonds"] <= 4, "semi_flexible", "flexible"))

num_cols = ["MolWt", "MolLogP", "TPSA", "HeavyAtomCount", "NumHDonors", "BertzCT"]
cat_cols = ["chem_class", "flex_grade"]

dirty_df = df[num_cols].copy()
dirty_df["chem_class"] = pd.Series(chem_class, dtype=object)
dirty_df["flex_grade"] = pd.Series(flex_grade, dtype=object)

# 模拟实验室常见的约 10% 随机测量缺失 (NaN)
for col in ["MolLogP", "TPSA", "chem_class"]:
    miss_idx = rng_dirty.choice(len(dirty_df), size=int(0.10 * len(dirty_df)), replace=False)
    dirty_df.loc[miss_idx, col] = np.nan

print("异构脏表格缺失值统计:\n", dirty_df.isna().sum())

# 构建分列预处理流水线 ColumnTransformer + Pipeline
num_pipeline = Pipeline([
    ("imputer", SimpleImputer(strategy="median")),
    ("scaler",  StandardScaler()),
])
cat_pipeline = Pipeline([
    ("imputer", SimpleImputer(strategy="most_frequent")),
    ("onehot",  OneHotEncoder(handle_unknown="ignore", sparse_output=False)),
])
preprocessor = ColumnTransformer([
    ("num", num_pipeline, num_cols),
    ("cat", cat_pipeline, cat_cols),
])

full_pipe = Pipeline([
    ("prep",  preprocessor),
    ("model", Ridge(alpha=20.0)),
])

Xd_tr, Xd_te, yd_tr, yd_te = train_test_split(dirty_df, y, test_size=0.2, random_state=42)
cv5 = KFold(n_splits=5, shuffle=True, random_state=42)
cv_clean_rmse = -cross_val_score(full_pipe, Xd_tr, yd_tr, cv=cv5, scoring="neg_root_mean_squared_error").mean()
full_pipe.fit(Xd_tr, yd_tr)
print(f"\n✅ 无泄漏异构 ColumnTransformer+Pipeline | 5-Fold CV RMSE = {cv_clean_rmse:.3f} | Test RMSE = {root_mean_squared_error(yd_te, full_pipe.predict(Xd_te)):.3f}")

# 现场抓包演示:在小样本高维数据 (N=80, p=1500) 上,CV 前做预处理/特征选择如何凭空捏造 R² > 0.45 的假科学发现!
X_noise = rng_dirty.normal(size=(80, 1500))
y_noise = rng_dirty.normal(size=80)
X_leaked = SelectKBest(f_regression, k=15).fit_transform(SimpleImputer().fit_transform(X_noise), y_noise)
leaked_r2 = cross_val_score(Ridge(), X_leaked, y_noise, cv=5, scoring="r2").mean()
honest_pipe = make_pipeline(SimpleImputer(), StandardScaler(), SelectKBest(f_regression, k=15), Ridge())
honest_r2 = cross_val_score(honest_pipe, X_noise, y_noise, cv=5, scoring="r2").mean()
print(f"\n🚨 纯白噪声泄漏警示 | ❌ CV外预处理虚假 R² = {leaked_r2:+.3f}  vs  ✅ Pipeline内严密验证真实 R² = {honest_r2:+.3f}")
Out:
异构脏表格缺失值统计:
 MolWt               0
MolLogP           843
TPSA              843
HeavyAtomCount      0
NumHDonors          0
BertzCT             0
chem_class        843
flex_grade          0
dtype: int64
✅ 无泄漏异构 ColumnTransformer+Pipeline | 5-Fold CV RMSE = 1.455 | Test RMSE = 1.488

🚨 纯白噪声泄漏警示 | ❌ CV外预处理虚假 R² = +0.385  vs  ✅ Pipeline内严密验证真实 R² = -0.628

2. 交叉验证、超参数调优(GridSearchCV vs RandomizedSearchCV)与学习曲线

  1. GridSearchCV(穷举网格搜索)vs RandomizedSearchCV(随机采样搜索):
    • 当只有 2 个超参数(如 \(3 \times 3 = 9\) 种组合)时,GridSearchCV 穷举毫无压力;
    • 当树集成或神经网络有 4–6 个超参数时,网格组合数呈指数爆炸(\(5^5 = 3125\) 次),而且很多算力浪费在对性能不敏感的次要维度上!RandomizedSearchCV 给定固定预算(如 n_iter=12 次随机组合),往往用 1/3 的时间就能搜到持平甚至更优的超参数!
  2. 学习曲线(learning_curve):定量判断当前瓶颈是“模型太简单(高偏差饱和,加数据没用)”还是“模型还没吃饱(继续补实验数据能稳步降误差)”。
In [4] · Python
# ▶️ 运行看看:对比 GridSearchCV vs RandomizedSearchCV 的调参耗时与精度,并绘制学习曲线
rf_base_est = RandomForestRegressor(n_estimators=80, random_state=42, n_jobs=-1)

t0 = time.perf_counter()
grid_search = GridSearchCV(
    rf_base_est,
    param_grid={"max_depth": [6, 12, 20], "min_samples_leaf": [1, 3, 6], "max_features": [0.5, 1.0]},
    cv=cv5, scoring="neg_root_mean_squared_error", n_jobs=-1,
).fit(X_train, y_train)
t_grid = time.perf_counter() - t0

t1 = time.perf_counter()
rand_search = RandomizedSearchCV(
    rf_base_est,
    param_distributions={"max_depth": randint(6, 26), "min_samples_leaf": randint(1, 8), "max_features": [0.4, 0.6, 0.8, 1.0]},
    n_iter=8, cv=cv5, scoring="neg_root_mean_squared_error", random_state=42, n_jobs=-1,
).fit(X_train, y_train)
t_rand = time.perf_counter() - t1

print(f"GridSearchCV (18 组合)      | 耗时 {t_grid:5.1f}s | 最优 CV RMSE = {-grid_search.best_score_:.3f} | best = {grid_search.best_params_}")
print(f"RandomizedSearchCV (8 采样) | 耗时 {t_rand:5.1f}s | 最优 CV RMSE = {-rand_search.best_score_:.3f} | best = {rand_search.best_params_}")
print(f"最优模型最终闭卷测试集 RMSE = {root_mean_squared_error(y_test, rand_search.best_estimator_.predict(X_test)):.3f}")

# 学习曲线对比:线性 Ridge vs 随机森林
sizes, tr_rg, val_rg = learning_curve(
    make_pipeline(StandardScaler(), Ridge(alpha=50.0)), X_train, y_train,
    train_sizes=[0.05, 0.12, 0.25, 0.5, 1.0], cv=cv5, scoring="neg_root_mean_squared_error", n_jobs=-1
)
_, tr_rf, val_rf = learning_curve(
    RandomForestRegressor(n_estimators=80, max_depth=16, random_state=42, n_jobs=-1), X_train, y_train,
    train_sizes=[0.05, 0.12, 0.25, 0.5, 1.0], cv=cv5, scoring="neg_root_mean_squared_error", n_jobs=-1
)

fig, ax = plt.subplots(figsize=(7.6, 4.0))
ax.plot(sizes, -val_rg.mean(axis=1), "o--", color=C.slate, lw=1.9, label="Linear Ridge CV RMSE (Saturates Early - High Bias)")
ax.plot(sizes, -val_rf.mean(axis=1), "s-", color=C.navy, lw=2.2, label="Random Forest CV RMSE (Keeps Improving with More Data)")
ax.fill_between(sizes, -val_rf.mean(axis=1) - val_rf.std(axis=1), -val_rf.mean(axis=1) + val_rf.std(axis=1), color=C.navy, alpha=0.12)
ax.set_xlabel("Number of Training Molecules")
ax.set_ylabel("5-Fold Validation RMSE (logS units)")
ax.set_title("Learning Curves: Diagnosing Model Bias vs. Data Scarcity")
ax.legend(fontsize=8.3)
plt.tight_layout()
plt.show()
Out:
GridSearchCV (18 组合)      | 耗时  27.2s | 最优 CV RMSE = 1.008 | best = {'max_depth': 20, 'max_features': 0.5, 'min_samples_leaf': 1}
RandomizedSearchCV (8 采样) | 耗时   6.8s | 最优 CV RMSE = 1.022 | best = {'max_depth': 12, 'max_features': 0.6, 'min_samples_leaf': 3}
最优模型最终闭卷测试集 RMSE = 1.032
Notebook 输出图像

3. 严苛外推泛化大考:随机划分 vs 结构家族 GroupKFold vs 跨尺寸外推

普通随机切分(Random Split)常把同一结构家族的近亲分子拆进训练和测试两边,让模型靠“认熟脸”拿到乐观高分。在没有提取精确化学图骨架之前(我们将在 第五讲 Module 05 专门实现基于化学图的 Bemis–Murcko Scaffold Split!),单靠现有的物理化学表格列,我们就能设计两场极具杀伤力的真实泛化大考:

  1. 按芳香环与杂原子结构家族分组交叉验证(GroupKFold):以 (芳香环数, 饱和环数, 杂原子分档) 组合定义结构家族标签 struct_family,强制同一结构家族的全部化合物整组留出做测试,检验跨结构类别迁移能力;
  2. 跨分子尺寸外推划分(Size-Extrapolation Split):严格只在中小分子(重原子数 HeavyAtomCount <= 22)上训练,去预测从未见过的大分子(HeavyAtomCount > 22),亲眼目睹测试误差如何大幅飙升!
In [5] · Python
# ▶️ 运行看看:对比 (1) 随机 5-Fold CV、(2) 结构家族 GroupKFold 与 (3) 重原子数跨尺寸外推 (HeavyAtomCount <= 22 -> > 22)
rf_eval = RandomForestRegressor(n_estimators=120, random_state=42, n_jobs=-1)

# 1. 标准随机 5 折交叉验证
rand_cv_rmses = -cross_val_score(rf_eval, X, y, cv=KFold(5, shuffle=True, random_state=42),
                                 scoring="neg_root_mean_squared_error", n_jobs=-1)

# 2. 按 (芳香环数, 脂肪环分档, 杂原子分档) 定义结构家族并执行 GroupKFold
het_bin = pd.cut(df["NumHeteroatoms"], bins=[-1, 0, 2, 5, 100], labels=["H0", "H1_2", "H3_5", "H6p"]).astype(str)
aliph_bin = np.clip(df["NumAliphaticRings"].astype(int), 0, 3).astype(str)
arom_bin = np.clip(df["NumAromaticRings"].astype(int), 0, 5).astype(str)
struct_groups = arom_bin + "_" + aliph_bin + "_" + het_bin
gkf = GroupKFold(n_splits=5)
group_cv_rmses = -cross_val_score(rf_eval, X, y, groups=struct_groups, cv=gkf,
                                  scoring="neg_root_mean_squared_error", n_jobs=-1)

# 3. 尺寸外推大考:仅在 HeavyAtomCount <= 22 训练,测试 HeavyAtomCount > 22!
small_mask = df["HeavyAtomCount"].values <= 22
X_sm, y_sm = X[small_mask], y[small_mask]
X_lg, y_lg = X[~small_mask], y[~small_mask]

rf_size = RandomForestRegressor(n_estimators=120, random_state=42, n_jobs=-1).fit(X_sm, y_sm)
pred_lg_rf = rf_size.predict(X_lg)
size_extrap_rmse = root_mean_squared_error(y_lg, pred_lg_rf)

print(f"① 随机 5-Fold CV 平均 RMSE               : {rand_cv_rmses.mean():.3f} ± {rand_cv_rmses.std():.3f} (同家族内插,最乐观)")
print(f"② 结构家族 GroupKFold 平均 RMSE          : {group_cv_rmses.mean():.3f} ± {group_cv_rmses.std():.3f} (跨结构家族迁移,难度显著上升!)")
print(f"③ 尺寸外推 (Train <=22 -> Test >22, n={len(y_lg)}) : {size_extrap_rmse:.3f} (跨尺寸外推,RMSE 暴增至随机切分的 {size_extrap_rmse/rand_cv_rmses.mean():.2f} 倍!)")

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10.8, 4.0))
split_labels = ["Random\n5-Fold CV", "Structural-Family\nGroupKFold", "Size Extrapolation\n(HeavyAtom > 22)"]
split_vals = [rand_cv_rmses.mean(), group_cv_rmses.mean(), size_extrap_rmse]
bars = ax1.bar(split_labels, split_vals, color=[C.teal, C.gold, C.crimson], width=0.52)
for b, v in zip(bars, split_vals):
    ax1.text(b.get_x() + b.get_width()/2, v + 0.04, f"{v:.2f}", ha="center", fontweight="bold")
ax1.set_ylim(0, 2.25)
ax1.set_ylabel("Validation / Extrapolation RMSE")
ax1.set_title("(a) Realistic Splits Expose Extrapolation Gap")

ax2.scatter(y_lg, pred_lg_rf, s=12, alpha=0.35, color=C.crimson, label="Large Molecules (HeavyAtom > 22)")
ax2.plot([-13, 2], [-13, 2], "--", color=C.ink, lw=1.2, label="Ideal y = x")
ax2.axhline(y_sm.min(), ls=":", color=C.navy, lw=1.3, label="Systematic Overestimation on Ultra-Low logS")
ax2.set_xlim(-13, 2); ax2.set_ylim(-13, 2)
ax2.set_xlabel("Experimental logS")
ax2.set_ylabel("RF Predicted logS (Trained on <=22 Atoms)")
ax2.set_title("(b) Size-Extrapolation Parity Plot")
ax2.legend(loc="upper left", fontsize=7.8)

plt.tight_layout()
plt.show()
Out:
① 随机 5-Fold CV 平均 RMSE               : 1.019 ± 0.040 (同家族内插,最乐观)
② 结构家族 GroupKFold 平均 RMSE          : 1.134 ± 0.070 (跨结构家族迁移,难度显著上升!)
③ 尺寸外推 (Train <=22 -> Test >22, n=1463) : 1.779 (跨尺寸外推,RMSE 暴增至随机切分的 1.75 倍!)
Notebook 输出图像

4. 适用域(Applicability Domain, AD):用标准化 17 维近邻距离自动拦截越界分子

既然模型走出训练分布就会失准,交付给合成化学家使用时,必须给每一次预测配上一盏适用域交通灯(Applicability Domain):

  1. 在标准化 17 维训练特征空间 X_train_s 上建立近邻检索器 NearestNeighbors(n_neighbors=5);
  2. 计算每个训练样本到自身其余 5 个最近邻的平均欧氏距离,取其 95% 分位数作为适用域警戒线 \(d_{\text{AD}}\);
  3. 对任何新候选分子,一旦其到训练集最近 5 个邻居的平均距离 \(d_{\text{kNN}} > d_{\text{AD}}\),立即标记 OUT OF AD (Low Reliability)!下面我们在测试集分箱验证误差单调递增规律,并对大共轭有机半导体(C8-BTBT、Rubrene、TIPS-Pentacene)做现场体检:
In [6] · Python
# ▶️ 运行看看:建立标准化 17 维欧氏 5-NN 适用域警戒线,并拦截越界有机半导体!
sc_ad = StandardScaler().fit(X_train)
X_tr_ad, X_te_ad = sc_ad.transform(X_train), sc_ad.transform(X_test)

nn_ad = NearestNeighbors(n_neighbors=6, n_jobs=-1).fit(X_tr_ad)
# 训练集自身近邻距离(第 0 列是自身距离 0,取第 1..5 列求平均)
tr_dists = nn_ad.kneighbors(X_tr_ad)[0][:, 1:].mean(axis=1)
d_threshold = np.percentile(tr_dists, 95)

# 测试集到训练集的 5-NN 平均欧氏距离
nn_query = NearestNeighbors(n_neighbors=5, n_jobs=-1).fit(X_tr_ad)
te_dists = nn_query.kneighbors(X_te_ad)[0].mean(axis=1)

rf_full = RandomForestRegressor(n_estimators=150, random_state=42, n_jobs=-1).fit(X_train, y_train)
te_preds = rf_full.predict(X_test)

# 按 AD 距离分四档统计测试集真实 RMSE
q_edges = [0.0, 0.8, 1.4, d_threshold, np.inf]
q_names = ["Core\n(<0.8)", "Inner\n(0.8-1.4)", f"Border\n(1.4-{d_threshold:.2f})", f"Out of AD\n(>{d_threshold:.2f})"]
bin_rmses, bin_n = [], []
for lo, hi in zip(q_edges[:-1], q_edges[1:]):
    m = (te_dists >= lo) & (te_dists < hi)
    bin_n.append(m.sum())
    bin_rmses.append(root_mean_squared_error(y_test[m], te_preds[m]))

# 检验典型有机分子与有机半导体(C8-BTBT, Rubrene, TIPS-Pentacene)是否越出适用域
CANDIDATE_OSC_17 = {
    "Benzene (Simple)": [78.114,  1.6866,  26.442,  6.0, 0.0, 0.0, 0.0,  0.0,  30.0, 1.0, 0.0, 0.0, 1.0, 0.0,  37.4314, 3.0000,   71.9610],
    "Anthracene":       [178.234, 3.9930,  61.454, 14.0, 0.0, 0.0, 0.0,  0.0,  66.0, 3.0, 0.0, 0.0, 3.0, 0.0,  82.7947, 2.5237,  488.7591],
    "Pentacene":        [278.354, 6.2994,  96.466, 22.0, 0.0, 0.0, 0.0,  0.0, 102.0, 5.0, 0.0, 0.0, 5.0, 0.0, 128.1581, 1.9317,  982.2978],
    "C8-BTBT":          [464.784, 11.0752, 148.874, 32.0, 2.0, 0.0, 2.0, 14.0, 172.0, 4.0, 0.0, 0.0, 4.0, 0.0, 202.5962, 1.4036, 1024.4278],
    "Rubrene":          [482.626, 10.6610, 163.198, 38.0, 0.0, 0.0, 0.0,  4.0, 178.0, 7.0, 0.0, 0.0, 7.0, 0.0, 223.0231, 1.7160, 1727.2224],
    "TIPS-Pentacene":   [639.088, 13.4384, 212.318, 46.0, 0.0, 0.0, 2.0,  6.0, 238.0, 5.0, 0.0, 0.0, 5.0, 0.0, 280.9472, 2.0243, 1745.9427],
}
X_cand = np.array(list(CANDIDATE_OSC_17.values()))
cand_dists = nn_query.kneighbors(sc_ad.transform(X_cand))[0].mean(axis=1)
cand_preds = rf_full.predict(X_cand)

ad_report = pd.DataFrame({
    "Candidate": list(CANDIDATE_OSC_17.keys()),
    "MolLogP": X_cand[:, 1].round(2),
    "Pred logS": cand_preds.round(2),
    "17D 5-NN Dist": cand_dists.round(2),
    "AD Threshold (95%)": round(d_threshold, 2),
    "AD Status": ["IN-DOMAIN" if d <= d_threshold else "⚠️ OUT-OF-DOMAIN!" for d in cand_dists],
})
print(f"训练集 95% 适用域距离阈值 d_AD = {d_threshold:.3f}\n")
print(ad_report.to_string(index=False))

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10.8, 4.0))
xlabels = [f"{nm}\n(n={cnt})" for nm, cnt in zip(q_names, bin_n)]
b_ad = ax1.bar(xlabels, bin_rmses, color=[C.teal, C.steel, C.gold, C.crimson], width=0.54)
for b, v in zip(b_ad, bin_rmses):
    ax1.text(b.get_x() + b.get_width()/2, v + 0.04, f"{v:.2f}", ha="center", fontweight="bold")
ax1.set_ylim(0, 2.3)
ax1.set_ylabel("Test Set RMSE (logS units)")
ax1.set_title("(a) Prediction Error vs. 17D kNN Distance")

ax2.barh(list(CANDIDATE_OSC_17.keys()), cand_dists,
         color=[C.teal if d <= d_threshold else C.crimson for d in cand_dists])
ax2.axvline(d_threshold, ls="--", color=C.gold, lw=2.0, label=f"95% AD Limit ({d_threshold:.2f})")
ax2.set_xlabel("Standardized 17D 5-NN Distance to Training Set")
ax2.set_title("(b) Applicability Domain Flagging on OSCs")
ax2.legend(loc="lower right", fontsize=8.3)

plt.tight_layout()
plt.show()
Out:
训练集 95% 适用域距离阈值 d_AD = 1.773

       Candidate  MolLogP  Pred logS  17D 5-NN Dist  AD Threshold (95%)         AD Status
Benzene (Simple)     1.69      -1.81           0.39                1.77         IN-DOMAIN
      Anthracene     3.99      -5.96           0.32                1.77         IN-DOMAIN
       Pentacene     6.30      -8.37           0.43                1.77         IN-DOMAIN
         C8-BTBT    11.08      -7.05           2.73                1.77 ⚠️ OUT-OF-DOMAIN!
         Rubrene    10.66      -7.28           3.82                1.77 ⚠️ OUT-OF-DOMAIN!
  TIPS-Pentacene    13.44      -7.98           3.96                1.77 ⚠️ OUT-OF-DOMAIN!
Notebook 输出图像

🏋️ 练习 02d-1:用防泄漏 Pipeline + GridSearchCV 调优距离加权 kNN

构建 pipe = make_pipeline(StandardScaler(), KNeighborsRegressor()),在训练集 X_train, y_train 上用 5 折 GridSearchCV 搜索:

  • "kneighborsregressor__n_neighbors": [3, 5, 10, 20]
  • "kneighborsregressor__weights": ["uniform", "distance"] 打印最优超参数 best_params_、5 折 CV RMSE,以及在闭卷测试集 X_test, y_test 上的最终 RMSE!
In [7] · Python
# 🏋️ 练习 02d-1:在这里编写你的代码

🏋️ 练习 02d-2:将异构 ColumnTransformer 流水线接入非线性随机森林

复用第 1 节构造的带缺失值与文本类别列的脏表格 (Xd_tr, yd_tr, Xd_te, yd_te) 和 preprocessor:

  1. 组装 rf_dirty_pipe = Pipeline([("prep", preprocessor), ("rf", RandomForestRegressor(n_estimators=120, random_state=42, n_jobs=-1))]);
  2. 计算它在训练集上的 5 折交叉验证 RMSE 以及在 Xd_te, yd_te 上的测试 RMSE,对比比第 1 节的线性 Ridge 提升了多少!
In [8] · Python
# 🏋️ 练习 02d-2:在这里编写你的代码

模块 02 总结与下一章预告

恭喜你走完了经典监督学习从底层数学推导到工业级防泄漏验证的完整闭环:

  • 02a 线性与正则化:正规方程 vs 梯度下降、偏差–方差分解,以及 Ridge / Lasso / ElasticNet 驯服多重共线性;
  • 02b 分类、距离与核方法:感知机 \(\to\) Sigmoid 逻辑回归 \(\to\) Softmax 三分类、PR-AUC 与基础概率陷阱、以及依赖特征缩放的 kNN 与 RBF-SVM/SVR;
  • 02c 决策树与集成学习:CART 切分、异构 Voting、随机森林(含免费 oob_score)与梯度提升树(XGBoost 测试集 RMSE 1.016),以及并苯同系物外推截断本质;
  • 02d 异构流水线与适用域:SimpleImputer + OneHotEncoder + ColumnTransformer + Pipeline 封死数据泄漏,GridSearchCV / RandomizedSearchCV,GroupKFold 与尺寸外推检验,以及标准化 17 维 kNN 适用域预警(成功拦截 C8-BTBT、Rubrene、TIPS-Pentacene 等越界分子)。

请接着完成 02e_exercises.ipynb(8 道综合实战习题) 巩固本章全部核心技能! 👉 下一章预告(03 - Unsupervised Learning):当手头有成千上万种化合物或配体,却没有任何现成的性质标签 \(y\) 时,怎样通过降维(PCA / t-SNE / UMAP)与聚类自动绘制化学空间地图并发现隐藏材料家族?

读完了?

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

返回模块 02