AI for Materials Science · Lecture 07 (Complete Beginner-to-Research Edition)
Deep Learning Foundations & Microstructure Vision:
PyTorch MLPs, MC Dropout Uncertainty & Convolutional Neural Networks
Zesheng Liu
Laboratory of Organic Electronics, Linköping University
Modules 07a–07b | Pure PyTorch (CPU), Autograd, AqSolDB MLP & 4-Class Alloy Metallography CNN
Lecture 07 roadmap: from a single neuron to alloy vision
Transitioning from Scikit-Learn tabular models to differentiable PyTorch architectures (
07a–07b)PART 1 · MODULE 07a
PyTorch & Autograd
Tensors, computational graphs, automatic differentiation (loss.backward()), manual gradient descent on AqSolDB, and clean nn.Module encapsulation.
PART 2 · MODULE 07a
Regularization & Uncertainty
Train/Val/Test splits, DataLoader mini-batches, diagnosing overfitting, Dropout + Weight Decay + Early Stopping, and MC Dropout uncertainty bands.
PART 3 · MODULE 07b
Microstructure CNNs
Why MLPs fail on images, 2D convolution & Sobel phase-boundary filters, feature-map dimension arithmetic, 4-class metallography classification, and quantitative statistics.
Deep learning replaces manual feature engineering with differentiable layers—letting gradients optimize representations directly for molecules and micrographs.
Artificial neurons, nonlinear activations & MLP depth
Without nonlinear activation functions, stacking 100 linear layers collapses to a single matrix multiplication!
ReLU and GELU introduce piecewise/smooth nonlinearity without Sigmoid's vanishing-gradient saturation—enabling deep universal function approximation.
PyTorch Autograd in action: manual gradient descent on AqSolDB
Tracking operations dynamically to compute exact ∂L/∂w and ∂L/∂b with
loss.backward()PyTorch autograd reproduces exact analytical least squares (slope ≈ −0.42)—and scales identically to millions of neural network weights.
The universal PyTorch training loop (nn.Module + DataLoader)
Every deep learning model in Lectures 07–10 (MLP, CNN, LSTM, Transformer, VAE, GNN) follows this exact 4-step pattern
1
class SolubilityMLP(nn.Module): def forward(self, x): ...
Define layers in
__init__ and data flow in forward. PyTorch auto-tracks all parameters.2
for xb, yb in train_loader: pred = model(xb); loss = criterion(pred, yb)
Mini-batch forward pass via
DataLoader(shuffle=True) adds beneficial stochasticity and bounds RAM.3
optimizer.zero_grad(); loss.backward(); optimizer.step()
Clear old gradients → backpropagate exact partial derivatives → update weights with AdamW.
4
model.eval(); with torch.no_grad(): val_loss = ...
Switch off Dropout/BatchNorm updates and gradient tracking during validation & testing!
Master this 4-step PyTorch loop once, and you already know the engine behind CNNs, Transformers, VAEs, Diffusion models, and GNNs.
Taming overfitting: Dropout + Weight Decay + Early Stopping
A 50× wider MLP memorizes training noise unless constrained—and still hits the same tabular feature ceiling as RF!
On 17 tabular descriptors, a 512×512 MLP (RMSE ~1.17) cannot beat Random Forest (1.17)—the bottleneck is representation, not network width!
MC Dropout: deep-learning uncertainty in 2 lines of code
Bridging Lecture 04 (Gaussian Processes) to neural networks: keep
Dropout active during T = 80 inference passesRunning T stochastic forward passes with Dropout enabled approximates Bayesian inference—producing wider error bars in unexplored materials gaps.
Learning rate dynamics: the #1 training hyperparameter
Too small crawls forever, too large overshoots the valley—always inspect the loss curve first!
When a neural network fails to learn, check input standardization and learning rate (typically 1e-3 to 3e-3 for Adam) before changing architecture.
Why MLPs fail on SEM/metallography images
Flattening a 256×256 micrograph into a 65,536-element vector destroys 2D spatial neighborhood & explodes parameters
FLATTENED MLP
No Spatial Inductive Bias
- Parameter explosion: 65,536 inputs × 512 hidden = 33.5 million weights in layer 1 alone!
- Zero translation equivariance: Shifting a precipitate by 3 pixels triggers completely different weights.
- Destroys grain-boundary topology and local texture.
CONVOLUTIONAL NEURAL NETWORK (CNN)
Local Receptive Fields + Weight Sharing
- Tiny shared kernels (3×3): Only 9 weights per channel slide across the entire micrograph!
- Translation equivariance: A precipitate detector fires wherever the precipitate appears.
- Hierarchical features: Edges → grain boundaries → phase morphologies.
Inductive bias matters: CNNs encode 2D locality and translation symmetry directly into the architecture—using 1,000× fewer parameters than MLPs.
2D convolution: from classical Sobel filters to learned kernels
Sliding a 3×3 weighted stencil across an alloy micrograph highlights phase boundaries—CNNs learn optimal stencils automatically!
Classical image processing hand-crafts filters (Sobel, Gaussian); a CNN treats filter entries as learnable PyTorch weights updated by backprop.
Microstructure classification: four classic alloy morphologies
Processing history imprints unmistakable spatial signatures—linking Processing → Structure → Properties
Different heat treatments produce distinct textures (equiaxed grains, lamellar pearlite, precipitates, dendrites)—ideal for CNN feature hierarchies.
Opening the CNN black box: accuracy & quantitative metallography
A lightweight 2-layer CPU CNN achieves near-perfect microstructure classification and pairs with phase-fraction analysis
Inspecting CNN feature maps and coupling predictions with physical metrics (precipitate area fraction, size distribution) turns vision ML into actionable metallurgy.
Multi-task heads & small-data microscopy transfer learning
When lab micrographs are scarce (N = 12–30), freeze a pretrained backbone first, train a tiny head, then gently fine-tune!
Reuse pretrained edge/texture filters (ImageNet / MicroNet) via two-stage fine-tuning—and use multi-head trunks when predicting coupled properties like E_g + ΔE_f!
Summary (Take home notes)
- Differentiable building blocks: Nonlinear activations (ReLU/GELU) + PyTorch autograd turn arbitrary layer stacks into end-to-end trainable models.
- Regularize & quantify uncertainty: Combine Dropout, Weight Decay, and Early Stopping to prevent memorization; keep Dropout on at inference (MC Dropout) for uncertainty bands.
- Know when MLPs plateau: On fixed tabular descriptors, wider MLPs rarely beat Random Forests—deep learning's true edge is learning from raw structured data.
- CNNs encode 2D spatial symmetry: Local 3×3 weight-shared kernels + pooling give translation equivariance with 1,000× fewer parameters than flattened MLPs.
- Pair classification with physics: Combine CNN microstructure recognition with feature-map inspection and quantitative phase statistics.
Thanks for your listening
Zesheng Liu · zesheng.liu@liu.se
AI for Materials Science · Lecture 07 | Next: Hands-on Practice in
07c_exercises.ipynb