Stochastic Dynamics
modeling randomness through time-dependent processes, differential equations, and sampling techniques
Core Concepts Covered
- Random walks, Markov transition calculations, and stationary distributions
- Euler-Maruyama simulation, diffusion equations, scores, and Langevin dynamics
- Monte Carlo estimation, Metropolis-Hastings sampling, and MCMC diagnostics
Local Setup Recommendation
To execute and experiment with the code cells below on your local machine, ensure you have set up your isolated virtual environments and scientific libraries by following the detailed protocols in Unit 03: Environment Setup or run them in Google Colab.
1. Stochastic Processes and Random Walks
A random variable describes one uncertain quantity. A stochastic process describes a collection of random variables indexed by time. One realized sequence is a sample path, while the distribution of describes all values the process could occupy at time .
A random walk makes the idea concrete. Let , where each increment is with probability and with probability . The increments are random, but their mean and variance still let us summarize where many paths tend to go:
Time dependence matters because values from the same path are connected. Even when the increments are independent, contains the first four increments and contains those same four plus one more. Stochastic-process models describe both uncertainty at one time and the way uncertainty is carried forward.
Summarize a Biased Five-Step Walk
Start at . Each step is with probability and with probability . Find , , and trace the increments .
1.The increment mean is .
2.Because , .
3.Therefore and .
The supplied increments produce the path . One path ends at , while the average endpoint across many paths is .
A sample path is one outcome. An expectation summarizes the full distribution of possible paths.
2. Markov Chains and Transition Matrices
A process has the Markov property when the current state contains the information needed to model the next state: This does not say the states are independent. It says the past influences the next step through the present state.
For a finite-state chain, is the probability of moving from state to state , so every row of sums to . With row-vector distributions, one step is and steps are . The identity is the discrete Chapman-Kolmogorov relation.
A stationary distribution satisfies . Starting distributions converge to it only under suitable conditions such as irreducibility and aperiodicity. Unit 20 builds on this foundation by adding actions, rewards, and policies; Unit 19 keeps the transition process uncontrolled.
A Two-State Markov Chain Matches Its Transition Matrix
Read diagram labels
- S
- SUNNY
- state 0
- R
- RAINY
- state 1
- 0.2
- 0.3
- 0.8
- 0.7
- each state's outgoing probabilities sum to 1
import numpy as np
P = np.array([
[0.8, 0.2],
[0.3, 0.7],
])
p0 = np.array([1.0, 0.0])
p1 = p0 @ P
p2 = p1 @ P
stationary = np.array([0.6, 0.4])
print("p1:", np.round(p1, 2))
print("p2:", np.round(p2, 2))
print("pi:", stationary)
print("pi @ P:", np.round(stationary @ P, 2))p1: [0.8 0.2]
p2: [0.7 0.3]
pi: [0.6 0.4]
pi @ P: [0.6 0.4]Evolve a Two-State Markov Chain
Let the states be Sunny and Rainy, with and . Find and .
1.One step gives .
2.Multiply again: .
3.The Sunny probability is . The Rainy probability is .
After two steps, . The entries still sum to .
Solve for the Stationary Distribution
For the same transition matrix, find such that .
1.Use the Sunny coordinate: .
2.Collect terms: , so and .
3.The remaining probability is .
The stationary distribution is , and direct multiplication confirms .
3. SDEs and Euler-Maruyama
An ordinary differential equation fixes a path once its initial condition is known. A stochastic differential equation adds continuously arriving noise: The drift describes systematic motion, the diffusion coefficient controls noise strength, and a Brownian increment over a short interval satisfies .
Euler-Maruyama turns the continuous equation into small numerical steps. Write with , then use: Smaller time steps usually improve the approximation but require more computation.
Drift can depend on the current state. For example, pulls the process toward while noise keeps disturbing it. This is mean reversion. We will use the update rule directly rather than developing the proof machinery of Itô calculus.
import numpy as np
x = 1.0
drift = 0.2
diffusion = 0.5
dt = 0.04
standard_normal_steps = np.array([-1.0, 0.5, 0.0])
path = [x]
for epsilon in standard_normal_steps:
x = x + drift * dt + diffusion * np.sqrt(dt) * epsilon
path.append(x)
print([round(value, 3) for value in path])[1.0, 0.908, 0.966, 0.974]Take One Euler-Maruyama Step
Let , , , , and . Calculate .
1.The deterministic drift contribution is .
2.The Brownian increment is , so the noise contribution is .
3.Combine the start, drift, and noise: .
The drift nudges the state upward, but this particular random increment is larger and moves it downward to .
4. Diffusion and Score-Based Models
A diffusion model defines a forward process that adds small amounts of Gaussian noise. If and , a noisy sample can be drawn directly from the clean input: As decreases, less of remains and the noise term becomes stronger.
The reverse process is learned. A common objective trains a neural network to predict the sampled noise: Generation begins with noise and repeatedly applies learned denoising steps. Conventional sampling is iterative because each step depends on the current noisy state.
KL divergence also appears in the diffusion training derivation. At each step, it measures the gap between the forward process's tractable posterior and the learned reverse transition: These KL terms form part of the variational bound used to train a DDPM. The noise-prediction loss above is the common simplified, reweighted form of that objective. Unit 12 introduced KL divergence; here it measures how closely a denoising step matches the reverse distribution we want.
A score is the gradient , pointing toward directions where the log density increases. Score-based models connect diffusion to SDEs, while Langevin sampling combines a score-guided move with fresh Gaussian noise: Unit 21 compares diffusion with other generative-model families; this unit supplies the stochastic-process mechanics.
Forward Diffusion Adds Noise, the Learned Process Removes It
Read diagram labels
- FIXED FORWARD PROCESS q
- small Gaussian noise increments
- x₀
- clean data
- x₁
- slightly noisy
- xₜ
- partly noisy
- xT
- Gaussian noise
- β₁
- ⋯ βₜ
- ⋯ βT
- LEARNED REVERSE PROCESS pθ
- predict noise, then take one denoising step
- training pairs a known noise sample ε with the noisy state xₜ
Sample a Noisy Diffusion State
Let , , and . Calculate from the closed-form forward process.
1.The retained signal is .
2.The noise scale is .
3.The noise contribution is .
Therefore . This sample still retains most of the original signal because is large.
5. Monte Carlo Estimation
Monte Carlo methods replace a difficult expectation with an average over sampled values. For independent samples : The estimate changes from one sample set to another, but the law of large numbers makes it settle toward the true expectation as grows.
Estimate uncertainty with the sample variance and standard error . The typical error shrinks like , so reducing it by a factor of ten usually requires about one hundred times as many independent samples.
import numpy as np
samples = np.array([0.1, 0.4, 0.8, 0.9])
values = samples ** 2
estimate = values.mean()
standard_error = values.std(ddof=1) / np.sqrt(len(values))
print("h(x):", np.round(values, 2))
print("Estimate:", round(estimate, 3))
print("Standard error:", round(standard_error, 3))h(x): [0.01 0.16 0.64 0.81]
Estimate: 0.405
Standard error: 0.19Estimate an Expectation with Four Samples
Use samples to estimate and its standard error.
1.Square the samples: .
2.Average them: .
3.The sample standard deviation of the squared values is approximately .
Divide by : . Four samples give estimate , but the sizable standard error warns us not to overstate its precision.
6. Markov Chain Monte Carlo
Sometimes we can evaluate a target density up to a constant but cannot draw independent samples from it. Markov Chain Monte Carlo constructs a chain whose stationary distribution is the target. Metropolis-Hastings proposes from and accepts it with probability: For a symmetric proposal, the proposal terms cancel.
At each step, draw . Move to when ; otherwise repeat the current state. The repeated values are not an error. They preserve the target distribution, although they also make neighboring samples correlated.
Discard an initial warm-up period, inspect trace plots, compare multiple chains, and examine autocorrelation or effective sample size. A chain that barely moves can have thousands of stored values but very little independent information. Thinning reduces storage and correlation between retained draws, but it does not repair poor mixing.
import numpy as np
def log_target(x):
return -0.5 * x ** 2 # standard normal, constant omitted
current = 0.0
proposals = [1.2, 2.0]
uniforms = [0.3, 0.6]
path = [current]
for proposal, u in zip(proposals, uniforms):
probability = min(1.0, np.exp(log_target(proposal) - log_target(current)))
print("acceptance:", round(probability, 3), "u:", u)
if u < probability:
current = proposal
path.append(current)
print("path:", path)acceptance: 0.487 u: 0.3
acceptance: 0.278 u: 0.6
path: [0.0, 1.2, 1.2]Accept and Reject Metropolis Proposals
Target a standard normal density with a symmetric proposal. Start at , propose with , then propose with . Which moves are accepted?
1.For , the density ratio is .
2.Because , accept the first proposal and set the state to .
3.For , the ratio is .
Because , reject the second proposal. The recorded path is .
A rejection repeats the current state. Keeping that repeated value is part of the algorithm.
Interactive Practice Quiz
Test your understanding with instant feedback
What is a sample path of a stochastic process?
For the biased walk with , what is when ?
What does the Markov property say?
For and , what is ?
What condition defines a stationary distribution ?
Why does Euler-Maruyama multiply a standard normal draw by ?
With , , , , and , what is the Euler-Maruyama result?
In , what happens as becomes smaller?
How does ordinary Monte Carlo standard error usually scale with the number of independent samples ?
In Metropolis-Hastings, what should happen when a proposal is rejected?
Further Readings
Explore these highly recommended external references to deepen your understanding
The Monte Carlo Method
https://doi.org/10.1080/01621459.1949.10483310
Equation of State Calculations by Fast Computing Machines
https://doi.org/10.1063/1.1699114
Monte Carlo Sampling Methods Using Markov Chains
https://doi.org/10.1093/biomet/57.1.97
Denoising Diffusion Probabilistic Models
https://arxiv.org/abs/2006.11239
Score-Based Generative Modeling through Stochastic Differential Equations
https://arxiv.org/abs/2011.13456
