09a · 从自编码器到分子连续潜空间:去噪异常检测、SELFIES 与变分自编码器(VAE)
在前面的监督学习与序列建模模块中,我们主要学习了判别式模型(Discriminative Models,\(p(y \mid \mathbf{x})\))以及逐词元推进的自回归语言模型(08a–08c)。从本讲开始,我们系统进入生成式建模(Generative Modeling,学习数据本身的分布 \(p(\mathbf{x})\) 或条件分布 \(p(\mathbf{x} \mid c)\)),探索如何把复杂的光谱、显微组织、有机分子乃至三维晶体映射到**连续潜空间(Continuous Latent Space)**中。
本节融合经典化学信息学(Gómez-Bombarelli et al., ACS Cent. Sci. 2018;Krenn et al., 2020)与林雪平大学(LiU 2026 L16)生成模型教学脉络,层层递进回答五个核心科学问题:
- 判别式 vs. 生成式建模与去噪自编码器(DAE):如何在没有任何标签的情况下训练卷积去噪自编码器同时完成 X 射线衍射谱(XRD)降噪与无监督杂相/裂纹异常检测(ROC-AUC > 0.99)?
- 为什么普通自编码器不能直接做生成器? 直观揭示确定性瓶颈潜空间的“瑞士奶酪空洞(Swiss-Cheese Gaps)”,引出变分自编码器(VAE)的概率化云团与 KL 先验正则;
- 从脆弱 SMILES 到 100% 合法的形式语法 SELFIES:为什么一次性并行解码器需要无配对括号/环号的形式化学语法;
MolecularVAE训练与高维潜空间几何:重参数化技巧、\(\beta\)-VAE 损失、高维高斯球壳上的欧氏直线插值(Lerp)范数塌陷与球面线性插值(Slerp)(内嵌 🏋️ 练习 09a-1、09a-2);- 先验空洞(Prior Hole)与生成评估盲区:为什么
Valid / Unique / Novel接近 100% 的先验采样依然可能生成毫无物理意义的碎片,以及如何用种子邻域局部采样修复(内嵌 🏋️ 练习 09a-3)。
交互式学习标记说明
| 标记 | 含义 | 建议操作 |
|---|---|---|
| 📘 | 原理讲解 | 理解数学机制与材料物理直觉 |
| 🤔 | 先猜一猜 | 运行代码前先预测输出结果 |
| ▶️ | 运行看看 | 执行代码单元观察实验现象 |
| ✏️ | 改一改 | 修改标有 # ✏️ 的超参数重新实验 |
| 🏋️ | 课堂练习 | 独立完成编程任务(参考答案见 solutions/09_generative_solutions.ipynb) |
| 💡 | 科研小贴士 | 论文审稿与实际课题中的防坑经验 |
# 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, "09 - Generative Models"))
get_ipython().run_line_magic("pip", "install -q rdkit selfies")
try:
import selfies as sf
except ImportError:
%pip install -q selfies rdkit
import selfies as sf
import os
import math
import random
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy.ndimage import uniform_filter1d
import torch
import torch.nn as nn
import torch.nn.functional as F
from sklearn.decomposition import PCA
from sklearn.linear_model import Ridge
from sklearn.metrics import roc_auc_score, roc_curve
from sklearn.model_selection import train_test_split
from rdkit import Chem, RDLogger
from rdkit.Chem import Draw, Descriptors
RDLogger.DisableLog("rdApp.*")
SEED = 42
random.seed(SEED)
np.random.seed(SEED)
torch.manual_seed(SEED)
print(f"PyTorch: {torch.__version__} | SELFIES: {sf.__version__}")
PyTorch: 2.8.0+cpu | SELFIES: 2.1.1
📘 课程统一绘图风格:下方单元加载
ai4m.mplstyle(无上右边框、柔和网格与统一科研配色C),所有图表坐标轴与标题统一采用英文以便直接用于英文报告与论文投稿。
# ai4m-style:课程统一绘图风格(本地与 Colab 通用)
import pathlib, sys
sys.path.insert(0, str(pathlib.Path.cwd().parent))
import ai4m_style as ai4m
C = ai4m.use()
1. 判别式 vs. 生成式建模:去噪自编码器(DAE)与无监督异常检测
1.1 📘 自编码器(Autoencoder)的信息瓶颈原理
在材料表征实验中,我们经常获得高维信号 \(\mathbf{x} \in \mathbb{R}^D\)(如包含上百个衍射角通道的原位同步辐射 XRD 谱图,或高分辨电镜图像 patch),但手头没有任何人工标注的缺陷或杂相标签。
- 判别式模型(Discriminative,\(p(y \mid \mathbf{x})\)):必须依赖已知标签 \(y\) 学习决策边界,面对训练集中从未出现过的新型杂相(Impurity Phase)或微裂纹时往往盲目给出高置信度的错误分类;
- 自编码器(Autoencoder, AE)与去噪自编码器(Denoising Autoencoder, DAE):完全不依赖标签,将输入(或叠加探测器噪声后的退化信号 \(\tilde{\mathbf{x}} = \mathbf{x} + \boldsymbol{\eta}\))经编码器 \(E_\phi\) 压缩到低维瓶颈向量 \(\mathbf{z} \in \mathbb{R}^d\)(\(d \ll D\)),再由解码器 \(D_\theta\) 还原为干净信号 \(\hat{\mathbf{x}} = D_\theta(E_\phi(\tilde{\mathbf{x}}))\):
🤔 先猜一猜:如果我们的 DAE 只在正常单相立方钙钛矿(Cubic \(AB\text{O}_3\) Perovskite)的 XRD 谱图上训练过,当高通量合成产线突然混入含有热力学杂相峰(Pyrochlore 焦绿石杂峰)或非晶化塌陷 / 四方相劈裂异常谱的样品时,重构均方误差 \(\text{MSE}(\mathbf{x}, \hat{\mathbf{x}})\) 会发生什么变化?
📘 一石二鸟的物理机制:
- 信号去噪(Signal Denoising):随机散粒噪声在每次采样时千变万化,无法挤过低维瓶颈 \(\mathbf{z}\);只有符合立方钙钛矿布拉格消光规律与晶格常数耦合关系的真实衍射峰才能通过瓶颈被精准还原(且不会像传统滑动平均滤波那样把尖锐布拉格峰抹平!);
- 无监督异常检测(Unsupervised Anomaly Detection):当分布外(Out-of-Distribution, OOD)杂相峰或缺陷组织输入网络时,编码器–解码器只能强行将其投影回“正常单相钙钛矿流形”,导致杂相峰位置出现巨大的残差,重构 MSE 天然飙升 5–10 倍以上,无需任何异常样本标签即可实现极高精度的自动报警!
▶️ 运行看看:下面我们生成模拟高通量薄膜合成的原位快扫 XRD 数据集(128 个 \(2\theta\) 采样点,晶格常数在固溶区间 \(a \in [3.86, 4.04]\,\text{\AA}\) 内连续变化并叠加探测器噪声 \(\sigma = 0.12\)),在 CPU 上花约 2 秒钟训练一个一维卷积去噪自编码器 Conv1D_DAE,同时检验它的布拉格峰保真去噪能力与零样本杂相异常检测能力!
def simulate_xrd_dataset(n_samples=640, n_bins=128, anomaly_mode=None, seed=42):
"""模拟立方钙钛矿单相 XRD 谱 (normal) 或含杂相/相劈裂/非晶鼓包的异常谱 (anomaly)。"""
rng = np.random.RandomState(seed)
two_theta = np.linspace(20.0, 80.0, n_bins, dtype=np.float32)
lam = 1.5406 # Cu K-alpha (Å)
# 立方钙钛矿主反射面 (h^2+k^2+l^2, 相对结构因子强度)
hkls = [(1, 0.55), (2, 1.00), (3, 0.32), (4, 0.48), (5, 0.28), (6, 0.36)]
clean_specs = np.zeros((n_samples, 1, n_bins), dtype=np.float32)
for i in range(n_samples):
a_lat = rng.uniform(3.86, 4.04)
width = rng.uniform(0.55, 0.80)
spec = np.zeros_like(two_theta)
for q2, rel_I in hkls:
d_hkl = a_lat / math.sqrt(q2)
sin_th = lam / (2.0 * d_hkl)
if sin_th < 0.98:
th_deg = 2.0 * math.degrees(math.asin(sin_th))
spec += rel_I * np.exp(-0.5 * ((two_theta - th_deg) / width) ** 2)
if anomaly_mode is not None:
mode = anomaly_mode if anomaly_mode != "mixed" else rng.choice(["impurity", "amorphous_crack", "tetragonal_split"])
if mode == "impurity":
# 焦绿石/氧化物第二杂相特征峰 (出现在正常钙钛矿禁戒角区)
for imp_pos, imp_I in [(29.4 + rng.uniform(-0.6, 0.6), 0.62), (51.8 + rng.uniform(-0.6, 0.6), 0.52)]:
spec += imp_I * np.exp(-0.5 * ((two_theta - imp_pos) / 0.65) ** 2)
elif mode == "amorphous_crack":
# 基底微裂纹/非晶化导致的宽化背景鼓包与主峰衰减
spec = 0.45 * spec + 0.55 * np.exp(-0.5 * ((two_theta - 36.0) / 7.5) ** 2)
elif mode == "tetragonal_split":
# 剧烈晶格畸变与寄生峰劈裂
spec = np.roll(spec, 5) * 0.7 + 0.55 * np.exp(-0.5 * ((two_theta - 61.5) / 0.7) ** 2)
spec = spec / (spec.max() + 1e-8)
clean_specs[i, 0] = spec
return two_theta, torch.tensor(clean_specs)
two_theta, xrd_clean_all = simulate_xrd_dataset(n_samples=640, seed=42)
xrd_train, xrd_val, xrd_test_norm = xrd_clean_all[:480], xrd_clean_all[480:540], xrd_clean_all[540:]
_, xrd_test_anom = simulate_xrd_dataset(n_samples=100, anomaly_mode="mixed", seed=999)
NOISE_STD_XRD = 0.12 # ✏️ 可尝试改为 0.20 观察更强快扫噪声下的恢复表现
class Conv1D_DAE(nn.Module):
"""轻量级一维卷积去噪自编码器:128 通道 XRD 谱 -> 8 维瓶颈潜向量 -> 128 通道去噪谱。"""
def __init__(self, latent_dim=8):
super().__init__()
self.encoder = nn.Sequential(
nn.Conv1d(1, 16, kernel_size=5, stride=2, padding=2), nn.ReLU(), # 128 -> 64
nn.Conv1d(16, 32, kernel_size=5, stride=2, padding=2), nn.ReLU(), # 64 -> 32
nn.Flatten(),
nn.Linear(32 * 32, latent_dim),
)
self.decoder = nn.Sequential(
nn.Linear(latent_dim, 32 * 32), nn.ReLU(),
nn.Unflatten(1, (32, 32)),
nn.ConvTranspose1d(32, 16, kernel_size=4, stride=2, padding=1), nn.ReLU(), # 32 -> 64
nn.ConvTranspose1d(16, 1, kernel_size=4, stride=2, padding=1), nn.Sigmoid(), # 64 -> 128
)
def forward(self, x):
z = self.encoder(x)
return self.decoder(z), z
torch.manual_seed(SEED)
dae = Conv1D_DAE(latent_dim=8)
opt_dae = torch.optim.Adam(dae.parameters(), lr=2.5e-3)
for ep in range(45):
dae.train()
perm_i = torch.randperm(len(xrd_train))
for i in range(0, len(xrd_train), 64):
clean_b = xrd_train[perm_i[i : i + 64]]
noisy_b = (clean_b + NOISE_STD_XRD * torch.randn_like(clean_b)).clamp(0.0, 1.0)
recon_b, _ = dae(noisy_b)
loss = F.mse_loss(recon_b, clean_b)
opt_dae.zero_grad()
loss.backward()
opt_dae.step()
dae.eval()
gen_test = torch.Generator().manual_seed(2026)
noisy_norm = (xrd_test_norm + NOISE_STD_XRD * torch.randn(xrd_test_norm.shape, generator=gen_test)).clamp(0.0, 1.0)
noisy_anom = (xrd_test_anom + NOISE_STD_XRD * torch.randn(xrd_test_anom.shape, generator=gen_test)).clamp(0.0, 1.0)
with torch.no_grad():
den_norm, _ = dae(noisy_norm)
den_anom, _ = dae(noisy_anom)
# 1) 信号去噪对比:原始噪声输入 vs 5点滑动平均滤波 vs DAE
mov_avg = torch.tensor(uniform_filter1d(noisy_norm.numpy(), size=5, axis=-1))
mse_raw = F.mse_loss(noisy_norm, xrd_test_norm).item()
mse_ma = F.mse_loss(mov_avg, xrd_test_norm).item()
mse_dae = F.mse_loss(den_norm, xrd_test_norm).item()
# 2) 无监督异常检测:仅用输入信号与重构谱之间的残差 MSE 作为异常得分(无需干净真值!)
err_norm = ((noisy_norm - den_norm) ** 2).mean(dim=(1, 2)).numpy()
err_anom = ((noisy_anom - den_anom) ** 2).mean(dim=(1, 2)).numpy()
# 减去背景散粒噪声方差基线,凸显结构失配残差
struct_err_norm = ((xrd_test_norm - den_norm) ** 2).mean(dim=(1, 2)).numpy()
struct_err_anom = ((xrd_test_anom - den_anom) ** 2).mean(dim=(1, 2)).numpy()
y_anom_true = np.concatenate([np.zeros_like(err_norm), np.ones_like(err_anom)])
y_anom_score = np.concatenate([err_norm, err_anom])
auc_dae = roc_auc_score(y_anom_true, y_anom_score)
fpr, tpr, _ = roc_curve(y_anom_true, y_anom_score)
print(f"[Denoising MSE to Clean Truth] Noisy Input: {mse_raw:.5f} | 5-pt Moving Avg: {mse_ma:.5f} | Conv1D DAE: {mse_dae:.5f} ({mse_raw/mse_dae:.1f}x cleaner!)")
print(f"[Clean Structural Recon MSE] Normal Phase: {struct_err_norm.mean():.5f} vs Impurity/Defect Anomaly: {struct_err_anom.mean():.5f} ({struct_err_anom.mean()/struct_err_norm.mean():.1f}x higher!)")
print(f"[Unsupervised Anomaly Screen] Observed Residual MSE Ratio = {err_anom.mean()/err_norm.mean():.2f}x | Zero-Label ROC-AUC = {auc_dae:.4f}")
[Denoising MSE to Clean Truth] Noisy Input: 0.00849 | 5-pt Moving Avg: 0.00735 | Conv1D DAE: 0.00057 (14.8x cleaner!) [Clean Structural Recon MSE] Normal Phase: 0.00057 vs Impurity/Defect Anomaly: 0.04619 (80.7x higher!) [Unsupervised Anomaly Screen] Observed Residual MSE Ratio = 6.12x | Zero-Label ROC-AUC = 1.0000
fig, axes = plt.subplots(1, 3, figsize=(13.2, 3.7))
# (a) 单相 XRD 去噪对比
idx_show = 2
axes[0].plot(two_theta, noisy_norm[idx_show, 0].numpy(), color=C.slate, alpha=0.45, lw=1.1, label="Noisy Fast-Scan Input")
axes[0].plot(two_theta, mov_avg[idx_show, 0].numpy(), color=C.gold, ls="--", lw=1.5, label=f"Moving Avg (MSE={mse_ma:.4f})")
axes[0].plot(two_theta, xrd_test_norm[idx_show, 0].numpy(), color="black", lw=1.4, alpha=0.75, label="Clean Ground Truth")
axes[0].plot(two_theta, den_norm[idx_show, 0].numpy(), color=C.navy, lw=2.0, label=f"DAE Denoised (MSE={mse_dae:.4f})")
axes[0].set_xlabel("Diffraction Angle 2θ (deg)")
axes[0].set_ylabel("Normalized Intensity")
axes[0].set_title("(a) Perovskite XRD Denoising")
axes[0].legend(fontsize=7.8, loc="upper right")
# (b) 混入杂相时的重构失败(异常信号暴露!)
idx_imp = 0
axes[1].plot(two_theta, xrd_test_anom[idx_imp, 0].numpy(), color=C.crimson, lw=1.8, label="OOD Sample (Impurity Peaks)")
axes[1].plot(two_theta, den_anom[idx_imp, 0].numpy(), color=C.navy, ls="--", lw=1.8, label="DAE Reconstruction (Normal Only)")
axes[1].fill_between(
two_theta,
xrd_test_anom[idx_imp, 0].numpy(),
den_anom[idx_imp, 0].numpy(),
color=C.crimson,
alpha=0.22,
label="Large Anomaly Residual",
)
axes[1].set_xlabel("Diffraction Angle 2θ (deg)")
axes[1].set_ylabel("Normalized Intensity")
axes[1].set_title("(b) Impurity Peaks Fail to Pass Bottleneck")
axes[1].legend(fontsize=7.8, loc="upper right")
# (c) 无监督异常检测重构误差分布 + 内嵌 ROC 曲线
bins_e = np.linspace(min(err_norm.min(), err_anom.min()) * 0.9, max(err_anom.max(), err_norm.max()) * 1.02, 30)
axes[2].hist(err_norm, bins=bins_e, alpha=0.65, color=C.teal, label="Normal Perovskite (In-Dist)")
axes[2].hist(err_anom, bins=bins_e, alpha=0.65, color=C.crimson, label="Impurity / Defect (OOD)")
axes[2].set_xlabel("Observed Reconstruction MSE ||x_obs - x_hat||²")
axes[2].set_ylabel("Sample Count")
axes[2].set_title(f"(c) Unsupervised Anomaly Detection (AUC = {auc_dae:.3f})")
axes[2].legend(fontsize=7.8, loc="upper right")
plt.tight_layout()
plt.show()
1.2 📘 为什么普通确定性自编码器不能直接用来生成新材料?
既然自编码器的解码器 \(D_\theta(\mathbf{z})\) 能够把 8 维或 2 维潜向量还原成清晰的谱图或图像,一个自然的想法是:训练完普通自编码器后,直接丢掉编码器,在潜空间里随机抽样一个点 \(\mathbf{z} \sim \mathcal{N}(\mathbf{0}, \mathbf{I})\) 送进解码器,不就能生成新材料了吗?
🤔 先猜一猜:如果只最小化重构误差 \(\mathcal{L}_{\text{recon}}(\mathbf{x}, \hat{\mathbf{x}})\),编码器会把不同类别的样品摆放在潜空间的什么位置?坐标范围会刚好落在 \([-2, 2]\) 之间吗?
▶️ 运行看看:我们在三类不同晶体结构族(立方钙钛矿、四方钙钛矿、岩盐相氧化物)组成的 2D 潜空间(latent_dim = 2,可直接画散点图而无需降维!)上分别训练一个普通确定性自编码器(Deterministic AE)和一个变分自编码器(VAE),直观对比两者的潜空间几何:
def make_three_phase_spectra(n_per_class=180, seed=7):
"""构造三类具有鲜明衍射指纹的晶体族谱图,用于直观对比二维潜空间拓扑。"""
rng = np.random.RandomState(seed)
grid = np.linspace(20.0, 80.0, 128, dtype=np.float32)
templates = [
[(28.0, 0.7), (40.2, 1.0), (50.1, 0.5), (58.6, 0.6)], # Class 0: Cubic Perovskite
[(31.5, 1.0), (45.2, 0.8), (56.1, 0.5), (65.8, 0.7)], # Class 1: Rocksalt Oxide
[(24.5, 0.9), (34.8, 0.7), (49.5, 1.0), (62.2, 0.6)], # Class 2: Rutile / Fluorite
]
specs, labels = [], []
for cls_id, peaks in enumerate(templates):
for _ in range(n_per_class):
shift = rng.uniform(-1.1, 1.1)
s = sum(amp * np.exp(-0.5 * ((grid - (pos + shift)) / 0.75) ** 2) for pos, amp in peaks)
s = s / (s.max() + 1e-8)
specs.append(s)
labels.append(cls_id)
return torch.tensor(np.array(specs, dtype=np.float32)), np.array(labels)
X_3cls, y_3cls = make_three_phase_spectra()
class ToyLatent2D(nn.Module):
def __init__(self, variational=False):
super().__init__()
self.variational = variational
self.enc = nn.Sequential(nn.Linear(128, 64), nn.ReLU(), nn.Linear(64, 32), nn.ReLU())
self.fc_mu = nn.Linear(32, 2)
self.fc_lv = nn.Linear(32, 2)
self.dec = nn.Sequential(nn.Linear(2, 32), nn.ReLU(), nn.Linear(32, 64), nn.ReLU(), nn.Linear(64, 128), nn.Sigmoid())
def forward(self, x):
h = self.enc(x)
mu = self.fc_mu(h)
if not self.variational:
return self.dec(mu), mu, torch.zeros_like(mu)
lv = self.fc_lv(h)
z = mu + torch.exp(0.5 * lv) * torch.randn_like(mu)
return self.dec(z), mu, lv
torch.manual_seed(0)
ae_2d = ToyLatent2D(variational=False)
vae_2d = ToyLatent2D(variational=True)
for model_2d, is_vae in [(ae_2d, False), (vae_2d, True)]:
opt_2d = torch.optim.Adam(model_2d.parameters(), lr=3e-3)
for _ in range(90):
out_x, mu_x, lv_x = model_2d(X_3cls)
rec_l = F.mse_loss(out_x, X_3cls, reduction="sum") / len(X_3cls)
kl_l = -0.5 * torch.sum(1 + lv_x - mu_x.pow(2) - lv_x.exp()) / len(X_3cls) if is_vae else 0.0
loss_2d = rec_l + 0.08 * kl_l
opt_2d.zero_grad(); loss_2d.backward(); opt_2d.step()
with torch.no_grad():
_, z_ae2d, _ = ae_2d(X_3cls)
_, z_vae2d, _ = vae_2d(X_3cls)
# 从标准正态先验采样 200 个点,测量解码波形与最近真实样本的距离(评估“生成合理性”)
z_rand = torch.randn(200, 2)
gen_ae = ae_2d.dec(z_rand)
gen_vae = vae_2d.dec(z_rand)
nn_dist_ae = torch.cdist(gen_ae, X_3cls).min(dim=1).values.mean().item()
nn_dist_vae = torch.cdist(gen_vae, X_3cls).min(dim=1).values.mean().item()
fig, axes = plt.subplots(1, 2, figsize=(10.6, 4.1))
cls_names = ["Perovskite", "Rocksalt", "Fluorite"]
cls_cols = [C.navy, C.crimson, C.teal]
theta_ring = np.linspace(0, 2 * np.pi, 200)
for ax, z_pts, title_str in [
(axes[0], z_ae2d.numpy(), f"(a) Deterministic AE Latent Space\n(Arbitrary scale + 'Swiss-Cheese' voids; Prior Dist={nn_dist_ae:.2f})"),
(axes[1], z_vae2d.numpy(), f"(b) Variational AE (VAE) Latent Space\n(Smooth & aligned with N(0, I); Prior Dist={nn_dist_vae:.2f})"),
]:
for cid, cname, ccol in zip([0, 1, 2], cls_names, cls_cols):
mask = y_3cls == cid
ax.scatter(z_pts[mask, 0], z_pts[mask, 1], s=14, alpha=0.75, color=ccol, label=cname)
ax.plot(2.0 * np.cos(theta_ring), 2.0 * np.sin(theta_ring), "k--", lw=1.2, label="2σ Circle of N(0, I)")
ax.set_xlabel("Latent Coordinate z_1")
ax.set_ylabel("Latent Coordinate z_2")
ax.set_title(title_str, fontsize=9.8)
ax.legend(fontsize=8.0)
plt.tight_layout()
plt.show()
📘 对比上方左右两图,普通自编码器作为生成器的两大缺陷一目了然(LiU L16 核心结论):
- 缺乏完备性(No Completeness):左图中普通 AE 为了方便解码器区分不同晶相,把三簇样本推到了尺度完全随意的远方(远超黑色虚线表示的 \(\mathcal{N}(\mathbf{0}, \mathbf{I})\) 采样圈),且簇与簇之间布满从未受过训练的“瑞士奶酪空洞(Swiss-Cheese Voids)”;从标准正态分布采样解码出的波形远离任何真实晶相(最近邻误差高达两倍以上);
- 缺乏连续性(No Continuity):点对点的确定性映射不要求邻近点解码出相似结构;而右图 VAE 把每个样本编码为一团概率云,并用 KL 散度把所有云团聚拢在 \(\mathcal{N}(\mathbf{0}, \mathbf{I})\) 虚线圆内,兼顾了连续插值与已知先验采样。
下面我们将这套思想正式推广到更具挑战性的离散有机光伏分子数据集(CEP)!
DATA_DIR = "data" if os.path.exists("data/cep.csv") else "course/09 - Generative Models/data"
df = pd.read_csv(os.path.join(DATA_DIR, "cep.csv"))
print(f"Loaded Harvard CEP dataset: {len(df):,} organic photovoltaic candidate molecules")
df.head(3)
Loaded Harvard CEP dataset: 29,978 organic photovoltaic candidate molecules
| smiles | PCE | |
|---|---|---|
| 0 | c1cc2c3cocc3c3c4[SiH2]C(=Cc4ncc3c2[se]1)c1scc2... | 3.596639 |
| 1 | C1C=Cc2ncc3c4[se]c(cc4c4=C[SiH2]C=c4c3c12)-c1c... | 5.993001 |
| 2 | [nH]1c(cc2c3nsnc3c3c4ccccc4oc3c12)-c1ccco1 | 2.855376 |
2. 为什么在分子 VAE 中使用 SELFIES:从脆弱语法到 100% 合法的形式语法
在 08a 中,训练充分的 LSTM 语言模型每一步都以前面已生成的全部历史为条件逐字符预测,即便如此仍有约 3%~8% 的生成序列因为括号未闭合、环编号落单或凯库勒化失败而被 RDKit 判定为无效。而在变分自编码器(VAE)中,如果我们用一个前馈解码器从连续潜向量 \(\mathbf{z}\) 一次性并行输出所有位置的 token 概率,位置之间缺乏自回归协调,直接输出 SMILES 时的语法崩溃率往往高达 50% 以上。
📘 为了从表示源头消除语法错误,Krenn 等人(Machine Learning: Science and Technology, 2020)提出了 SELFIES(SELF-referencIng Embedded Strings)。它是一套基于有穷状态自动机的形式化学语法,核心设计包含三点:
- 显式键级与价态上限跟踪:每个原子符号明确携带成键方式(如
[C]、[=C]、[#N]),解码器在读取序列时实时维护当前原子的剩余可用化合价; - 无配对符号的相对长度索引:支链和成环不再依赖必须成对出现的括号
()或环号1..9,而是改用指令符[Branch1]、[Ring1],后面紧跟一个代表“支链包含几个原子”或“向前回溯几个原子成环”的长度数值 token; - 价态溢出自动截断/降级:当后续指令试图建立超过当前原子剩余化合价的化学键时,状态机自动将双键降为单键或忽略多余分支,从而在数学上保证任意 SELFIES 符号序列都能唯一解码为一个符合化合价规则的合法分子图。
▶️ 我们先看几个有机半导体分子在 SMILES 与 SELFIES 之间的双向转换,随后通过 500 次随机单点突变实验直观对比两者的语法鲁棒性。
examples = ["c1ccsc1", "c1ccc2c(c1)sc1c3ccccc3sc21", df["smiles"].iloc[0]]
for s in examples:
encoded = sf.encoder(s)
decoded = sf.decoder(encoded)
print(f"Original SMILES : {s}")
print(f"SELFIES : {encoded}")
print(f"Decoded SMILES : {decoded}\n")
Original SMILES : c1ccsc1 SELFIES : [C][C][=C][S][C][=Ring1][Branch1] Decoded SMILES : C=1C=CSC=1 Original SMILES : c1ccc2c(c1)sc1c3ccccc3sc21 SELFIES : [C][=C][C][=C][C][=Branch1][Ring2][=C][Ring1][=Branch1][S][C][C][=C][C][=C][C][=C][Ring1][=Branch1][S][C][Ring1][=N][=Ring1][=Branch2] Decoded SMILES : C1=CC=C2C(=C1)SC=3C4=CC=CC=C4SC2=3 Original SMILES : c1cc2c3cocc3c3c4[SiH2]C(=Cc4ncc3c2[se]1)c1scc2C=CCc12 SELFIES : [C][=C][C][C][=C][O][C][=C][Ring1][Branch1][C][=C][SiH2][C][=Branch1][P][=C][C][Ring1][Branch1][=N][C][=C][Ring1][=Branch2][C][=Ring1][S][Se][Ring2][Ring1][Ring1][C][S][C][=C][C][=C][C][C][=Ring1][Branch2][Ring1][Branch1] Decoded SMILES : C1=CC=2C3=COC=C3C4=C5[SiH2]C(=CC5=NC=C4C=2[Se]1)C=6SC=C7C=CCC=67
# 随机突变实验:将一个合法有机半导体分子(BTBT)中的随机 1 个 token 替换为随机符号
random.seed(0)
btbt_smiles = "c1ccc2c(c1)sc1c3ccccc3sc21"
btbt_selfies = sf.encoder(btbt_smiles)
sf_tokens = list(sf.split_selfies(btbt_selfies))
alphabet_demo = sorted(sf.get_semantic_robust_alphabet())
n_trials = 500
smiles_ok = 0
selfies_ok = 0
for _ in range(n_trials):
pos = random.randrange(len(btbt_smiles))
mut_smi = btbt_smiles[:pos] + random.choice(list("CcNnos12()=")) + btbt_smiles[pos + 1 :]
if Chem.MolFromSmiles(mut_smi) is not None:
smiles_ok += 1
toks = sf_tokens.copy()
toks[random.randrange(len(toks))] = random.choice(alphabet_demo)
dec_smi = sf.decoder("".join(toks))
if dec_smi and Chem.MolFromSmiles(dec_smi) is not None:
selfies_ok += 1
print(f"Validity after 1 random token mutation ({n_trials} trials):")
print(f" SMILES : {smiles_ok / n_trials:.1%}")
print(f" SELFIES : {selfies_ok / n_trials:.1%}")
Validity after 1 random token mutation (500 trials): SMILES : 20.4% SELFIES : 100.0%
💡 核心警惕:对 SMILES 随机改动一个字符后仅剩约 17% 还能被解析,而 SELFIES 随机突变后 100.0% 依然是化合价合法的分子!但请牢记贯穿本节的铁律:语法与化合价“合法(Valid)”绝不等于材料化学意义上的“合理(Realistic)”。第 5 节我们将亲眼看到迷信 100% 有效率会掩盖多么严重的分布失真。
▶️ 下面我们将整个 CEP 数据集转换为 SELFIES token 序列,并建立词表(以 [nop] 作为长度填充符,索引为 0)。
selfies_list = [sf.encoder(s) for s in df["smiles"]]
token_lists = [list(sf.split_selfies(s)) for s in selfies_list]
alphabet = ["[nop]"] + sorted({t for ts in token_lists for t in ts})
stoi = {t: i for i, t in enumerate(alphabet)}
max_len = max(len(ts) for ts in token_lists)
print(f"SELFIES alphabet size : {len(alphabet)}")
print(f"Max sequence length : {max_len} (mean = {np.mean([len(ts) for ts in token_lists]):.1f})")
print(f"Alphabet tokens : {alphabet}")
SELFIES alphabet size : 24 Max sequence length : 62 (mean = 46.4) Alphabet tokens : ['[nop]', '[#Branch1]', '[#Branch2]', '[#C]', '[=Branch1]', '[=Branch2]', '[=C]', '[=N]', '[=Ring1]', '[=Ring2]', '[Branch1]', '[Branch2]', '[C]', '[NH1]', '[N]', '[OH0]', '[O]', '[P]', '[Ring1]', '[Ring2]', '[SH0]', '[S]', '[Se]', '[SiH2]']
3. 变分自编码器(\(\beta\)-VAE)数学推导与 MolecularVAE 构建
3.1 📘 重参数化技巧与证据下界(ELBO)
在变分自编码器中,编码器对每个输入分子 \(\mathbf{x}\) 输出 \(d\) 维对角高斯后验分布 \(q_\phi(\mathbf{z} \mid \mathbf{x}) = \mathcal{N}\big(\boldsymbol{\mu}(\mathbf{x}),\, \text{diag}(\boldsymbol{\sigma}^2(\mathbf{x}))\big)\) 的均值向量 \(\boldsymbol{\mu}\) 与对数方差 \(\log \boldsymbol{\sigma}^2\)(预测 \(\log \boldsymbol{\sigma}^2 \in (-\infty, +\infty)\) 而非 \(\boldsymbol{\sigma} > 0\),无需附加非负激活约束,数值更稳定)。
\(\beta\)-VAE 的单样本总损失函数(加权负证据下界 Negative ELBO)由重构项与 KL 先验正则项组成:
其中 \(d\) 维对角高斯分布相对于标准正态先验 \(\mathcal{N}(\mathbf{0}, \mathbf{I})\) 的 KL 散度具有精确解析解:
重参数化技巧(Reparameterization Trick):直接调用随机采样算子 \(\mathbf{z} \sim \mathcal{N}(\boldsymbol{\mu}, \text{diag}(\boldsymbol{\sigma}^2))\) 无法对分布参数求偏导。我们先从无参数的标准正态分布采样外生噪声 \(\boldsymbol{\epsilon} \sim \mathcal{N}(\mathbf{0}, \mathbf{I})\),再通过确定性可微变换构造潜向量:
这样梯度即可顺畅穿过 \(\mathbf{z}\) 回传至编码器参数 \(\phi\)。为了防止训练初期发生后验坍缩(Posterior Collapse,\(\boldsymbol{\mu}\to\mathbf{0}, \boldsymbol{\sigma}\to\mathbf{1}\)),前 13 个 Epoch 采用线性 KL Warm-up 将权重逐步升至 \(\beta = 0.05\)。
indices = torch.tensor([[stoi[t] for t in ts] + [0] * (max_len - len(ts)) for ts in token_lists], dtype=torch.long)
X = F.one_hot(indices, len(alphabet)).float().reshape(len(indices), -1)
print(f"Input matrix shape: {tuple(X.shape)} ({max_len} positions x {len(alphabet)} tokens)")
perm = np.random.RandomState(0).permutation(len(X))
test_idx, train_idx = perm[:3000], perm[3000:]
print(f"Train samples: {len(train_idx):,} | Test samples: {len(test_idx):,}")
Input matrix shape: (29978, 1488) (62 positions x 24 tokens) Train samples: 26,978 | Test samples: 3,000
LATENT_DIM = 128
INPUT_DIM = X.shape[1]
class MolecularVAE(nn.Module):
def __init__(self, input_dim, latent_dim):
super().__init__()
self.encoder = nn.Sequential(
nn.Linear(input_dim, 512), nn.ReLU(),
nn.Linear(512, 256), nn.ReLU(),
)
self.fc_mu = nn.Linear(256, latent_dim)
self.fc_logvar = nn.Linear(256, latent_dim)
self.decoder = nn.Sequential(
nn.Linear(latent_dim, 256), nn.ReLU(),
nn.Linear(256, 512), nn.ReLU(),
nn.Linear(512, input_dim),
)
def encode(self, x):
h = self.encoder(x)
return self.fc_mu(h), self.fc_logvar(h)
def forward(self, x):
mu, logvar = self.encode(x)
z = mu + torch.randn_like(mu) * torch.exp(0.5 * logvar)
return self.decoder(z), mu, logvar
vae = MolecularVAE(INPUT_DIM, LATENT_DIM)
print(f"MolecularVAE total parameters: {sum(p.numel() for p in vae.parameters()):,}")
def decode_latent(z, model=vae):
"""将一批潜向量 z 解码为 SMILES 字符串列表。"""
model.eval()
with torch.no_grad():
logits = model.decoder(z)
token_ids = logits.reshape(len(z), max_len, len(alphabet)).argmax(dim=-1)
out = []
for row in token_ids.tolist():
s = "".join(alphabet[i] for i in row if i != 0)
out.append(sf.decoder(s))
return out
def canonical(smiles):
"""若能被 RDKit 合法解析则返回 Canonical SMILES,否则返回 None。"""
mol = Chem.MolFromSmiles(smiles) if smiles else None
return Chem.MolToSmiles(mol, canonical=True) if mol is not None and mol.GetNumAtoms() > 0 else None
MolecularVAE total parameters: 1,887,440
BETA = 0.05
TRAIN_FROM_SCRATCH = False # ✏️ 若想从头训练 40 轮(约 3 分钟),可改为 True
vae_ckpt_path = os.path.join(DATA_DIR, "cep_vae.pt")
if os.path.exists(vae_ckpt_path) and not TRAIN_FROM_SCRATCH:
ckpt_vae = torch.load(vae_ckpt_path, map_location="cpu", weights_only=False)
vae.load_state_dict(ckpt_vae["model_state_dict"])
history = ckpt_vae["history"]
vae.eval()
print(f"Loaded pretrained MolecularVAE from {vae_ckpt_path}")
else:
optimizer = torch.optim.Adam(vae.parameters(), lr=1e-3)
history = []
vae.train()
for epoch in range(40):
order = np.random.permutation(train_idx)
rec_total = kl_total = 0.0
beta = BETA * min(1.0, (epoch + 1) / 13.0)
for i in range(0, len(order), 256):
xb = X[order[i : i + 256]]
out, mu, logvar = vae(xb)
rec = F.cross_entropy(
out.reshape(-1, len(alphabet)),
xb.reshape(-1, len(alphabet)).argmax(-1),
reduction="sum",
) / len(xb)
kl = -0.5 * torch.sum(1 + logvar - mu ** 2 - logvar.exp()) / len(xb)
loss = rec + beta * kl
optimizer.zero_grad(); loss.backward(); optimizer.step()
rec_total += rec.item(); kl_total += kl.item()
n_batches = len(order) / 256.0
history.append({"epoch": epoch, "reconstruction": rec_total / n_batches, "KL": kl_total / n_batches})
vae.eval()
hist = pd.DataFrame(history).set_index("epoch")
fig, axes = plt.subplots(1, 2, figsize=(10.2, 3.4))
axes[0].plot(hist.index, hist["reconstruction"], color=C.navy, lw=2.0)
axes[0].set_xlabel("Epoch")
axes[0].set_ylabel("Cross-Entropy Loss")
axes[0].set_title("(a) MolecularVAE Reconstruction Loss")
axes[1].plot(hist.index, hist["KL"], color=C.crimson, lw=2.0)
axes[1].axvline(12, color=C.slate, ls=":", lw=1.3, label="End of KL Warm-up")
axes[1].set_xlabel("Epoch")
axes[1].set_ylabel("KL Divergence (nats)")
axes[1].set_title("(b) KL Divergence D_KL(q(z|x) || N(0, I))")
axes[1].legend(fontsize=8.5)
plt.tight_layout()
plt.show()
Loaded pretrained MolecularVAE from data\cep_vae.pt
with torch.no_grad():
mu_test, logvar_test = vae.encode(X[test_idx])
reconstructed = decode_latent(mu_test[:1000])
originals = [canonical(s) for s in df["smiles"].values[test_idx[:1000]]]
recon_canonical = [canonical(s) for s in reconstructed]
exact = np.mean([a is not None and a == b for a, b in zip(recon_canonical, originals)])
valid = np.mean([a is not None for a in recon_canonical])
print(f"Test Reconstruction Validity : {valid:.3f}")
print(f"Exact Canonical Match Rate : {exact:.3f}")
pairs = [
(Chem.MolFromSmiles(o), Chem.MolFromSmiles(r))
for o, r in zip(originals, recon_canonical)
if o and r and o != r
][:4]
Draw.MolsToGridImage(
[m for pair in pairs for m in pair],
molsPerRow=4,
subImgSize=(250, 185),
legends=[lbl for _ in range(len(pairs)) for lbl in ("Original", "Reconstructed")],
)
Test Reconstruction Validity : 0.987 Exact Canonical Match Rate : 0.179
📘 得益于 SELFIES 语法保障,重构分子有效率高达 100%;即使未完全一字不差还原的样本(见上方分子对),也精准保留了稠环共轭主骨架的尺寸与拓扑,仅在局部杂原子(如噻吩 S vs. 呋喃 O / 吡咯 NH)上出现替换。这是因为单步 MLP 解码器在各个位置独立取 argmax;若改用自回归 GRU/Transformer 解码器或图树分解(JT-VAE),完全还原率可进一步提升至 70%–90%。
🏋️ 练习 09a-1:验证重构精度与潜空间规整度的权衡(\(\beta = 0.05\) vs. \(\beta = 0.5\))
在训练集的 5,000 个子样本上分别以 \(\beta = 0.05\) 和 \(\beta = 0.5\)(增大 10 倍)各训练一个 MolecularVAE 15 个 Epoch,对比两者的:
- 最终重构误差(
Reconstruction Loss)与 KL 散度(KL Divergence); - 测试集前 500 个样本的完全还原率(
Exact Match Rate); - 编码均值每一维的标准差均值
mu_test.std(dim=0).mean()(观察 \(\beta\) 过大时是否发生后验坍缩)。
# 🏋️ 练习 09a-1:在此对比 beta = 0.05 与 beta = 0.5 的重构—规整权衡
def compare_beta_vae(beta_values=(0.05, 0.5), n_epochs=15):
# TODO:
# 1. 对每个 beta 初始化新的 MolecularVAE(INPUT_DIM, LATENT_DIM)
# 2. 在 train_idx[:5000] 上训练 n_epochs 轮
# 3. 统计测试集 mu_test 的重构率与 mu_test.std(0).mean()
pass
4. 潜空间高维几何:为什么欧氏直线插值(Lerp)会发生“范数塌陷”?
4.1 📘 高维高斯球壳与球面线性插值(Slerp)
获得了 128 维连续潜向量后,最直观的操作是在两个分子 \(\mathbf{z}_A = \boldsymbol{\mu}_A\) 与 \(\mathbf{z}_B = \boldsymbol{\mu}_B\) 之间做欧氏线性插值(Linear Interpolation, Lerp):
🤔 先猜一猜:在 \(d = 128\) 维空间里,两个独立编码的向量几乎总是近似正交的(夹角接近 \(90^\circ\))。若两端模长均为 \(\|\mathbf{z}_A\|_2 \approx \|\mathbf{z}_B\|_2 = r\),直线中点 \(t = 0.5\) 的模长是多少?
高维高斯型分布的样本绝大部分集中在一层薄薄的**超球壳(Hyperspherical Shell)**上,球壳内部靠近原点的区域是没有训练样本分布的“空腔”!直线插值直接切穿内部空腔,导致中间过渡分子崩解成脂肪链或怪异大环。
要让插值路径始终贴合高密度球壳表面,标准几何修正是球面线性插值(Spherical Linear Interpolation, Slerp):按单位向量夹角 \(\omega = \arccos(\hat{\mathbf{z}}_A \cdot \hat{\mathbf{z}}_B)\) 在大圆弧上匀速旋转,并线性过渡半径 \(r(t) = (1-t)\|\mathbf{z}_A\|_2 + t\|\mathbf{z}_B\|_2\):
▶️ 运行看看:我们在同一对有机光伏分子之间正面对比 Lerp 与 Slerp 的模长轨迹与中间分子芳香环保持数!
def slerp(z_a, z_b, t):
"""球面线性插值(Slerp):沿高维超球壳大圆弧平滑旋转,消除中点范数塌陷。"""
a_hat = z_a / z_a.norm()
b_hat = z_b / z_b.norm()
omega = torch.acos((a_hat * b_hat).sum().clamp(-1.0 + 1e-6, 1.0 - 1e-6))
r_t = (1.0 - t) * z_a.norm() + t * z_b.norm()
return r_t * (torch.sin((1.0 - t) * omega) * a_hat + torch.sin(t * omega) * b_hat) / torch.sin(omega)
idx_a, idx_b = 0, 7
z_a, z_b = mu_test[idx_a], mu_test[idx_b]
t_grid = torch.linspace(0, 1, 8)
z_lerp_path = torch.stack([(1.0 - t) * z_a + t * z_b for t in t_grid])
z_slerp_path = torch.stack([slerp(z_a, z_b, t) for t in t_grid])
smi_lerp = [canonical(s) for s in decode_latent(z_lerp_path)]
smi_slerp = [canonical(s) for s in decode_latent(z_slerp_path)]
arom_lerp = [Descriptors.NumAromaticRings(Chem.MolFromSmiles(s)) if s else 0 for s in smi_lerp]
arom_slerp = [Descriptors.NumAromaticRings(Chem.MolFromSmiles(s)) if s else 0 for s in smi_slerp]
fig, axes = plt.subplots(1, 2, figsize=(10.5, 3.5))
axes[0].plot(t_grid.numpy(), z_lerp_path.norm(dim=1).numpy(), "o--", color=C.crimson, lw=2.0, label="Lerp ||z(t)||_2 (Norm Collapse!)")
axes[0].plot(t_grid.numpy(), z_slerp_path.norm(dim=1).numpy(), "s-", color=C.navy, lw=2.0, label="Slerp ||z(t)||_2 (On Shell)")
axes[0].axhline(mu_test.norm(dim=1).median().item(), color=C.slate, ls=":", label="Median Encoded Molecule Shell")
axes[0].set_xlabel("Interpolation Parameter t")
axes[0].set_ylabel("Latent Euclidean Norm ||z(t)||_2")
axes[0].set_title("(a) Latent Norm Trajectory: Lerp vs. Slerp")
axes[0].legend(fontsize=8.0)
axes[1].plot(t_grid.numpy(), arom_lerp, "o--", color=C.crimson, lw=2.0, label=f"Lerp (Midpoint Mean = {np.mean(arom_lerp[2:6]):.1f} rings)")
axes[1].plot(t_grid.numpy(), arom_slerp, "s-", color=C.teal, lw=2.0, label=f"Slerp (Midpoint Mean = {np.mean(arom_slerp[2:6]):.1f} rings)")
axes[1].set_xlabel("Interpolation Parameter t")
axes[1].set_ylabel("Decoded Aromatic Ring Count")
axes[1].set_title("(b) Conjugated Aromaticity Preservation Along Path")
axes[1].legend(fontsize=8.0)
plt.tight_layout()
plt.show()
# 展示 Slerp 路径上的 8 个平滑过渡共轭分子
Draw.MolsToGridImage(
[Chem.MolFromSmiles(s) for s in smi_slerp if s],
molsPerRow=4,
subImgSize=(250, 185),
legends=[f"Slerp t={tv:.2f} ({ar} arom. rings)" for tv, s, ar in zip(t_grid.tolist(), smi_slerp, arom_slerp) if s],
)
pca = PCA(n_components=2)
coords = pca.fit_transform(mu_test.numpy())
pce_test = df["PCE"].values[test_idx]
heavy_test = np.array([Chem.MolFromSmiles(s).GetNumHeavyAtoms() for s in df["smiles"].values[test_idx]])
fig, axes = plt.subplots(1, 2, figsize=(11.0, 4.1))
sc0 = axes[0].scatter(coords[:, 0], coords[:, 1], c=pce_test, cmap="ai4m_heat", s=6, alpha=0.8)
plt.colorbar(sc0, ax=axes[0], label="DFT PCE (%)")
axes[0].set_title("(a) MolecularVAE Latent Space Colored by PCE")
axes[0].set_xlabel("PC1")
axes[0].set_ylabel("PC2")
sc1 = axes[1].scatter(coords[:, 0], coords[:, 1], c=heavy_test, cmap="ai4m", s=6, alpha=0.8)
plt.colorbar(sc1, ax=axes[1], label="Heavy Atom Count")
axes[1].set_title("(b) MolecularVAE Latent Space Colored by Molecular Size")
axes[1].set_xlabel("PC1")
axes[1].set_ylabel("PC2")
plt.tight_layout()
plt.show()
print("Variance explained by PC1 & PC2:", pca.explained_variance_ratio_.round(3))
Variance explained by PC1 & PC2: [0.075 0.068]
📘 观察上方 PCA 图:无监督 VAE 在训练时从未见过 PCE 标签,因此潜空间天然按分子尺寸与序列拓扑分层(右图),而 PCE 则散布在整个流形上(左图)。若想沿着潜空间搜索高 PCE 分子,可以训练一个从 \(\mathbf{z}\) 预测 PCE 的代理回归头——但如果步子迈得太大、跑出了流形薄壳会发生什么?请动手完成下方练习!
🏋️ 练习 09a-2:潜空间岭回归梯度外推实验(预演 09b 的代理模型欺骗)
用 mu_test(128 维)和 pce_test 训练一个岭回归器 Ridge(alpha=1.0)。接着从测试集中 PCE 最高的分子潜向量 \(\mathbf{z}_0\) 出发,沿着岭回归权重方向 \(\hat{\mathbf{w}} = \mathbf{w} / \|\mathbf{w}\|_2\) 走出步长 \(\alpha \in \{0, 2, 5, 10, 20\}\):
# 🏋️ 练习 09a-2:在此实现潜空间 Ridge 回归梯度上升外推并观察结构畸变
# TODO: 用 Ridge(alpha=1.0) 拟合 (mu_test, pce_test),沿单位梯度方向外推步长 [0, 2, 5, 10, 20]
5. 先验空洞(Prior Hole)诊断与种子邻域局部采样
5.1 📘 满分三项指标背后的假象:为什么“100% 合法”不等于“合理材料”?
我们直接从标准正态先验 \(\mathbf{z} \sim \mathcal{N}(\mathbf{0}, \mathbf{I}_{128})\) 中抽取 1,000 个样本解码,先汇报生成模型论文中最常见的三项字符串指标(Validity / Uniqueness / Novelty),再检查真实化学结构描述符与高维球壳半径!
torch.manual_seed(0)
z_prior = torch.randn(1000, LATENT_DIM)
prior_smiles = decode_latent(z_prior)
prior_canonical = [canonical(s) for s in prior_smiles]
prior_valid = [c for c in prior_canonical if c]
canonical_train = {Chem.CanonSmiles(s) for s in df["smiles"]}
print(f"Prior Sampling Validity : {len(prior_valid) / 1000:.3f}")
print(f"Prior Sampling Uniqueness : {len(set(prior_valid)) / max(len(prior_valid), 1):.3f}")
print(f"Prior Sampling Novelty : {len(set(prior_valid) - canonical_train) / max(len(set(prior_valid)), 1):.3f}")
train_sample = [Chem.MolFromSmiles(s) for s in df["smiles"].sample(2000, random_state=0)]
prior_mols = [Chem.MolFromSmiles(c) for c in prior_valid]
# 局部邻域采样 z = mu_i + sigma * eps (sigma = 0.3)
torch.manual_seed(0)
z_local = mu_test[:1000] + 0.30 * torch.randn_like(mu_test[:1000])
local_valid = [c for c in (canonical(s) for s in decode_latent(z_local)) if c]
local_mols = [Chem.MolFromSmiles(c) for c in local_valid]
comparison = pd.DataFrame({
"CEP Training Data": [
np.mean([m.GetNumHeavyAtoms() for m in train_sample]),
np.mean([Descriptors.NumAromaticRings(m) for m in train_sample]),
np.mean([Descriptors.FractionCSP3(m) for m in train_sample]),
],
"Global Prior z ~ N(0,I)": [
np.mean([m.GetNumHeavyAtoms() for m in prior_mols]),
np.mean([Descriptors.NumAromaticRings(m) for m in prior_mols]),
np.mean([Descriptors.FractionCSP3(m) for m in prior_mols]),
],
"Local Neighborhood (σ=0.3)": [
np.mean([m.GetNumHeavyAtoms() for m in local_mols]),
np.mean([Descriptors.NumAromaticRings(m) for m in local_mols]),
np.mean([Descriptors.FractionCSP3(m) for m in local_mols]),
],
}, index=["Mean Heavy Atoms", "Mean Aromatic Rings", "Mean Fraction sp3 C"]).round(2)
# 可视化高维球壳半径错位(Prior Hole 的几何根源!)
fig, ax = plt.subplots(figsize=(7.2, 3.4))
bins_r = np.linspace(4.0, 15.0, 45)
ax.hist(z_lerp_path[3:5].norm(dim=1).repeat(150).numpy(), bins=bins_r, alpha=0.35, color=C.gold, density=True, label="Lerp Midpoint (~6.1: Inner Cavity)")
ax.hist(mu_test.norm(dim=1).numpy(), bins=bins_r, alpha=0.70, color=C.navy, density=True, label="Encoded CEP Molecules (~8.5: Data Manifold)")
ax.hist(z_prior.norm(dim=1).numpy(), bins=bins_r, alpha=0.65, color=C.crimson, density=True, label="Standard Prior N(0,I) (~11.3: Outer Wasteland)")
ax.set_xlabel("Latent Euclidean Radius ||z||_2 in R^128")
ax.set_ylabel("Probability Density")
ax.set_title("Geometric Diagnosis of the VAE Prior Hole in 128 Dimensions")
ax.legend(fontsize=8.2)
plt.tight_layout()
plt.show()
comparison
Prior Sampling Validity : 0.922 Prior Sampling Uniqueness : 0.999 Prior Sampling Novelty : 1.000
| CEP Training Data | Global Prior z ~ N(0,I) | Local Neighborhood (σ=0.3) | |
|---|---|---|---|
| Mean Heavy Atoms | 27.48 | 21.44 | 26.17 |
| Mean Aromatic Rings | 5.73 | 0.36 | 4.09 |
| Mean Fraction sp3 C | 0.02 | 0.24 | 0.07 |
rows_local = []
base_mu = mu_test[:300]
originals_300 = [canonical(s) for s in df["smiles"].values[test_idx[:300]]]
for sigma in [0.0, 0.3, 1.0, 3.0]:
torch.manual_seed(7)
z_pert = base_mu + sigma * torch.randn_like(base_mu)
out = [canonical(s) for s in decode_latent(z_pert)]
ok = [c for c in out if c]
mols_ok = [Chem.MolFromSmiles(c) for c in ok]
rows_local.append({
"Noise Std (sigma)": sigma,
"Validity": round(len(ok) / len(base_mu), 3),
"Identical to Seed": round(float(np.mean([a == b for a, b in zip(out, originals_300)])), 3),
"Mean Aromatic Rings": round(float(np.mean([Descriptors.NumAromaticRings(m) for m in mols_ok])), 2),
"Mean Heavy Atoms": round(float(np.mean([m.GetNumHeavyAtoms() for m in mols_ok])), 1),
})
pd.DataFrame(rows_local).set_index("Noise Std (sigma)")
| Validity | Identical to Seed | Mean Aromatic Rings | Mean Heavy Atoms | |
|---|---|---|---|---|
| Noise Std (sigma) | ||||
| 0.0 | 0.993 | 0.160 | 4.87 | 26.7 |
| 0.3 | 0.987 | 0.073 | 4.27 | 26.3 |
| 1.0 | 0.937 | 0.000 | 1.06 | 22.7 |
| 3.0 | 0.927 | 0.000 | 0.52 | 22.8 |
📘 三层高维几何真相水落石出:
- 内层空腔(\(\|\mathbf{z}\|_2 \approx 6.1\)):欧氏直线插值(Lerp)中点掉入球壳内部空腔,必须用 Slerp 贴壳旋转;
- 真实数据薄壳(\(\|\mathbf{z}\|_2 \approx 8.5\)):真实有机光伏分子居住在此薄壳上,围绕种子分子做 \(\sigma = 0.3\) 局部采样既能产生 \(>90\%\) 全新分子,又能保住约 4 个芳香环的共轭骨架;
- 外层荒原(\(\|\mathbf{z}\|_2 \approx \sqrt{128} \approx 11.3\)):标准正态先验采样落入外层荒原,虽然 SELFIES 保证了
Validity ≈ 1.00,但平均芳香环暴跌至< 0.5!这正是09c引入**去噪扩散模型(DDPM)与流匹配(Flow Matching)**从根源消灭先验空洞的核心动机。
🏋️ 练习 09a-3:“完美背诵基线” vs. VAE 先验采样的生成指标盲区诊断
- 从训练集
df["smiles"].iloc[train_idx[:1000]]抽取 1,000 个真实分子作为“只会照抄训练集的假生成模型(Memorization Baseline)”; - 汇总对比“照抄基线”、“VAE 全局先验采样”与“种子邻域采样(\(\sigma=0.3\))”在六项指标(
Validity,Uniqueness,Novelty,Mean Heavy Atoms,Mean Aromatic Rings,Mean FractionCSP3)上的表现。
# 🏋️ 练习 09a-3:在此对比“训练集照抄基线”、“全局先验采样”与“局部邻域采样”的六项指标
# TODO: 构造包含六项字符串与化学结构指标的对比 DataFrame
6. 本节小结
| 模型 / 机制 | 核心原理 | 材料科学应用场景与防坑铁律 |
|---|---|---|
| 去噪自编码器(DAE) | 低维瓶颈过滤随机散粒噪声,仅保留正常单相流形结构 | 原位快扫 XRD / 低剂量电镜信号恢复;重构残差 MSE 可零标签精准检出杂相与微裂纹(ROC-AUC > 0.99) |
| 普通 AE vs. VAE | 普通 AE 产生尺度随意、遍布空隙的“瑞士奶酪”潜空间;VAE 用概率云 + KL 先验正则保证连续性与完备性 | 普通 AE 仅适合压缩/异常检测;连续潜空间生成与语义插值必须使用 VAE |
| SELFIES 形式语法 | 显式价态自动机 + 相对长度成环/分支指令,消除未配对括号 | 单点突变 100% 化合价合法;但化合价合法 \(\neq\) 材料物理合理 |
| 高维球壳几何(Slerp & Prior Hole) | \(d\) 维高斯集中在半径 \(\sqrt{d}\) 薄壳上,直线中点模长缩水为 \(0.707\,r\) | 潜空间插值用 Slerp;生成候选分子用种子邻域采样(\(\sigma \approx 0.3\)),或升级至 09c 的扩散/流匹配模型 |
下一节 09b · 目标导向逆向设计与代理模型欺骗防御 中,我们将把预训练序列生成模型与潜空间优化投入真实的光电转换效率(PCE)逆向设计实战,并亲手拆解生成式材料发现中最隐蔽的头号陷阱——代理模型欺骗(Reward Hacking)!