Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Part I: Introduction to Machine Learning

From Parameters to Functions | Module 6: The Learnable Universe | ASTR 596

San Diego State University

“The purpose of computing is insight, not numbers.”

Richard Hamming

Learning Objectives

By the end of this module, you will be able to:

  1. Articulate what machine learning is and how it differs from (and connects to) traditional scientific computing

  2. Identify when machine learning is appropriate for astrophysical problems versus when physics-based simulation is better

  3. Understand the fundamental learning problem: balancing model complexity with data limitations

  4. Connect machine learning to statistical inference (Module 5) and function approximation (Module 1)

  5. Distinguish between supervised, unsupervised, and reinforcement learning paradigms

  6. Recognize common pitfalls: overfitting, underfitting, and the bias-variance tradeoff

  7. Design validation strategies to assess model generalization

  8. Appreciate the philosophical shift from “physics first” to “data first” approaches in modern astrophysics


From Parameter Inference to Function Learning

The Bayesian Foundation (Module 5 Recap)

In Module 5: Inferential Thinking, you learned Bayesian inference for parameters:

The Parameter Inference Problem:

Example from Module 5: Fitting a line to data

yi=θ0+θ1xi+ϵiy_i = \theta_0 + \theta_1 x_i + \epsilon_i

You inferred the parameters θ=(θ0,θ1)\boldsymbol{\theta} = (\theta_0, \theta_1) from noisy observations.

The Machine Learning Extension

Machine learning is Bayesian inference in function space.

Instead of asking “what parameters θ\boldsymbol{\theta} are plausible?”, we ask:

“What functions ff are plausible?”

Given data D={(xi,yi)}\mathcal{D} = \{(\mathbf{x}_i, y_i)\}, we want the posterior over functions:

p(fD)p(Df)p(f)p(f \,|\, \mathcal{D}) \propto p(\mathcal{D} \,|\, f) \cdot p(f)

The mathematical structure is identical to Module 5—only the space changed:

Module 5: Parameter SpaceModule 6: Function Space
Parameter θRd\boldsymbol{\theta} \in \mathbb{R}^dFunction f:RdRf: \mathbb{R}^d \to \mathbb{R}
Prior p(θ)p(\boldsymbol{\theta})Prior p(f)p(f) (kernel, architecture)
Likelihood p(D,,θ)p(\mathcal{D} \\,\vert\\, \boldsymbol{\theta})Likelihood p(D,,f)p(\mathcal{D} \\,\vert\\, f)
MCMC samples p(θ,,D)p(\boldsymbol{\theta} \\,\vert\\, \mathcal{D})Learning algorithms find p(f,,D)p(f \\,\vert\\, \mathcal{D})
Predictive: marginalize posteriorPredictive: marginalize posterior

What This Module Teaches You

Part 1-4: What is machine learning? Why does astrophysics need it?

Part 2: Gaussian Processes

Part 3: Neural Networks

Throughout: Bayesian thinking guides ML design choices


🔴 Part 1: What Is Machine Learning?

The Traditional Scientific Method

You’ve spent this entire semester doing physics-based computational astrophysics:

  1. Write down equations: dvidt=jiGmj(rjri)rjri3\frac{d\mathbf{v}_i}{dt} = \sum_{j \neq i} \frac{Gm_j(\mathbf{r}_j - \mathbf{r}_i)}{|\mathbf{r}_j - \mathbf{r}_i|^3}

  2. Solve numerically: Runge-Kutta, leapfrog, adaptive timesteps

  3. Analyze results: Measure observables, compare to theory

  4. Iterate: Refine physics, improve numerics, explore parameter space

This is model-driven science: we start with physical laws and derive predictions.

Strengths:

Limitations:

The Machine Learning Paradigm

Machine learning inverts the traditional approach:

Instead of: Physics equations → Simulation → Predictions

We do: Data → Learning algorithm → Predictions

A Concrete Example: Your Final Project

The Problem: Predict how a star cluster evolves from t=0t=0 to t=200t=200 Myr.

Physics-based approach (Projects 2 & 5):

Initial conditions → N-body equations → Integrate 200 Myr → r_core(t)
                    (Computationally expensive!)

Machine learning approach (Final Project):

Many N-body simulations → Learn patterns → Instant predictions
(Upfront cost, then fast!)

The key insight: We’re not replacing physics—we’re using N-body simulations to train a fast surrogate model.

This is physics-informed machine learning: combining physical knowledge with data-driven learning.


🔴 Part 2: The Learning Problem - Generalization from Data

What Does It Mean to “Learn”?

Suppose we have training data:

D={(xi,yi)}i=1N\mathcal{D} = \{(\mathbf{x}_i, y_i)\}_{i=1}^{N}

where:

Goal: Find a function ff such that for new, unseen inputs x\mathbf{x}_*:

f(x)yf(\mathbf{x}_*) \approx y_*

This is the learning problem: generalize from observed data to unobserved cases.

The Bayesian Perspective: Learning = Inference

The Fundamental Challenge: Bias-Variance Tradeoff

Consider fitting a polynomial to data:

Underfitting (high bias):

f(x)=w0+w1x(linear model)f(x) = w_0 + w_1 x \quad \text{(linear model)}

Overfitting (high variance):

f(x)=i=0100wixi(100th degree polynomial)f(x) = \sum_{i=0}^{100} w_i x^i \quad \text{(100th degree polynomial)}

Just right:

f(x)=i=05wixi(modest degree polynomial)f(x) = \sum_{i=0}^{5} w_i x^i \quad \text{(modest degree polynomial)}

Figure 1:Figure 1: The bias-variance tradeoff.

  • Left: Underfit model (high bias) - too simple, doesn’t capture curvature

  • Middle: Well-fit model - captures trend, robust to noise

  • Right: Overfit model (high variance) - memorizes noise, wiggles unrealistically

The mathematical formulation:

Expected prediction error decomposes as:

E[(yf^(x))2]=Bias[f^(x)]2systematic error+Var[f^(x)]sensitivity to data+σ2irreducible noise\mathbb{E}[(y - \hat{f}(x))^2] = \underbrace{\text{Bias}[\hat{f}(x)]^2}_{\text{systematic error}} + \underbrace{\text{Var}[\hat{f}(x)]}_{\text{sensitivity to data}} + \underbrace{\sigma^2}_{\text{irreducible noise}}

Key insight: There’s an optimal model complexity that balances bias and variance!

Training, Validation, and Test Sets

The gold standard: Split data into three sets:

  1. Training set (60-80%): Fit model parameters

  2. Validation set (10-20%): Tune hyperparameters (model complexity, regularization)

  3. Test set (10-20%): Final evaluation (never used during development!)

Why three sets?

Cross-Validation: Making the Most of Limited Data

When data is scarce (e.g., 200 expensive N-body simulations), splitting into train/val/test is wasteful.

K-fold cross-validation:

  1. Divide data into KK folds (typically K=5K=5 or K=10K=10)

  2. For each fold kk:

    • Train on all folds except kk

    • Validate on fold kk

  3. Average performance across all KK folds

This uses all data for both training and validation (at different times).

import jax.numpy as jnp

def k_fold_cross_validation(X, y, model_fn, k=5):
    """K-fold cross-validation
    
    Args:
        X: Input data (N, d)
        y: Outputs (N,)
        model_fn: Function that trains and evaluates model
        k: Number of folds
        
    Returns:
        scores: Validation scores for each fold
    """
    N = len(X)
    fold_size = N // k
    scores = []
    
    for i in range(k):
        # Split into train and validation
        val_start = i * fold_size
        val_end = (i + 1) * fold_size
        
        # Validation fold
        X_val = X[val_start:val_end]
        y_val = y[val_start:val_end]
        
        # Training folds (everything else)
        X_train = jnp.concatenate([X[:val_start], X[val_end:]])
        y_train = jnp.concatenate([y[:val_start], y[val_end:]])
        
        # Train and evaluate
        score = model_fn(X_train, y_train, X_val, y_val)
        scores.append(score)
    
    return jnp.array(scores)

# Usage
mean_score = jnp.mean(scores)
std_score = jnp.std(scores)
print(f"CV Score: {mean_score:.3f} ± {std_score:.3f}")

🟡 Part 3: Types of Machine Learning

Supervised Learning: Learning from Labeled Examples

Setup: We have input-output pairs {(xi,yi)}\{(\mathbf{x}_i, y_i)\}

Goal: Learn mapping f:xyf: \mathbf{x} \to y

Two subtypes:

  1. Regression: Predict continuous values

    • Example: Initial conditions → core radius

    • Loss: Mean Squared Error (MSE)

  2. Classification: Predict discrete categories

    • Example: Galaxy image → [spiral, elliptical, irregular]

    • Loss: Cross-entropy

Astrophysical applications:

Unsupervised Learning: Finding Structure Without Labels

Setup: We only have inputs {xi}\{\mathbf{x}_i\} (no outputs!)

Goal: Discover hidden structure, patterns, or groupings

Common tasks:

  1. Clustering: Group similar objects

    • K-means, hierarchical clustering

    • Example: Group galaxies by properties (without pre-defined labels)

  2. Dimensionality reduction: Find low-dimensional representation

    • PCA, t-SNE, autoencoders

    • Example: Compress 1000-dimensional galaxy spectra to 10 principal components

  3. Density estimation: Learn probability distribution

    • Example: What’s the distribution of stellar masses in clusters?

Astrophysical applications:

Reinforcement Learning: Learning from Interaction

Setup: Agent interacts with environment, receives rewards

Goal: Learn policy (strategy) that maximizes cumulative reward

Components:

Astrophysical applications (less common but emerging):

Not the focus of this course (supervised learning is most relevant for emulation).


🔴 Part 4: Why Machine Learning for Astrophysics?

The Data Deluge

Astronomy is drowning in data:

Survey/InstrumentData VolumeTime to Analyze Manually
Sloan Digital Sky Survey (SDSS)200 million objectsCenturies
Large Synoptic Survey Telescope (LSST)30 TB/nightImpossible
Square Kilometer Array (SKA)160 TB/secondAbsolutely impossible
Gaia1 billion starsMany lifetimes

Traditional approach: Manually inspect each object, classify, measure properties

Machine learning approach: Train algorithms to do this automatically

The Complexity Challenge

Some astrophysical systems are too complex for analytic solutions:

Simple (we have equations):

Complex (need simulation):

Very complex (even simulation is hard):

Machine learning solution: Learn simplified models from expensive simulations

The Emulation Use Case: Your Final Project

This is the primary motivation for your final project:

The Problem:

The ML Solution:

  1. Run 500 simulations (8 hours)

  2. Train surrogate model (1 hour)

  3. Make 10,000 predictions (seconds)

  4. Total: <10 hours instead of 1 week

The benefit: ~100-1000× speedup (depending on emulator type and accuracy) enables:

When NOT to Use Machine Learning

ML is powerful but not always appropriate:

Don’t use ML when:

  1. Physics is cheap: If simulation takes seconds, no need for emulation

  2. Data is scarce: <100 training examples → physics priors are better

  3. Interpretability is critical: Need to understand mechanism, not just predict

  4. Extrapolation is required: ML fails outside training distribution

  5. Uncertainty quantification is essential: Standard NNs don’t provide this

Use ML when:

  1. Physics is expensive: Emulation saves time

  2. Data is abundant: Enough examples to learn patterns

  3. Patterns are complex: Too nonlinear for simple models

  4. Speed matters: Need real-time or interactive predictions

  5. You validate carefully: Test generalization thoroughly


🟡 Part 5: The Spectrum of Models - From Physics to Data

A Taxonomy of Approaches

Figure 2:Figure 2: The spectrum from purely physics-based to purely data-driven models.

Level 1: Pure Physics (Projects 1-5)

Level 2: Physics-Informed ML (Final project, Residual Networks)

Level 3: Constrained ML (Physics-Informed Neural Networks)

Level 4: Pure ML (Standard Neural Networks)

Level 5: End-to-End Learning (Deep Learning on Raw Data)

Example: Photometric Redshifts

The Problem: Estimate galaxy distance from broad-band colors (no spectroscopy)

Level 1 (Pure Physics):

Level 2-3 (Physics-Informed ML):

Level 4 (Pure ML):

Current best practice: Hybrid approaches (Levels 2-3)


🔴 Part 6: The Learning Algorithm Landscape

Classical Machine Learning (Pre-Deep Learning)

Linear Models:

Tree-Based Methods:

Support Vector Machines (SVMs):

Gaussian Processes (Part 2 of this module):

Deep Learning (Modern ML)

Neural Networks (Part 3 of this module):

Specialized Architectures:

The Modern Paradigm:


🟡 Part 7: Evaluation and Validation

Metrics for Regression

For continuous predictions y^i\hat{y}_i vs true values yiy_i:

Mean Squared Error (MSE):

MSE=1Ni=1N(yiy^i)2\text{MSE} = \frac{1}{N} \sum_{i=1}^{N} (y_i - \hat{y}_i)^2

Root Mean Squared Error (RMSE):

RMSE=MSE\text{RMSE} = \sqrt{\text{MSE}}

Mean Absolute Error (MAE):

MAE=1Ni=1Nyiy^i\text{MAE} = \frac{1}{N} \sum_{i=1}^{N} |y_i - \hat{y}_i|

R² Score (Coefficient of Determination):

R2=1i(yiy^i)2i(yiyˉ)2R^2 = 1 - \frac{\sum_i (y_i - \hat{y}_i)^2}{\sum_i (y_i - \bar{y})^2}

Classification metrics: Accuracy, precision, recall, F1 score, confusion matrix

Visualizing performance:


🔴 Part 8: Regularization = Bayesian Priors

The Bayesian View: Regularization IS Prior Knowledge

In machine learning, we typically don’t compute the full posterior p(fD)p(f \,|\, \mathcal{D}). Instead, we find the MAP (Maximum A Posteriori) estimate:

fMAP=argmaxfp(fD)=argmaxf[p(Df)p(f)]f_{\text{MAP}} = \arg\max_f p(f \,|\, \mathcal{D}) = \arg\max_f \left[ p(\mathcal{D} \,|\, f) \cdot p(f) \right]

Taking the negative log:

fMAP=argminf[logp(Df)Data loss Ldata+logp(f)Prior penalty]f_{\text{MAP}} = \arg\min_f \left[ \underbrace{-\log p(\mathcal{D} \,|\, f)}_{\text{Data loss } \mathcal{L}_{\text{data}}} + \underbrace{-\log p(f)}_{\text{Prior penalty}} \right]

This is training with regularization!

Training loss=Data loss+Regularization=logp(Df)logp(f)\boxed{\text{Training loss} = \text{Data loss} + \text{Regularization} = -\log p(\mathcal{D} \,|\, f) - \log p(f)}

Different regularization techniques = different Bayesian priors on functions

L2 Regularization = Gaussian Prior

Regularization term:

Ltotal=Ldata+λ2iwi2\mathcal{L}_{\text{total}} = \mathcal{L}_{\text{data}} + \frac{\lambda}{2} \sum_i w_i^2

Bayesian interpretation: This is MAP estimation with a Gaussian prior on weights:

p(wi)=N(0,σ2)logp(w)=12σ2iwi2+constp(w_i) = \mathcal{N}(0, \sigma^2) \quad \Rightarrow \quad -\log p(\mathbf{w}) = \frac{1}{2\sigma^2} \sum_i w_i^2 + \text{const}

where λ=1/σ2\lambda = 1/\sigma^2 connects the regularization strength to prior variance.

What this prior says: “I believe weights should be small, with typical magnitude σ\sigma. Large weights are possible but unlikely.”

Effect: Smooth functions (no wild oscillations)

Also known as: Ridge regression, weight decay

L1 Regularization = Laplace Prior

Regularization term:

Ltotal=Ldata+λiwi\mathcal{L}_{\text{total}} = \mathcal{L}_{\text{data}} + \lambda \sum_i |w_i|

Bayesian interpretation: This is MAP estimation with a Laplace prior:

p(wi)=12bexp(wib)logp(w)=1biwi+constp(w_i) = \frac{1}{2b} \exp\left(-\frac{|w_i|}{b}\right) \quad \Rightarrow \quad -\log p(\mathbf{w}) = \frac{1}{b} \sum_i |w_i| + \text{const}

What this prior says: “I believe most weights should be exactly zero. Only a few features matter.”

Effect: Sparse models - drives many weights to exactly zero

Use case: Automatic feature selection

Also known as: Lasso regression

Comparing Priors Visually

Figure 3:Figure: L2 vs L1 priors in 2D weight space.

  • L2 (Gaussian): Circular contours → encourages small weights uniformly

  • L1 (Laplace): Diamond-shaped contours → encourages weights along axes (sparsity)

Key insight: The sharp corners of the L1 diamond cause weights to hit zero exactly!

Early Stopping = Implicit Prior on Solution Trajectory

What it is: Stop training when validation loss stops improving

Bayesian interpretation:

Why this makes sense: Neural network training typically finds simpler patterns first, then overfits to noise later.

Dropout = Approximate Bayesian Model Averaging

What it is: During training, randomly drop neurons with probability pp

Bayesian interpretation (Gal & Ghahramani, 2016):

DropoutSampling from approximate posterior over networks\text{Dropout} \approx \text{Sampling from approximate posterior over networks}

At test time with dropout:

Important caveats: This connection is approximate, and the approximation quality depends on:

  1. Coverage underfitting: Dropout uncertainty often underestimates true epistemic uncertainty (empirical coverage < nominal—e.g., 68% coverage instead of predicted 95%)

  2. Missing structure: The approximate posterior doesn’t capture all correlations present in the true Bayesian posterior

  3. Hyperparameter sensitivity: Dropout rate pp must be tuned carefully; no principled way to choose it from Bayes’ theorem

  4. No marginal likelihood: Unlike GPs, dropout networks can’t compute marginal likelihood for model comparison

When to use for uncertainty:

# Dropout for uncertainty quantification
def predict_with_uncertainty(model, x, n_samples=100):
    """Use dropout at test time for uncertainty estimates"""
    predictions = []
    for _ in range(n_samples):
        # Keep dropout active at test time
        y_pred = model(x, training=True)
        predictions.append(y_pred)

    predictions = jnp.array(predictions)
    mean = jnp.mean(predictions, axis=0)
    std = jnp.std(predictions, axis=0)  # Epistemic uncertainty

    return mean, std

The Fundamental Connection


🟡 Part 9: The Philosophical Shift - From Understanding to Prediction

The Traditional Physics Mindset

As a physicist, you’ve been trained to ask:

This is the explanatory paradigm: science as understanding mechanism.

Example: Newton didn’t just predict planetary motion—he explained it via gravity.

The Machine Learning Mindset

Machine learning often asks:

This is the predictive paradigm: science as pattern recognition.

Example: A neural network might predict galaxy morphology accurately without understanding how galaxies form.

Interpretability vs Accuracy

The tradeoff: Linear models and GPs are interpretable; deep neural networks are powerful but opaque.

For astrophysics: Choose based on goal—interpretability for theory testing, prediction for observations.

Scientific Integrity

Key principles: Hold out test set (use only once!), report all experiments (including failures), validate predictions physically, practice open science.


🔴 Part 10: Looking Ahead - The Module Structure

Part 2: Gaussian Processes

What you’ll learn:

What you’ll build:

What you’ll discover:

Part 3: Neural Networks

What you’ll learn:

What you’ll build:

What you’ll discover:

The Final Project Arc

Week 1: Train GP on scalar outputs

Week 2: Demonstrate GP limitations

Week 3-4: Implement neural networks

Deliverable: Comprehensive analysis answering:


Conceptual Checkpoints

Before moving to Parts 2 and 3, reflect on these questions:

  1. Generalization: You have 500 N-body simulations. How do you know your ML model will work on the 501st simulation you haven’t run yet?

  2. Bias-Variance: A simple linear model has high bias but low variance. A 100-layer neural network has low bias but high variance. For 200 training samples, which would you choose? Why?

  3. Cross-validation: Why do we need a separate validation set? Can’t we just look at training error?

  4. Physics vs ML: Your physics-based N-body code gives exact answers (within numerical precision). Your ML emulator gives approximate answers (±5% error). Why would you ever use the emulator?

  5. Interpretability: A Gaussian Process tells you that the lengthscale for the NN parameter is small (meaning NN strongly affects core radius). A neural network predicts accurately but doesn’t tell you why. Which is more useful for science?

  6. Overfitting: You train a model that achieves 99.9% accuracy on training data but only 60% accuracy on test data. What went wrong? How would you fix it?

  7. Regularization: Explain why adding a penalty λiwi2\lambda \sum_i w_i^2 to the loss function is equivalent to putting a Gaussian prior on weights in Bayesian inference (Module 5 connection!).

  8. Connection to Module 1: How is machine learning related to function approximation with basis functions? What makes ML different from choosing Fourier or Legendre basis functions?


Further Reading

Foundational Machine Learning

  1. James, Witten, Hastie, Tibshirani (2013): An Introduction to Statistical Learning

  2. Bishop (2006): Pattern Recognition and Machine Learning

    • More mathematical, comprehensive

    • Covers Bayesian perspective

  3. Murphy (2012): Machine Learning: A Probabilistic Perspective

    • Connects ML to probabilistic inference

    • Great for physics backgrounds

ML for Physical Sciences

  1. Mehta et al. (2019): “A high-bias, low-variance introduction to Machine Learning for physicists”

  2. Cranmer et al. (2020): “The frontier of simulation-based inference”

    • Connects ML to statistical inference

    • Relevant for emulation

  3. Carleo et al. (2019): “Machine learning and the physical sciences”

    • Reviews of Modern Physics

    • Comprehensive survey

Astrophysics Applications

  1. Baron (2019): “Machine Learning in Astronomy: A Practical Overview”

    • Survey of ML applications in astronomy

  2. Ntampaka et al. (2019): “The Role of Machine Learning in Astrophysics”

    • Philosophical and practical perspectives

  3. Fluke & Jacobs (2020): “Surveying the reach and maturity of machine learning and artificial intelligence in astronomy”

    • State of the field

Gaussian Processes (Preview of Part 2)

  1. Rasmussen & Williams (2006): Gaussian Processes for Machine Learning

Deep Learning (Preview of Part 3)

  1. Goodfellow, Bengio, Courville (2016): Deep Learning


What’s Next

You now understand:

In Part 2, you’ll learn:

In Part 3, you’ll learn:

Together, these three parts will give you: