课件答案 第三部分 · 练习参考答案
直接阅读答案的学习效果远低于独立实现。建议至少尝试 20 分钟,卡住时先看习题里的 💡 提示,再展开本页。
展开状态只在当前浏览器标签页有效,关闭标签页后会重新折叠。
第三部分 · 练习参考答案
⚠️ 先自己做,再看答案。 写法不唯一,能得到同样结果的都对。
神经网络的结果和随机种子、软件版本有关,你的数字和这里差在小数点后第二位是正常的。
下面先把 07a 和 10a 共用的准备工作做一遍(和 notebook 里的代码完全相同)。整个 notebook 运行大约 10 分钟,其中 chemprop 的两个练习占一半。
# 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, "10 - Graph Neural Networks and MLIPs/solutions"))
get_ipython().run_line_magic("pip", "install -q rdkit chemprop")
try:
import rdkit
except ImportError:
%pip install -q rdkit
import rdkit
import copy
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import torch
from torch import nn
from rdkit import Chem, RDLogger
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
RDLogger.DisableLog("rdApp.*")
print("PyTorch 版本:", torch.__version__)
📘 课程统一绘图风格:下面这格加载课程自带的
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,返回课程配色
def set_seed(seed=0):
torch.manual_seed(seed)
np.random.seed(seed)
torch.use_deterministic_algorithms(True) # 有些运算默认每次结果略有不同,这一行让它们也固定下来
set_seed(0)
import os
import pandas as pd
# 本地运行:数据在 data/ 文件夹里
# Colab 运行:如果找不到文件,会弹出上传按钮,选择 solubility.csv 即可
DATA_FILE = "../data/solubility.csv"
if not os.path.exists(DATA_FILE):
DATA_FILE = "solubility.csv"
if not os.path.exists(DATA_FILE):
try:
from google.colab import files
print("请上传 solubility.csv")
files.upload()
except ImportError:
raise FileNotFoundError("找不到 solubility.csv,请把它放在 data/ 文件夹或和 notebook 同一个文件夹里")
df = pd.read_csv(DATA_FILE)
print("读取成功!一共", len(df), "个分子")
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
y = df["Solubility"].values
print("分子数:", len(df), " 特征数:", X.shape[1])
X_trval, X_test, y_trval, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
X_train, X_valid, y_train, y_valid = train_test_split(X_trval, y_trval, test_size=0.1, random_state=42)
print("训练:", len(X_train), " 验证:", len(X_valid), " 测试:", len(X_test))
scaler = StandardScaler().fit(X_train) # 和 kNN 一样,神经网络也需要缩放;只在训练集上 fit
def to_tensor(a):
return torch.tensor(a, dtype=torch.float32)
Xtr, Xva, Xte = (to_tensor(scaler.transform(a)) for a in (X_train, X_valid, X_test))
ytr, yva, yte = (to_tensor(a) for a in (y_train, y_valid, y_test))
from torch.utils.data import DataLoader, TensorDataset
train_loader = DataLoader(TensorDataset(Xtr, ytr), batch_size=64, shuffle=True)
xb, yb = next(iter(train_loader)) # 取出第一个小批看看
print("一个小批的 X:", xb.shape, " y:", yb.shape)
print("每个 epoch 有", len(train_loader), "个小批,也就是更新", len(train_loader), "次参数")
class SolubilityMLP(nn.Module):
def __init__(self, n_features, hidden_size=64, dropout=0.0):
super().__init__() # 先让 nn.Module 做好它的准备工作
self.net = nn.Sequential(
nn.Linear(n_features, hidden_size),
nn.ReLU(),
nn.Dropout(dropout), # 第 6 节再讲;dropout=0 时什么也不做
nn.Linear(hidden_size, hidden_size),
nn.ReLU(),
nn.Dropout(dropout),
nn.Linear(hidden_size, 1),
)
def forward(self, x):
return self.net(x).squeeze(1) # 形状 (batch, 1) -> (batch,)
set_seed(0)
model = SolubilityMLP(n_features=17)
print(model)
loss_fn = nn.MSELoss()
def train_one_epoch(model, loader, optimizer):
model.train() # 训练模式(Dropout 生效)
for xb, yb in loader:
loss = loss_fn(model(xb), yb)
optimizer.zero_grad()
loss.backward()
optimizer.step()
def rmse(model, X, y):
model.eval() # 评估模式(Dropout 关闭)
with torch.no_grad(): # 评估时不需要求导,更快也更省内存
return torch.sqrt(loss_fn(model(X), y)).item()
def fit(model, n_epochs=100, lr=1e-3, weight_decay=0.0):
"""训练 n_epochs 轮。返回每一轮的训练/验证 RMSE,以及验证集上最好的那一轮的参数。"""
optimizer = torch.optim.Adam(model.parameters(), lr=lr, weight_decay=weight_decay)
history = {"train": [], "valid": []}
best_valid, best_state = float("inf"), None
for epoch in range(n_epochs):
train_one_epoch(model, train_loader, optimizer)
history["train"].append(rmse(model, Xtr, ytr))
history["valid"].append(rmse(model, Xva, yva))
if history["valid"][-1] < best_valid: # 记下验证集上最好的参数(第 6 节用)
best_valid = history["valid"][-1]
best_state = copy.deepcopy(model.state_dict())
return history, best_state
def plot_history(history, title=""):
fig, ax = plt.subplots(figsize=(5.5, 3.5))
ax.plot(history["train"], label="train")
ax.plot(history["valid"], label="validation")
best = int(np.argmin(history["valid"]))
ax.axvline(best, color="gray", ls=":", label=f"best epoch ({best})")
ax.set_xlabel("epoch"); ax.set_ylabel("RMSE (logS)"); ax.set_title(title); ax.legend()
plt.tight_layout(); plt.show()
07a
07a-1
from rdkit.Chem import Descriptors
class Molecule:
def __init__(self, name, smiles):
self.name = name
self.smiles = smiles
self.mol = Chem.MolFromSmiles(smiles)
def n_heavy_atoms(self):
return self.mol.GetNumHeavyAtoms()
def n_aromatic_rings(self):
return Descriptors.NumAromaticRings(self.mol)
def describe(self):
return f"{self.name}: {self.smiles}, {self.n_heavy_atoms()} heavy atoms"
for m in [Molecule("thiophene", "c1ccsc1"), Molecule("pentacene", "c1ccc2cc3cc4cc5ccccc5cc4cc3cc2c1")]:
print(m.name, "芳香环数:", m.n_aromatic_rings())
💡 实际写代码时,更好的做法是修改原来的类,而不是重新写一遍。这里重写只是为了让答案能单独运行。
07a-2
class FlexibleMLP(nn.Module):
"""和 SolubilityMLP 一样,只是激活函数可以换"""
def __init__(self, n_features, hidden_size=64, activation=nn.ReLU):
super().__init__()
self.net = nn.Sequential(
nn.Linear(n_features, hidden_size), activation(),
nn.Linear(hidden_size, hidden_size), activation(),
nn.Linear(hidden_size, 1),
)
def forward(self, x):
return self.net(x).squeeze(1)
for activation in [nn.ReLU, nn.Tanh]:
set_seed(0)
model = FlexibleMLP(17, activation=activation)
history, best_state = fit(model, n_epochs=100)
print(f"{activation.__name__:5s}: 最后一轮测试 RMSE = {rmse(model, Xte, yte):.2f}", end="")
model.load_state_dict(best_state)
print(f", 早停后测试 RMSE = {rmse(model, Xte, yte):.2f}")
📘 Tanh 和 ReLU 的结果差不多(1.17–1.23 之间)。这么浅的网络,激活函数的选择影响不大。
🤔 注意 ReLU 那一行:早停后的测试 RMSE(≈1.23)反而比最后一轮(≈1.19)更差。早停不是保证变好吗?
📘 早停选的是验证集上最好的一轮。验证集只有 759 个分子,噪声很大(07a 第 6.2 节),"验证集最好"的那一轮在测试集上不一定最好。这类 0.0x 的差别不要过度解读。网络很深时,ReLU 的优势才明显:tanh 和 sigmoid 在两端很"平",导数接近 0,梯度一层层乘下去会越来越小(梯度消失),前面的层几乎学不动。
注意 activation=nn.ReLU 传的是类,在 __init__ 里用 activation() 才造出实例。
07a-3
from sklearn.metrics import roc_auc_score
y_cls_train, y_cls_valid, y_cls_test = (to_tensor((a < -4).astype(float)) for a in (y_train, y_valid, y_test))
cls_loader = DataLoader(TensorDataset(Xtr, y_cls_train), batch_size=64, shuffle=True)
bce = nn.BCEWithLogitsLoss()
def predict_proba(model, X):
model.eval()
with torch.no_grad():
return torch.sigmoid(model(X)).numpy()
set_seed(0)
clf = SolubilityMLP(n_features=17)
optimizer = torch.optim.Adam(clf.parameters(), lr=1e-3)
best_auc, best_state = 0.0, None
for epoch in range(50):
clf.train()
for xb, yb in cls_loader:
loss = bce(clf(xb), yb)
optimizer.zero_grad(); loss.backward(); optimizer.step()
valid_auc = roc_auc_score(y_cls_valid.numpy(), predict_proba(clf, Xva))
if valid_auc > best_auc: # 早停:用验证集 AUC 选最好的一轮
best_auc, best_state = valid_auc, copy.deepcopy(clf.state_dict())
clf.load_state_dict(best_state)
print(f"验证集最好 AUC = {best_auc:.3f}")
print(f"MLP 测试 ROC-AUC = {roc_auc_score(y_cls_test.numpy(), predict_proba(clf, Xte)):.3f} (02c 随机森林: 0.953)")
📘 MLP 的测试 ROC-AUC ≈ 0.94,比随机森林(0.953)略低。和回归一样:同样的 17 个特征,换成神经网络并不会更好。
⚠️ 这里的测试集和 02c 不完全一样:02c 用了 stratify=y 分层划分,这里沿用 07a 的回归划分。两者大致可比,但不是严格的同一批分子。
10a
先把 10a 的分子图、模型和训练函数准备好:
thiophene = Chem.MolFromSmiles("c1ccsc1")
bithiophene = Chem.MolFromSmiles("s1cccc1-c1cccs1")
ELEMENTS = ["C", "N", "O", "S", "F", "Cl", "Br", "I", "P"]
HYBRIDIZATIONS = [Chem.HybridizationType.SP, Chem.HybridizationType.SP2, Chem.HybridizationType.SP3]
def one_hot(value, choices):
"""value 在 choices 里的位置记 1;不在列表里就把最后一位"其他"记 1"""
return [float(value == c) for c in choices] + [float(value not in choices)]
def atom_features(atom):
return (one_hot(atom.GetSymbol(), ELEMENTS)
+ one_hot(atom.GetDegree(), [0, 1, 2, 3, 4])
+ one_hot(atom.GetTotalNumHs(), [0, 1, 2, 3])
+ one_hot(atom.GetFormalCharge(), [-1, 0, 1])
+ one_hot(atom.GetHybridization(), HYBRIDIZATIONS)
+ [float(atom.GetIsAromatic()), float(atom.IsInRing())])
for atom in thiophene.GetAtoms():
print(atom.GetIdx(), atom.GetSymbol(), atom_features(atom))
print("每个原子的特征数:", len(atom_features(thiophene.GetAtomWithIdx(0))))
BOND_TYPES = [Chem.BondType.SINGLE, Chem.BondType.DOUBLE, Chem.BondType.TRIPLE, Chem.BondType.AROMATIC]
def bond_features(bond):
return ([float(bond.GetBondType() == t) for t in BOND_TYPES]
+ [float(bond.GetIsConjugated()), float(bond.IsInRing())])
for bond in thiophene.GetBonds():
print(f"键 {bond.GetIdx()}: 原子 {bond.GetBeginAtomIdx()}-{bond.GetEndAtomIdx()}, {bond.GetBondType()}, 特征 {bond_features(bond)}")
N_ATOM_FEATURES = len(atom_features(thiophene.GetAtomWithIdx(0)))
N_BOND_FEATURES = len(bond_features(thiophene.GetBondWithIdx(0)))
def mol_to_graph(mol):
x = torch.tensor([atom_features(a) for a in mol.GetAtoms()], dtype=torch.float32)
src, dst, edge_attr = [], [], []
for bond in mol.GetBonds():
i, j = bond.GetBeginAtomIdx(), bond.GetEndAtomIdx()
f = bond_features(bond)
src += [i, j]; dst += [j, i]; edge_attr += [f, f]
return {
"x": x, # (原子数, 31)
"edge_index": torch.tensor([src, dst], dtype=torch.long).reshape(2, -1), # (2, 2×键数)
"edge_attr": torch.tensor(edge_attr, dtype=torch.float32).reshape(-1, N_BOND_FEATURES), # (2×键数, 6)
}
g = mol_to_graph(thiophene)
{k: tuple(v.shape) for k, v in g.items()}
class MessagePassingLayer(nn.Module):
def __init__(self, hidden_size, n_bond_features):
super().__init__()
self.message = nn.Linear(hidden_size + n_bond_features, hidden_size) # M:邻居状态 + 键特征 -> 消息
self.update = nn.Linear(2 * hidden_size, hidden_size) # U:自己的状态 + 收到的消息 -> 新状态
def forward(self, h, edge_index, edge_attr):
src, dst = edge_index
# 1. 发送消息:每条边 src -> dst 生成一条消息
messages = torch.relu(self.message(torch.cat([h[src], edge_attr], dim=1)))
# 2. 聚合:把消息加到终点原子上
aggregated = torch.zeros_like(h).index_add_(0, dst, messages)
# 3. 更新
return torch.relu(self.update(torch.cat([h, aggregated], dim=1)))
def collate(graphs):
xs, edge_indices, edge_attrs, batch = [], [], [], []
offset = 0
for k, g in enumerate(graphs):
n_atoms = g["x"].shape[0]
xs.append(g["x"])
edge_indices.append(g["edge_index"] + offset) # 原子编号整体平移
edge_attrs.append(g["edge_attr"])
batch.append(torch.full((n_atoms,), k)) # 这些原子属于第 k 个分子
offset += n_atoms
return {"x": torch.cat(xs), "edge_index": torch.cat(edge_indices, dim=1),
"edge_attr": torch.cat(edge_attrs), "batch": torch.cat(batch), "num_graphs": len(graphs)}
demo = collate([mol_to_graph(thiophene), mol_to_graph(bithiophene)])
print("原子总数:", demo["x"].shape[0], "(5 + 10)")
print("batch 向量:", demo["batch"].tolist())
class SolubilityGNN(nn.Module):
def __init__(self, hidden_size=64, n_layers=3, readout="sum"):
super().__init__()
self.readout = readout
self.embed = nn.Linear(N_ATOM_FEATURES, hidden_size)
self.layers = nn.ModuleList([MessagePassingLayer(hidden_size, N_BOND_FEATURES) for _ in range(n_layers)])
self.head = nn.Sequential(nn.Linear(hidden_size, hidden_size), nn.ReLU(), nn.Linear(hidden_size, 1))
def forward(self, g):
h = torch.relu(self.embed(g["x"]))
for layer in self.layers:
h = layer(h, g["edge_index"], g["edge_attr"])
# 读出:按 batch 向量把原子加回各自的分子
h_graph = torch.zeros(g["num_graphs"], h.shape[1]).index_add_(0, g["batch"], h)
if self.readout == "mean":
n_atoms = torch.bincount(g["batch"], minlength=g["num_graphs"]).clamp(min=1)
h_graph = h_graph / n_atoms.unsqueeze(1)
return self.head(h_graph).squeeze(1)
set_seed(0)
gnn = SolubilityGNN()
print("参数总数:", sum(p.numel() for p in gnn.parameters()))
graphs = [mol_to_graph(m) for m in df["mol"]]
y_t = torch.tensor(y, dtype=torch.float32)
idx = np.arange(len(df))
idx_trval, idx_test = train_test_split(idx, test_size=0.2, random_state=42)
idx_train, idx_valid = train_test_split(idx_trval, test_size=0.1, random_state=42)
print("训练:", len(idx_train), " 验证:", len(idx_valid), " 测试:", len(idx_test))
print("平均每个分子的重原子数:", round(np.mean([g["x"].shape[0] for g in graphs]), 1))
def iterate_batches(indices, batch_size=64, shuffle=False):
if shuffle:
indices = np.random.permutation(indices)
for start in range(0, len(indices), batch_size):
ids = indices[start:start + batch_size]
yield collate([graphs[i] for i in ids]), y_t[ids]
def predict(model, indices):
model.eval()
with torch.no_grad():
return torch.cat([model(g) for g, _ in iterate_batches(indices, batch_size=512)])
def rmse(model, indices):
return torch.sqrt(loss_fn(predict(model, indices), y_t[indices])).item()
def fit(model, n_epochs=40, lr=1e-3):
optimizer = torch.optim.Adam(model.parameters(), lr=lr)
history = {"train": [], "valid": []}
best_valid, best_state = float("inf"), None
for epoch in range(n_epochs):
model.train()
total, n = 0.0, 0
for g, yb in iterate_batches(idx_train, shuffle=True):
loss = loss_fn(model(g), yb)
optimizer.zero_grad(); loss.backward(); optimizer.step()
total += loss.item() * len(yb); n += len(yb)
history["train"].append((total / n) ** 0.5) # 训练误差:这一轮各小批的平均,省得再算一遍
history["valid"].append(rmse(model, idx_valid))
if history["valid"][-1] < best_valid:
best_valid, best_state = history["valid"][-1], copy.deepcopy(model.state_dict())
if epoch % 10 == 9:
print(f"epoch {epoch + 1:3d}: 训练 RMSE {history['train'][-1]:.2f}, 验证 RMSE {history['valid'][-1]:.2f}")
model.load_state_dict(best_state) # 早停:装回验证集上最好的参数
return history
10a-1
btbt = Chem.MolFromSmiles("c1ccc2c(c1)sc1c3ccccc3sc21")
g = mol_to_graph(btbt)
print({k: tuple(v.shape) for k, v in g.items()})
print("重原子数:", btbt.GetNumAtoms(), " 键数:", btbt.GetNumBonds())
is_carbon = g["x"][:, ELEMENTS.index("C")] == 1
is_aromatic, in_ring = g["x"][:, -2] == 1, g["x"][:, -1] == 1
print("在环上的芳香碳:", int((is_carbon & is_aromatic & in_ring).sum()))
📘 BTBT 是 C₁₄H₈S₂:14 个碳 + 2 个硫 = 16 个重原子。四个稠合的环:两个苯环各 6 根键、两个噻吩环各 5 根键,共 22 根,但三处稠合各有一根键被两个环共用,所以键数 = 22 - 3 = 19。edge_index 每根键正反各一列,共 38 列。
16 个原子全都在环上、全都是芳香的,其中 14 个是碳。
10a-2
layer_results = {}
for n_layers in [1, 5]:
set_seed(0)
model = SolubilityGNN(n_layers=n_layers)
fit(model, n_epochs=40)
layer_results[n_layers] = rmse(model, idx_test)
print(f"n_layers = {n_layers}: 测试 RMSE = {layer_results[n_layers]:.2f}")
print("(对照:n_layers = 3,60 轮,测试 RMSE ≈ 1.04)")
📘 结果(40 轮):1 层 ≈ 1.12,5 层 ≈ 1.03。正文 3 层训练 60 轮是 ≈ 1.04。
- 1 层的 GNN 每个原子只看得到直接相连的邻居,相当于半径为 1 的"可学习指纹"。即便如此,它已经和 02a 的"描述符 + 计数指纹"随机森林(1.11)差不多了。
- 5 层看得更远,只训练 40 轮就和 3 层训练 60 轮的结果相当,略好一点。对这个数据集,层数从 3 加到 5 还没出现过平滑。
1 层到 3 层的提升(约 0.08)比 3 层到 5 层(约 0.01)大得多:对溶解度来说,大部分有用的信息就在每个原子周围两三根键的范围内。
比较时注意:这里只训练了 40 轮,而 10a 正文的 3 层模型训练了 60 轮。严格比较应该用相同的轮数,最好再换几个随机种子取平均(02b 第 1 节)。
10a-3
set_seed(0)
gnn_sum = SolubilityGNN(readout="sum")
fit(gnn_sum, n_epochs=60)
set_seed(0)
gnn_mean = SolubilityGNN(readout="mean")
fit(gnn_mean, n_epochs=60)
print(f"求和读出: 测试 RMSE = {rmse(gnn_sum, idx_test):.2f}")
print(f"平均读出: 测试 RMSE = {rmse(gnn_mean, idx_test):.2f}")
acenes = ["c1ccccc1", "c1ccc2ccccc2c1", "c1ccc2cc3ccccc3cc2c1",
"c1ccc2cc3cc4ccccc4cc3cc2c1", "c1ccc2cc3cc4cc5ccccc5cc4cc3cc2c1"]
def gnn_predict_smiles(model, smiles_list):
model.eval()
with torch.no_grad():
return model(collate([mol_to_graph(Chem.MolFromSmiles(s)) for s in smiles_list])).numpy()
pd.DataFrame({
"molecule": ["benzene", "naphthalene", "anthracene", "tetracene", "pentacene"],
"measured": [-1.64, -4.31, -6.44, -8.60, np.nan],
"GNN, sum readout": gnn_predict_smiles(gnn_sum, acenes),
"GNN, mean readout": gnn_predict_smiles(gnn_mean, acenes),
}).round(2)
📘 结果:
- 平均读出的测试 RMSE ≈ 1.26,比求和读出(≈1.04)差了很多,甚至不如 17 个描述符的随机森林(1.17)。
- 出乎意料的是,并苯系列的趋势还在,并五苯也比并四苯预测得更难溶(约 -7.2 vs -6.4)。但整个系列都比求和读出预测得更"好溶"(高出 0.5–0.8),离实验值更远。
🤔 平均读出把"分子有多大"的信息除掉了,为什么还能分出并四苯和并五苯?
📘 因为经过消息传递,每个原子的向量已经编码了它的局部环境,而不同大小的并苯里,各种环境的比例不一样。比如稠合位置的碳(连 3 个碳、没有氢):苯 0/6,萘 2/10,蒽 4/14,并四苯 6/18,并五苯 8/22。比例在变,平均值就在变,模型可以从比例间接"猜"出大小。
但这种线索很脆弱:比例的变化越来越慢(0.33 → 0.36),而且很多分子根本没有这样的规律。比如烷基链,C8 和 C12 的链里几乎全是 CH₂,平均下来几乎一样,可溶解度差了好几个数量级。这就是平均读出整体变差的原因。
读出方式也是一种归纳偏置:广延性质(随分子变大而累加,比如 logP、分子量、溶解度的对数)适合求和;强度性质(不随大小累加,比如某些电子性质)可能更适合平均。
💡 set_seed 里的 torch.use_deterministic_algorithms(True) 很重要:没有它,index_add_ 在多线程 CPU 上做浮点加法的顺序不固定,同样的代码和种子每次结果略有不同,训练 60 轮后会被放大。我们试过,不加这一行时平均读出的测试 RMSE 两次分别是 1.15 和 1.24。同一个模型、同一份数据,仅仅因为加法顺序不同,结果就能差 0.09,这比 02b 里调参带来的提升还大。
10b
下面两个练习各要训练一次 chemprop(每次约 2–3 分钟)。先把 10b 的数据文件和划分文件准备好:
try:
import chemprop
except ImportError:
%pip install -q chemprop
import chemprop
import os, json
os.environ["PYTHONIOENCODING"] = "utf-8"
os.makedirs("chemprop_data", exist_ok=True)
SPLITS_JSON = "chemprop_data/splits.json"
with open(SPLITS_JSON, "w") as f:
json.dump([{"train": idx_train.tolist(), "val": idx_valid.tolist(), "test": idx_test.tolist()}], f)
def show_log(path, keyword="test/"):
lines = open(path, encoding="utf-8", errors="replace").read().splitlines()
hits = [line for line in lines if keyword in line]
print("\n".join(hits) if hits else "\n".join(lines[-20:]))
10b-1
CLS_CSV = "chemprop_data/insoluble.csv"
df.assign(insoluble=(df["Solubility"] < -4).astype(int))[["SMILES", "insoluble"]].to_csv(CLS_CSV, index=False)
!chemprop train -i {CLS_CSV} -s SMILES --target-columns insoluble --task-type classification --splits-file {SPLITS_JSON} --epochs 30 --pytorch-seed 0 --metrics roc prc accuracy -o chemprop_runs/insoluble > chemprop_data/train_cls.log 2>&1
show_log("chemprop_data/train_cls.log")
📘 chemprop 的测试 ROC-AUC ≈ 0.944,准确率 ≈ 0.90,和 02c 的随机森林(ROC-AUC 0.953,准确率 0.891)基本持平,AUC 还略低一点。
回归任务上 GNN 明显更好,分类任务上却没有优势。一个原因是:分类只需要分清 logS 在 -4 的哪一边,远离 -4 的分子用简单的特征(logP、大小)就能判断对,难的只有边界附近那一小部分,留给"更好的特征"发挥的空间不多。另外 chemprop 只训练了 30 轮,也没有调参。
(和 07a-3 一样,这里的测试集用的是回归的划分,不是 02c 的分层划分。)
10b-2
SOL_CSV = "chemprop_data/solubility_clean.csv"
df[["SMILES", "Solubility"]].to_csv(SOL_CSV, index=False)
!chemprop train -i {SOL_CSV} -s SMILES --target-columns Solubility --task-type regression --split-type SCAFFOLD_BALANCED --split-sizes 0.8 0.1 0.1 --epochs 30 --pytorch-seed 0 --metrics rmse mae r2 -o chemprop_runs/scaffold > chemprop_data/train_scaffold.log 2>&1
show_log("chemprop_data/train_scaffold.log")
📘 scaffold split 的测试 RMSE ≈ 1.05,和随机划分(≈1.05)几乎一样;R² 从 0.81 降到约 0.76,那是因为两个测试集里 logS 的分布不同(R² 依赖测试集本身的方差),不是模型变差了。02b 里随机森林也只差了 0.03(1.17 → 1.20)。
原因和 02b 第 6 节说的相同:AqSolDB 里约 30% 的分子没有环(scaffold 是空的,全挤在一组),18% 只是一个苯环,"新骨架"的分子并不比随机抽的更"陌生"。
另外两次划分的测试集不是同一批分子,测试集大小也不同(这里是 10%,随机划分是 20%),0.0x 的差别不必过度解读。