AI for Materials Science · Lecture 05 (Complete Beginner-to-Research Edition)
Feature Engineering, Explainable AI & 3D Molecular Informatics:
Feature Selection, SHAP Attribution & PubChem Physical Data
Zesheng Liu
Laboratory of Organic Electronics, Linköping University
Modules 05a–05b | AqSolDB 29-Descriptor Matrix, SHAP Game Theory, ETKDGv3 Conformers & Yalkowsky Tm
Lecture 05 roadmap: from feature pruning to physical data
Three pillars connecting tabular ML interpretability to 3D geometry and chemical databases (05a–05b)
PART 1 · MODULE 05a
Feature Selection & Pipelines
Filtering quasi-constant and collinear descriptors (|r| > 0.90), Recursive Feature Elimination (RFE), and preventing catastrophic selection leakage inside Pipeline.
PART 2 · MODULE 05a
Explainable AI with SHAP
Shapley values from cooperative game theory, fast exact TreeExplainer, global beeswarm vs. local waterfall plots, and why MDI & Permutation diverge under collinearity.
PART 3 · MODULE 05b
3D Conformers & PubChem API
ETKDGv3 distance geometry, MMFF94 conformer ensembles & Boltzmann weights, an honest test of 3D descriptors, and fetching experimental Tm to close the Yalkowsky cliffhanger.
Better materials ML rarely comes from blindly adding 200 descriptors—it comes from pruning noise, auditing attributions with SHAP, and injecting missing physics.
Computable descriptors ≠ useful descriptors
RDKit can compute 200+ descriptors in milliseconds—why throwing all of them into a model backfires
THE CURSE OF REDUNDANCY
Why "More Features" Hurts
- Quasi-constant noise: e.g.,
NumRadicalElectrons is 0 for >99% of closed-shell molecules.
- Severe collinearity:
MolWt, HeavyAtomMolWt, ExactMolWt, LabuteASA, and MolMR all correlate at r > 0.95.
- Broken interpretation: Correlated twins split importance scores and destabilize linear weights.
THREE SELECTION FAMILIES
Filter · Wrapper · Embedded
- Filter (model-free): Variance threshold & correlation pruning—fast, deterministic, first pass.
- Wrapper (RFE / RFECV): Iteratively train & drop weakest feature—captures feature interactions.
- Embedded (Lasso / RF / XGB): Regularization or tree splits select features during training.
Start with fast model-free filtering (variance + collinearity), then refine with wrapper/embedded selection—always guided by domain meaning.
Filter route: removing zero-variance & collinear twins
Inspecting 29 RDKit descriptors on AqSolDB reveals a massive size-proxy cluster with |r| > 0.90
Dropping quasi-constant features and pruning |r| > 0.90 clusters immediately removes redundant mass/volume copies without touching labels.
Three-way benchmark: 29 → 10 descriptors with no accuracy loss
Comparing full 29 features against Filter, RFE wrapper, and Embedded top-10 on the AqSolDB test set
Cutting two-thirds of the descriptors leaves test RMSE virtually unchanged—proving most extra features were redundant noise.
Critical pitfall: feature selection MUST live inside Pipeline
Selecting top features on the full dataset before CV leaks validation labels—creating fake R2 ≈ 0.5 on pure noise!
Any supervised step (scaling, correlation screening, RFE) must be fit exclusively inside each training fold via sklearn.pipeline.Pipeline.
Shapley values: fair credit assignment from game theory
Moving from global 'which feature matters on average?' to local 'why did the model predict logS = −6.2 for THIS molecule?'
1
f(x) = φ0 + Σj=1..p φj(x)
Efficiency axiom: Individual feature attributions sum exactly to prediction minus dataset mean φ0.
2
φj = Avg over subsets S [ f(S ∪ {j}) − f(S) ]
Average marginal contribution of feature j across all possible feature coalitions.
3
explainer = shap.TreeExplainer(rf_model)
Exact polynomial-time algorithm for Random Forests & XGBoost (milliseconds instead of 2p).
WHY CHEMISTS LOVE SHAP
Signed & Instance-Specific
- Directionality: Not just "
MolLogP is important", but "high MolLogP pushes logS down".
- Local auditing: Diagnose individual outliers or failed organic semiconductor predictions.
- Physical sanity check: Verify the model learned H-bonding & hydrophobicity rather than dataset artifacts.
SHAP decomposes every single molecule's prediction into an exact sum of signed physical contributions starting from the dataset baseline.
Global SHAP beeswarm: magnitude + physical sign at a glance
Every dot is one test molecule; color encodes feature value (low = blue, high = red), x-axis encodes impact on logS
SHAP automatically recovers chemical intuition: higher MolLogP and aromatic ring count strongly depress logS, while higher TPSA raises solubility.
Local SHAP attribution: explaining two contrasting molecules
Opening the black box on a single highly soluble compound vs. a poorly soluble hydrophobic molecule
Local SHAP waterfalls tell chemists exactly which structural lever (e.g., lowering LogP or adding polar groups) moves a specific candidate.
SHAP vs. MDI vs. Permutation under collinear descriptors
How three popular importance metrics behave when MolWt, HeavyAtomMolWt, and ExactMolWt coexist
Never interpret Permutation Importance blindly before pruning collinear features: shuffling one twin leaves its clones intact, collapsing its score to near zero!
From 2D SMILES graphs to 3D molecular geometry: ETKDGv3
Real molecules are flexible 3D objects—how RDKit turns a 1D string into physically realistic atomic coordinates
STEP 1 · EXPLICIT H & BOUNDS
Distance Geometry
Always call Chem.AddHs(mol) first! RDKit builds a pairwise distance bounds matrix from bond lengths, angles, and 1–4 distances, then embeds into 3D via metric matrix projection.
STEP 2 · ETKDGv3 TORSIONS
CSD Experimental Priors
Experimental-Torsion Knowledge Distance Geometry injects preferred dihedral distributions mined from the Cambridge Structural Database (CSD)—far better than naive geometry.
STEP 3 · MMFF94 RELAXATION
Force-Field Cleanup
Minimize steric clashes with MMFFOptimizeMolecule. Because rotatable bonds create multiple local minima, sample an ensemble of conformers and weight by Boltzmann factor.
A single 3D structure is rarely enough for flexible molecules—generate an ETKDGv3 conformer ensemble, minimize with MMFF94, and check Boltzmann weights.
Conformer ensembles & Boltzmann populations at 298 K
40 ETKDGv3 conformers of Ibuprofen relaxed with MMFF94: energy spread and room-temperature occupancy
At 298 K (k_B T ≈ 0.59 kcal/mol), conformers >2 kcal/mol above the global minimum contribute <3%—Boltzmann averaging focuses on populated shapes.
Honest test: do 3D descriptors actually improve logS prediction?
Principal Moments of Inertia (NPR1/NPR2) shape map and 5-fold CV comparison of 2D vs. 2D + 3D descriptors
3D vacuum shape barely moves AqSolDB RMSE—solubility is limited by solid-state crystal packing, not isolated gas-phase geometry!
Programmatic data retrieval: PubChem PUG-REST & PUG-View
When the missing physical variable isn't in your CSV, query 118M+ compounds via REST APIs—respecting rate limits
1
PUG-REST: /compound/smiles/{smi}/cids/JSON
Resolve SMILES or names to unique PubChem CID and structured properties (MW, IUPAC, InChIKey).
2
PUG-View: /data/compound/{cid}/JSON?heading=Melting+Point
Fetch curated experimental annotations (melting point, boiling point, hazards) from literature sources.
3
Regex parsing + local CSV cache + time.sleep(0.25)
Extract numeric °C from messy strings ("216–218 °C", "490 K"), throttle ≤5 req/s, and cache results!
DATA ENGINEERING REALITY
Why Experimental Text Needs Care
- Unit heterogeneity: °C, °F, and K coexist in the same PubChem section.
- Ranges & decomposition:
"286 °C (sublimes)" or "142-145 °C" require defensive regex rules.
- Reproducibility: Always save fetched data to
data/melting_points.csv so notebooks work offline.
Real-world materials informatics combines ML with clean API engineering: resolve IDs, parse noisy experimental text defensively, throttle requests, and cache locally.
Closing Lecture 02's cliffhanger: Yalkowsky's equation with real Tm
Adding experimental melting point (crystal packing proxy) to logP slashes solubility RMSE—even with zero fitted parameters!
Domain physics beats brute-force complexity: a 2-variable physical equation (LogP + Tₘ) breaks the ceiling that 200+ 2D/3D descriptors could not.
Summary (Take home notes)
- Prune before interpreting: Remove quasi-constant features and collinear clusters (|r| > 0.90); cutting 29 → 10 descriptors preserves accuracy while restoring clarity.
- Guard against leakage: Every supervised selection step must live inside
sklearn.pipeline.Pipeline—otherwise pure noise can mimic R2 ≈ 0.5.
- Explain locally & globally with SHAP: Exact
TreeExplainer decomposes each molecule's prediction into signed physical contributions and avoids Permutation's collinearity collapse.
- Be honest about 3D features: ETKDGv3 + MMFF94 conformer ensembles capture 3D shape, but add little to aqueous solubility where crystal packing dominates.
- Inject missing physics via APIs: Fetching experimental melting points from PubChem and plugging into Yalkowsky's GSE breaks the 2D accuracy ceiling.
Thanks for your listening
AI for Materials Science · Lecture 05 | Next: Hands-on Practice in 05c_exercises.ipynb