习题答案 第四讲基础习题参考答案
先自己做一遍,再看答案。
直接阅读答案的学习效果远低于独立实现。建议至少尝试 20 分钟,卡住时先看习题里的 💡 提示,再展开本页。
展开状态只在当前浏览器标签页有效,关闭标签页后会重新折叠。
本 notebook 提供 04c_exercises.ipynb 中 8 道基础巩固习题的完整参考代码与结果说明。
In [1] · Python
import warnings
warnings.filterwarnings("ignore")
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy.stats import norm
from sklearn.gaussian_process import GaussianProcessRegressor
from sklearn.gaussian_process.kernels import RBF, ConstantKernel as C, WhiteKernel
from sklearn.preprocessing import OneHotEncoder
%matplotlib inline
plt.rcParams["figure.dpi"] = 110
📘 课程统一绘图风格:下面这格加载课程自带的
ai4m.mplstyle(配色与课程网站同源,无上右边框,仅横向浅网格,保存默认 300 dpi)。C是课程配色,手动指定颜色时写color=C.crimson。
In [2] · Python
# 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,返回课程配色
第一部分:高斯过程回归(GPR)与不确定性估计
习题 1:手工计算一维 RBF 核矩阵
In [3] · Python
x = np.array([100.0, 120.0, 200.0])
l = 30.0
diff = x[:, None] - x[None, :]
K = np.exp(-0.5 * (diff ** 2) / (l ** 2))
print("3x3 RBF Kernel Matrix K:")
print(np.round(K, 4))
print(f"\nk(100, 120) = {K[0, 1]:.4f} (距离较近,协方差较高)")
print(f"k(100, 200) = {K[0, 2]:.4f} (距离超过 3 倍长度尺度,协方差接近 0)")
习题 2:拟合高斯过程回归并输出预测均值与标准差
In [4] · Python
X_train = np.array([0.0, 1.2, 2.5, 5.5, 6.0]).reshape(-1, 1)
y_train = np.sin(X_train).ravel()
X_grid = np.linspace(0.0, 6.0, 200).reshape(-1, 1)
kernel = C(1.0) * RBF(length_scale=1.0)
gp = GaussianProcessRegressor(kernel=kernel, alpha=1e-6, n_restarts_optimizer=5, random_state=42)
gp.fit(X_train, y_train)
mu, sigma = gp.predict(X_grid, return_std=True)
x_probe = np.array([[1.2], [4.0]])
mu_probe, sigma_probe = gp.predict(x_probe, return_std=True)
print("Fitted Kernel:", gp.kernel_)
print(f"x = 1.2 (观测点处): mu = {mu_probe[0]:+.4f}, sigma = {sigma_probe[0]:.4f}")
print(f"x = 4.0 (未观测空白区): mu = {mu_probe[1]:+.4f}, sigma = {sigma_probe[1]:.4f}")
习题 3:绘制 GPR 的 95% 置信区间带
In [5] · Python
fig, ax = plt.subplots(figsize=(7.5, 4.2))
ax.plot(X_grid.ravel(), np.sin(X_grid.ravel()), "k--", alpha=0.6, label="True sin(x)")
ax.plot(X_grid.ravel(), mu, color="#1f77b4", lw=2, label="GPR Mean")
ax.fill_between(
X_grid.ravel(),
mu - 1.96 * sigma,
mu + 1.96 * sigma,
color="#1f77b4",
alpha=0.22,
label="95% Confidence Interval",
)
ax.scatter(X_train.ravel(), y_train, color="#d62728", s=55, zorder=5, label="Observed Data")
ax.set_xlabel("x")
ax.set_ylabel("y")
ax.set_title("Gaussian Process Regression with 95% Confidence Band")
ax.legend(loc="lower left")
plt.tight_layout()
plt.show()
习题 4:用 WhiteKernel 自动估计实验测量噪声
In [6] · Python
rng = np.random.RandomState(42)
X_noisy = np.linspace(0, 6, 25).reshape(-1, 1)
y_noisy = np.sin(X_noisy).ravel() + rng.normal(0, 0.15, size=len(X_noisy))
kernel_noisy = C(1.0) * RBF(length_scale=1.0) + WhiteKernel(noise_level=0.05)
gp_noisy = GaussianProcessRegressor(kernel=kernel_noisy, n_restarts_optimizer=10, random_state=42)
gp_noisy.fit(X_noisy, y_noisy)
learned_noise_var = gp_noisy.kernel_.k2.noise_level
print("Fitted Kernel:", gp_noisy.kernel_)
print(f"Estimated noise std: {np.sqrt(learned_noise_var):.4f} (True noise std = 0.1500)")
第二部分:采集函数与序列选点
习题 5:用上置信界(UCB)平衡利用与探索
In [7] · Python
candidates = ["Cand_A", "Cand_B", "Cand_C", "Cand_D"]
mu_cand = np.array([78.0, 74.0, 68.0, 80.0])
sigma_cand = np.array([2.0, 8.0, 12.0, 0.5])
ucb_low = mu_cand + 0.5 * sigma_cand
ucb_high = mu_cand + 2.5 * sigma_cand
for name, m, s, u1, u2 in zip(candidates, mu_cand, sigma_cand, ucb_low, ucb_high):
print(f"{name}: mu={m:4.1f}, sigma={s:4.1f} | UCB(k=0.5)={u1:5.2f} | UCB(k=2.5)={u2:5.2f}")
print(f"\nkappa = 0.5 推荐候选点: {candidates[np.argmax(ucb_low)]} (偏向利用已知高均值)")
print(f"kappa = 2.5 推荐候选点: {candidates[np.argmax(ucb_high)]} (偏向探索高不确定性区域)")
习题 6:实现期望改进(EI)并推荐下一个实验点
In [8] · Python
def true_yield(T):
return 85.0 * np.exp(-((T - 135.0) / 22.0) ** 2) + 0.08 * (T - 100.0)
T_obs = np.array([80.0, 105.0, 155.0, 175.0]).reshape(-1, 1)
y_obs = true_yield(T_obs.ravel())
T_grid = np.linspace(80.0, 180.0, 201).reshape(-1, 1)
def expected_improvement(mu, sigma, f_best, xi=0.01):
sigma = np.maximum(sigma, 1e-9)
imp = mu - f_best - xi
Z = imp / sigma
return imp * norm.cdf(Z) + sigma * norm.pdf(Z)
kernel_bo = C(50.0, (1.0, 1e4)) * RBF(length_scale=25.0, length_scale_bounds=(5.0, 100.0))
gp_bo = GaussianProcessRegressor(kernel=kernel_bo, alpha=1e-4, n_restarts_optimizer=10, random_state=42)
gp_bo.fit(T_obs, y_obs)
mu_grid, sigma_grid = gp_bo.predict(T_grid, return_std=True)
ei_grid = expected_improvement(mu_grid, sigma_grid, f_best=y_obs.max(), xi=0.01)
best_idx = int(np.argmax(ei_grid))
T_next = T_grid[best_idx, 0]
print(f"Current Best Yield: {y_obs.max():.2f}% at T = {T_obs[np.argmax(y_obs), 0]:.1f} °C")
print(f"Next Recommended Temperature by EI: T_next = {T_next:.1f} °C (True Optimum = 135.5 °C)")
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(7.5, 5.5), sharex=True, gridspec_kw={"height_ratios": [2, 1]})
ax1.plot(T_grid.ravel(), true_yield(T_grid.ravel()), "k--", alpha=0.6, label="True Yield Curve")
ax1.plot(T_grid.ravel(), mu_grid, color="#1f77b4", lw=2, label="GPR Mean")
ax1.fill_between(T_grid.ravel(), mu_grid - 1.96 * sigma_grid, mu_grid + 1.96 * sigma_grid, color="#1f77b4", alpha=0.2)
ax1.scatter(T_obs.ravel(), y_obs, color="#d62728", s=55, zorder=5, label="Observed")
ax1.set_ylabel("Yield (%)")
ax1.set_title("GPR Surrogate & Expected Improvement")
ax1.legend(loc="upper left")
ax2.plot(T_grid.ravel(), ei_grid, color="#2ca02c", lw=2, label="Expected Improvement (EI)")
ax2.axvline(T_next, color="#d62728", ls="--", label=f"Next T = {T_next:.1f} °C")
ax2.set_xlabel("Temperature (°C)")
ax2.set_ylabel("EI")
ax2.legend(loc="upper left")
plt.tight_layout()
plt.show()
第三部分:分子 Tanimoto 核与组合反应池优化
习题 7:向量化计算二元指纹的 Tanimoto 相似性核矩阵
In [9] · Python
X_fp = np.array([
[1, 1, 0, 1, 0, 0, 1, 0],
[1, 1, 0, 1, 1, 0, 0, 0],
[0, 0, 1, 0, 1, 1, 0, 1],
[1, 0, 0, 1, 0, 0, 1, 0],
], dtype=float)
def tanimoto_matrix(A, B):
dot = A @ B.T
norm_a = np.sum(A ** 2, axis=1, keepdims=True)
norm_b = np.sum(B ** 2, axis=1, keepdims=True).T
return dot / np.maximum(norm_a + norm_b - dot, 1e-12)
K_tan = tanimoto_matrix(X_fp, X_fp)
print("4x4 Tanimoto Kernel Matrix:")
print(np.round(K_tan, 3))
off_diag = K_tan.copy()
np.fill_diagonal(off_diag, -1.0)
idx_i, idx_j = np.unravel_index(np.argmax(off_diag), off_diag.shape)
print(f"\n除了自身外相似度最高的分子对: 分子 {idx_i} 与 分子 {idx_j} (Tanimoto = {K_tan[idx_i, idx_j]:.3f})")
习题 8:在 Buchwald–Hartwig 反应子集上运行 10 步贝叶斯优化
In [10] · Python
df_bh = pd.read_csv("../data/Dreher_and_Doyle_science_aar5169_rxn_results.csv")
sub_bh = df_bh.sample(n=300, random_state=42).reset_index(drop=True)
cat_cols = ["Ligand", "Additive", "Base", "Aryl halide"]
X_pool = OneHotEncoder(sparse_output=False).fit_transform(sub_bh[cat_cols])
y_pool = sub_bh["Yield"].values
rng = np.random.RandomState(7)
init_indices = rng.choice(len(y_pool), size=5, replace=False).tolist()
# 1. BO (GPR + EI)
chosen_bo = list(init_indices)
best_bo = [y_pool[chosen_bo].max()]
for step in range(10):
rem = [i for i in range(len(y_pool)) if i not in chosen_bo]
gp_rxn = GaussianProcessRegressor(
kernel=C(500.0, (10.0, 1e4)) * RBF(length_scale=2.0, length_scale_bounds=(0.1, 20.0)) + WhiteKernel(10.0),
random_state=42,
)
gp_rxn.fit(X_pool[chosen_bo], y_pool[chosen_bo])
mu_r, std_r = gp_rxn.predict(X_pool[rem], return_std=True)
ei_r = expected_improvement(mu_r, std_r, f_best=y_pool[chosen_bo].max(), xi=0.5)
next_idx = rem[int(np.argmax(ei_r))]
chosen_bo.append(next_idx)
best_bo.append(y_pool[chosen_bo].max())
# 2. Random Search baseline
chosen_rand = list(init_indices)
best_rand = [y_pool[chosen_rand].max()]
for step in range(10):
rem = [i for i in range(len(y_pool)) if i not in chosen_rand]
next_idx = int(rng.choice(rem))
chosen_rand.append(next_idx)
best_rand.append(y_pool[chosen_rand].max())
print(f"Pool Global Max Yield: {y_pool.max():.2f}%")
print(f"Initial 5-point Max Yield: {best_bo[0]:.2f}%")
print(f"After +10 steps BO Best: {best_bo[-1]:.2f}%")
print(f"After +10 steps Rand Best: {best_rand[-1]:.2f}%")
fig, ax = plt.subplots(figsize=(7.0, 4.2))
steps = np.arange(0, 11)
ax.plot(steps, best_bo, "o-", color="#d62728", lw=2, label="Bayesian Optimization (EI)")
ax.plot(steps, best_rand, "s--", color="#7f7f7f", lw=1.8, label="Random Search")
ax.axhline(y_pool.max(), color="k", ls=":", alpha=0.6, label=f"Pool Max ({y_pool.max():.1f}%)")
ax.set_xlabel("Optimization Step (after 5 initial points)")
ax.set_ylabel("Best Observed Yield (%)")
ax.set_title("Buchwald-Hartwig Reaction Subset (N=300): BO vs. Random Search")
ax.legend(loc="lower right")
plt.tight_layout()
plt.show()