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

习题 03d — 第三讲基础习题:PCA 降维、聚类与化学空间巩固练习

习题文件:03d_exercises.ipynb(13.9 KB)

Open In Colab

03d — 第三讲基础习题:PCA 降维、聚类与化学空间巩固练习

本套习题帮助你一步步巩固第三讲(03a–03c)中降维可视化、聚类分析与化学空间近邻检索的核心代码操作。每道题只需填写 2–6 行代码,并附有预期输出提示供你自查。完成后可对照 solutions/03_exercises_solutions.ipynb 查看完整解答。

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, "03 - Unsupervised Learning"))
    get_ipython().run_line_magic("pip", "install -q rdkit")

0. 公共环境与分子特征准备

为了保证每道习题都能在 1 秒内快速运行完毕,我们从 data/solubility.csv(AqSolDB)中固定抽取前 1,000 个分子作为练习子集 df_sub,并提取其 17 个物理化学描述符矩阵 X_raw。

In [2] · Python
import os
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from rdkit import Chem, DataStructs, RDLogger
from rdkit.Chem import Descriptors, Draw, rdFingerprintGenerator
from rdkit.ML.Cluster import Butina

RDLogger.DisableLog("rdApp.*")
plt.rcParams["figure.dpi"] = 110

for p in ["data/solubility.csv", "../data/solubility.csv", "solubility.csv"]:
    if os.path.exists(p):
        df = pd.read_csv(p)
        break

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",
]

df_sub = df.iloc[:1000].copy().reset_index(drop=True)
X_raw = df_sub[feature_cols]
y_sub = df_sub["Solubility"].values
print(f"成功准备练习子集 df_sub: {X_raw.shape}")

📘 课程统一绘图风格:下面这格加载课程自带的 ai4m.mplstyle(配色与课程网站同源,无上右边框,仅横向浅网格,保存默认 300 dpi)。C 是课程配色,手动指定颜色时写 color=C.crimson。

In [3] · 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,返回课程配色

第一部分:主成分分析(PCA)与新分子投影(对应 03a)

🏋️ 习题 1:特征标准化与 PCA 解释方差比

  1. 使用 StandardScaler() 对 X_raw 进行标准化,得到 X_scaled;
  2. 在 X_scaled 上拟合 PCA()(保留全部主成分),打印前 3 个主成分各自的解释方差比(pca.explained_variance_ratio_[:3])以及前 3 个主成分的累计解释方差比。
  • 预期输出:前 3 个主成分约 [0.501, 0.163, 0.088],累计解释方差比约 0.752
In [4] · Python
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA

# 在下方填写你的代码:

🏋️ 习题 2:找出对 PC1 和 PC2 贡献最大的前 3 个描述符

主成分载荷矩阵存储在 pca.components_ 中(第 0 行对应 PC1,第 1 行对应 PC2)。

  1. 将 pca.components_[:2].T 封装为以 feature_cols 为行索引、列名为 ["PC1", "PC2"] 的 DataFrame loadings;
  2. 分别打印 loadings["PC1"].abs().nlargest(3) 和 loadings["PC2"].abs().nlargest(3),查看主导前两个主轴的物理化学量。
In [5] · Python
# 在下方填写你的代码:

🏋️ 习题 3:绘制二维 PCA 散点图并将新分子投影上去

下方代码已为你算好阿司匹林(aspirin)和并五苯(pentacene)两个新分子的 17 个描述符 DataFrame new_mols_df。

  1. 用习题 1 中已经拟合好的 scaler 和 pca(切勿重新 fit!),依次调用 scaler.transform 和 pca.transform 计算这两个新分子的主成分坐标 new_pcs;
  2. 将背景数据集 pcs[:, 0], pcs[:, 1] 画成浅灰色散点,把两个新分子画成红色五角星(marker="*", s=180, color="red")。
In [6] · Python
new_smiles = {
    "aspirin":   "CC(=O)Oc1ccccc1C(=O)O",
    "pentacene": "c1ccc2cc3cc4cc5ccccc5cc4cc3cc2c1",
}
new_mols_df = pd.DataFrame(
    [[getattr(Descriptors, col)(Chem.MolFromSmiles(s)) for col in feature_cols] for s in new_smiles.values()],
    columns=feature_cols,
    index=list(new_smiles.keys()),
)

# 在下方填写你的投影与绘图代码:

第二部分:K-means、轮廓系数与 Butina 分子聚类(对应 03b)

🏋️ 习题 4:运行 K-means 并统计各簇分子数与平均溶解度

  1. 在标准化特征 X_scaled 上运行 KMeans(n_clusters=3, n_init=10, random_state=42),将预测出的簇标签存入 df_sub["cluster"];
  2. 使用 df_sub.groupby("cluster")[["MolWt", "MolLogP", "Solubility"]].agg(["count", "mean"]) 查看这 3 个簇的分子数量以及平均分子量、平均 \(\log P\) 和平均溶解度。
In [7] · Python
from sklearn.cluster import KMeans

# 在下方填写你的代码:

🏋️ 习题 5:计算不同簇数 \(k\) 下的轮廓系数(Silhouette Score)

遍历 k 从 2 到 6,每次在 X_scaled 上拟合 KMeans(n_clusters=k, n_init=10, random_state=42),调用 silhouette_score(X_scaled, km.labels_) 计算轮廓系数并打印,找出轮廓系数最高的 k。

  • 预期输出:k=2 时轮廓系数最高(约 0.335)
In [8] · Python
from sklearn.metrics import silhouette_score

# 在下方填写你的代码:

🏋️ 习题 6:使用 RDKit Taylor-Butina 算法对分子指纹聚类

下方代码已为你计算好前 300 个分子的 Morgan 指纹列表 fps_300 以及两两 Tanimoto 距离下三角数组 dists_300。

  1. 调用 Butina.ClusterData(dists_300, len(fps_300), cutoff, isDistData=True)(设距离阈值 cutoff = 0.5,即要求相似度 \(\ge 0.5\))得到聚类结果元组 clusters;
  2. 打印生成的总簇数 len(clusters),以及最大簇(clusters[0])包含的分子个数,并用 Draw.MolsToGridImage 画出最大簇的前 4 个分子。
  • 预期输出:共生成 207 个簇,第 1 大簇包含 12 个分子。
In [9] · Python
fp_gen = rdFingerprintGenerator.GetMorganGenerator(radius=2, fpSize=2048)
mols_300 = df_sub["mol"].iloc[:300].tolist()
fps_300 = [fp_gen.GetFingerprint(m) for m in mols_300]

dists_300 = []
for i in range(1, len(fps_300)):
    sims = DataStructs.BulkTanimotoSimilarity(fps_300[i], fps_300[:i])
    dists_300.extend(1.0 - np.array(sims))

# 在下方填写你的 Butina 聚类与可视化代码:

第三部分:按簇交叉验证与膦配体近邻查找(对应 03b & 03c)

🏋️ 习题 7:对比普通 KFold 与按簇分组 GroupKFold 的回归误差

我们先用 KMeans(n_clusters=10, n_init=10, random_state=42) 将 X_scaled 分成 10 个簇,簇编号记为 groups。 请使用 cross_val_score(评分标准 scoring="neg_root_mean_squared_error")分别计算 RandomForestRegressor(n_estimators=50, random_state=42) 在以下两种 5 折划分下的平均测试 RMSE:

  1. 普通随机 5 折:cv=KFold(n_splits=5, shuffle=True, random_state=42);
  2. 按簇分组 5 折:cv=list(GroupKFold(n_splits=5).split(X_raw, y_sub, groups))。
  • 预期输出:Random 5-Fold RMSE = 0.870 | Cluster 5-Fold RMSE = 1.119
In [10] · Python
from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import KFold, GroupKFold, cross_val_score

groups = KMeans(n_clusters=10, n_init=10, random_state=42).fit_predict(X_scaled)
rf = RandomForestRegressor(n_estimators=50, random_state=42, n_jobs=-1)

# 在下方填写你的代码:

🏋️ 习题 8:在 LKB-P 膦配体数据库中查找 16 号正例配体的最近邻

下方代码已读入 03c 的 LKB_P.csv(以配体编号 No. 为行索引),并将 28 个 DFT 描述符标准化为 DataFrame X_lkb。 请计算所有配体到 16 号正例配体(X_lkb.loc[16]) 的欧氏距离:

  1. 使用 dists = np.linalg.norm(X_lkb.values - X_lkb.loc[16].values, axis=1) 计算距离,并封装成以 X_lkb.index 为索引的 pd.Series;
  2. 找出距离最小的前 6 个配体编号(包含 16 号自身),打印它们的距离以及在 ligands 表中的 Type 和 He8_steric。
  • 预期输出:除 16 号自身(距离 0.0)外,最近的配体编号依次为 116, 17, 15, 53, 54(注意其中 54 号恰好也是论文的 4 个已知正例之一!)。
In [11] · Python
for p in ["data/LKB_P.csv", "../data/LKB_P.csv", "LKB_P.csv"]:
    if os.path.exists(p):
        ligands = pd.read_csv(p, sep=";", index_col=0)
        break

drop_cols = ["Type", "PC1", "PC2", "PC3", "PC4"]
X_lkb = pd.DataFrame(
    StandardScaler().fit_transform(ligands.drop(columns=drop_cols)),
    index=ligands.index,
)

# 在下方填写你的代码:
返回模块 03 全部习题汇总