Supervised Learning for Molecular & Materials Discovery:
Intuition, Algorithms, Physical Priors & Validation Pitfalls
Lecture 02 roadmap: six progressive building blocks
020 and 02a–02ePanorama & Mindset
What are AI, ML & DL? How do SMILES strings become matrices X and targets y? Why is materials data fundamentally different from internet big data?
Linear Models & Regularization
Train/test split, 3-line scikit-learn API, Ordinary Least Squares, Gradient Descent, polynomial overfitting, and Ridge (L2) vs. Lasso (L1).
Distance & Margin Models
k-Nearest Neighbors (chemical analogy), why unscaled features ruin Euclidean distance, Support Vector Machines, RBF kernels, and ε-tubes.
Decision Trees & Ensembles
CART “20 questions” splits, Bagging (Random Forest) vs. Boosting (XGBoost), descriptors vs. fingerprints, and the Acene extrapolation trap.
Classification & Attribution
Perceptron to Sigmoid probabilities, escaping the Accuracy trap, ROC-AUC, lab-cost thresholds, C8-BTBT solvent priors & Yalkowsky’s equation.
Validation & Applicability Domain
5-Fold Cross-Validation, Pipeline against data leakage, Learning Curves, Murcko Scaffold Splits, and Tanimoto Applicability Domain checks.
Why materials science needs machine learning
What is machine learning? AI ⊃ ML ⊃ DL and the core paradigm flip
Machine Learning: Input X + Measured Labels y → Learn Mapping f̂(X)
| ML Paradigm | Data Needed | Typical Materials Question | Course |
|---|---|---|---|
| 1. Supervised | Labeled (X, y) | Predict solubility logS, bandgap Eg, or soluble vs. insoluble | Mod 02 |
| 2. Unsupervised | X only (no y) | Map chemical space (PCA/t-SNE), cluster ligands & catalysts | Mod 03 |
| 3. Active / BO | Small (X, y) | Pick the next best experiment under tight budget (GPR + EI) | Mod 04 |
| 4. Generative | Structures X | Inverse-design new molecules or super-resolve SEM images | Mod 08–09 |
| 5. End-to-End DL | Graphs / 3D | Learn directly from molecular graphs or crystal unit cells | Mod 07, 10 |
How molecules become numbers: from SMILES to (X, y)
| Molecule | SMILES | MolWt (x1) | MolLogP (x2) | TPSA Ų (x3) | Arom. Rings (x4) | Target y: logS | Screening Class |
|---|---|---|---|---|---|---|---|
| Ethanol | CCO | 46.07 | −0.00 | 20.23 | 0 | +1.10 | 0 (Soluble) |
| Benzene | c1ccccc1 | 78.11 | +1.69 | 0.00 | 1 | −1.64 | 0 (Soluble) |
| Naphthalene | c1ccc2ccccc2c1 | 128.17 | +2.84 | 0.00 | 2 | −3.61 | 0 (Borderline) |
| Anthracene | c1ccc2cc3ccccc3cc2c1 | 178.23 | +3.99 | 0.00 | 3 | −6.44 | 1 (Insoluble < −4) |
Reading a Parity Plot: three progressive leaps on AqSolDB
Materials data ≠ internet AI: interpolation vs. extrapolation
Standard 6-step materials ML workflow and thesis route selector
Active Learning Regime
Avoid deep neural nets! Use 5–12 physical descriptors + Ridge / Gaussian Process (GPR) + Bayesian Optimization (Module 04) to guide experiments.
Classical Tabular Sweet Spot
Random Forest, XGBoost, and Scaled RBF-SVR on domain descriptors + Count Fingerprints (Module 02) typically outperform deep learning.
Representation Learning
End-to-end Graph Neural Networks (Chemprop, CGCNN, MACE) & Transformers (Modules 07–10) learn features directly from atoms and bonds.
Train/test split, regression metrics, and logarithmic error scale
Zero-barrier Python: the universal 3-line scikit-learn workflow
(X_train, y_train).X_test (without y_test!), and compare y_pred vs. y_test.| Algorithm Family | Swap Line 1 Only! | Section |
|---|---|---|
| Ordinary Least Squares | LinearRegression() | 02a |
| L2 / L1 Regularized | Ridge(alpha=50) / Lasso(0.05) | 02a |
| k-Nearest Neighbors | KNeighborsRegressor(n_neighbors=5) | 02b |
| Support Vector Reg. | SVR(kernel="rbf", C=5.0) | 02b |
| Random Forest | RandomForestRegressor(150) | 02c |
| Gradient Boosting | XGBRegressor(n_estimators=300) | 02c |
| Binary Classifier | LogisticRegression() | 02d |
fit(X_train, y_train) and predict(X_test), you can run dozens of ML algorithms by changing a single line.How linear regression learns: least squares & gradient descent
Fitting curves with linear models: polynomial features & overfitting
Multivariate linear regression and the multicollinearity trap
Regularization intuition: putting a budget on runaway weights
Loss = MSE + α Σ wj2
Squares large weights heavily: (−6)² + (+5)² = 61 is crushed into (−0.5)² + (−0.5)² = 0.50! Correlated features share small, stable weights; none become exact zero.
Loss = MSE + α Σ |wj|
Diamond constraint has sharp corners sitting directly on coordinate axes—MSE contours hit corners first, driving redundant descriptors to exact 0 (automatic feature selection).
Ridge (L2) and Lasso (L1) regularization paths on AqSolDB
k-Nearest Neighbors (kNN): learning by chemical analogy
No Formula Fitted in .fit()
Unlike linear regression, kNN fits zero weights during training—it simply stores all known molecules (X_train, y_train) as coordinates in p-dimensional feature space.
Euclidean Distance d(x, xi)
For a query molecule x, compute straight-line distance across all p features:
d = √[ Σj=1..p (xj − xij)² ]
Pick the k closest training neighbors.
Average or Distance-Weight
Uniform: ŷ = (1/k) Σ yi.
Distance-weighted: closer analogs get higher weight wi = 1/di.
k = 1 overfits noise; k = 100 oversmooths.
MolLogP spans −5 to +7, while complexity index BertzCT spans 0 to 4,000? → A 1% change in BertzCT completely drowns out hydrophobicity!
Why feature scaling is mandatory: rescuing Naphthalene’s neighbors
StandardScaler rescues neighbor chemistry (Pred −0.74 → −2.99) and slashes 17D kNN Test RMSE from 1.56 to 1.19.Support Vector Machines (SVM): widest street, RBF kernel & ε-tube
The Widest Separating Street
Among infinitely many lines separating two classes, SVM picks the centerline with the widest safety margin—anchored solely by boundary molecules called Support Vectors. Knob C balances margin width vs. margin violations.
Lifting 2D Rings into 3D
When classes form concentric rings inseparable by any straight line, the Radial Basis Function kernel K(x, x′) = exp(−γ‖x−x′‖²) measures Gaussian similarity—implicitly slicing a 3D hill into smooth nonlinear contours in 2D!
Ignoring Lab Noise ≤ ε
Wet-lab logS measurements naturally fluctuate by ±0.2 units. Support Vector Regression wraps a tolerance tube of half-width ε around the curve: points inside incur zero loss, preventing overfitting to titration noise.
StandardScaler first (RBF depends on ‖x−x′‖²)! • Too large γ shrinks Gaussian width into tiny “overfitting islands” around individual molecules; balanced C = 5, gamma = "scale" yields smooth generalization.
Visualizing SVM margins, RBF boundaries, and SVR solubility contours
How a decision tree thinks: playing “20 questions” with molecules
Rank-Order Invariance
Asking MolWt ≤ 250 splits the exact same molecules left and right as asking MolWt_scaled ≤ +0.12! Decision trees, Random Forests, and XGBoost never need StandardScaler.
Leaf Output = Training Average
Every terminal leaf simply outputs the average y of training molecules inside that box—making a tree a piecewise-constant step function bounded by [y_min, y_max].
MolLogP ≤ 2.75 as the single most informative root split.Piecewise-constant steps and single-tree variance overfitting
max_depth=2 steps vs. an unpruned tree that isolates single noisy molecules per leafWisdom of crowds: Bagging (Random Forest) vs. Boosting (XGBoost)
Random Forest (Bagging)
- Bootstrap rows + random features: Train 150 deep, independent trees in parallel, each seeing a slightly different random sample of molecules and descriptors.
- Average out noise: Individual deep trees overfit in different random directions; averaging all 150 trees cancels variance:
ŷ = (1 / B) Σb=1..B Treeb(x) - Strength: Extremely hard to overfit by adding more trees; works great out-of-the-box with minimal tuning.
XGBoost (Gradient Boosting)
- Learn from prior mistakes: Train shallow trees (
max_depth = 4–6) one after another in series. - Fit residuals: Tree t does NOT predict y—it predicts the remaining error r(t−1) = y − ŷ(t−1), nudged by learning rate η:
ŷ(T) = Σt=1..T η · Treet(x) - Strength: Highest tabular accuracy, but aggressive
learning_rateor excessive depth can overfit noise.
Boosting residual stages and ensemble convergence on AqSolDB
Molecular representations: global descriptors vs. local fingerprints
Organic semiconductor stress test: why tree ensembles cannot extrapolate
Binary classification: from Perceptron to Logistic Regression
predict_proba.Classification metrics for beginners: escaping the Accuracy trap
| 2×2 Confusion Matrix | Predicted Soluble (0) | Predicted Insoluble (1) |
|---|---|---|
| Truly Soluble (0) (Good candidate) |
TN (True Negative) Correctly passed to lab |
FP (False Alarm) Viable molecule discarded |
| Truly Insoluble (1) (“Brick dust”) |
FN (Missed Trap!) Wastes 2 wks synthesis! |
TP (True Positive) Successfully intercepted |
Confusion matrix, ROC curves, and decision threshold tuning
Opening the black box: solvent priors & Yalkowsky’s solubility equation
BTBT vs. C8-BTBTC8-BTBT dissolves well in chlorobenzene yet scores insoluble in water (MolLogP = 11.1)—models strictly obey training solvent priors!Leak-free validation architecture: 5-Fold CV and sklearn.Pipeline
X_s = SelectKBest().fit_transform(X_train, y_train)cross_val_score(Ridge(), X_s, y_train, cv=5)
Validation fold labels already leaked into feature selection before CV even started!
pipe = make_pipeline(StandardScaler(), SVR())cross_val_score(pipe, X_train, y_train, cv=5)
Automatically fits scaler/selector inside the 4 blue folds only during every round!
.fit() method (scaling, imputation, PCA, feature selection) belongs inside a Pipeline.Quantifying split variance and catching leakage on pure random noise
Pipeline honestly reports R2 = −0.77.Hyperparameter tuning (GridSearchCV) and learning curves
.fit) vs. Hyperparameters (tuned via 5-Fold CV on X_train) · Scaling with dataset size NRealistic generalization: Bemis–Murcko scaffold and ring-size splits
Applicability domain (AD): knowing when NOT to trust your model
How good is good enough? Benchmarking against experimental noise
02a–02c against the label noise floor measured in Lecture 01 (a), and the same Random Forest re-scored by how much the sources agreed (b)Practical cheat-sheet: which supervised model should I choose?
| Algorithm | StandardScaler? |
AqSolDB RMSE | Extrapolates Trend? | Best Materials Science Use Case |
|---|---|---|---|---|
| OLS / Ridge (L2) | Yes (for Ridge) | 1.64 – 1.65 | Yes (linear/physics) | Fast mandatory baseline; physical scaling laws (e.g., 1/N oligomer bandgap) |
| Lasso (L1) | Yes (mandatory) | 1.67 | Yes (linear) | Automatic feature selection when pruning dozens of collinear descriptors |
| kNN | Mandatory! | 1.19 – 1.24 | No (local average) | Intuitive chemical-analogy lookup; inspect actual nearest database molecules |
| RBF-SVM / SVR | Mandatory! | 1.23 | No (decays to mean) | Smooth nonlinear surfaces on small-to-medium descriptor tables (N < 5,000) |
| Random Forest | No (scale-free) | 1.17 | No (flatlines!) | Rock-solid nonlinear tabular workhorse; minimal tuning, resistant to overfitting |
| XGBoost | No (scale-free) | 1.11 (Hybrid) | No (flatlines!) | Highest accuracy on descriptors + Count Fingerprints (tune lr & max_depth) |
| Logistic Reg. | Yes (for L2) | AUC = 0.892 | Linear log-odds | Calibrated baseline probabilities for binary pass/fail screening |
Summary (Take home notes)
- Start simple, benchmark fairly: Lock away
X_testfirst, beat the Dummy baseline (2.42), and progress systematically from Ridge (1.65) → Scaled kNN/SVR (1.19–1.23) → RF/XGBoost + Count FP (1.11, R2 = 0.79). - Respect geometry & units: Distance, kernel, and regularized models require training-only
StandardScalerinside aPipeline; tree ensembles are scale-invariant, while Ridge (L2) and Permutation Importance tame collinearity. - Match metrics to lab costs: Under class imbalance, replace Accuracy with Confusion Matrices, ROC-AUC (0.956), and threshold tuning (lowering τ = 0.25 catches >93% of insoluble compounds).
- Never ignore physical priors: Tree ensembles strictly interpolate within training label bounds (Pentacene flatline); predictions obey training solvent conditions (water vs. chlorobenzene for
C8-BTBT) and miss unencoded 3D crystal lattice energy (Tm). - Validate like a skeptic before synthesis: Combine 5-Fold CV (
mean ± std), Murcko Scaffold Splits, Learning Curves, and Count-FP Applicability Domain checks.
Thanks for your listening
020 & 02a–02f