Guide To AI Logo
Unit 19

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 {Xt}t0\{X_t\}_{t\geq0} describes a collection of random variables indexed by time. One realized sequence x0,x1,x_0,x_1,\ldots is a sample path, while the distribution of XtX_t describes all values the process could occupy at time tt.

A random walk makes the idea concrete. Let Xt+1=Xt+ϵt+1X_{t+1}=X_t+\epsilon_{t+1}, where each increment is +1+1 with probability 0.60.6 and 1-1 with probability 0.40.4. The increments are random, but their mean and variance still let us summarize where many paths tend to go: E[Xn]=X0+nE[ϵ],Var(Xn)=nVar(ϵ).\mathbb E[X_n]=X_0+n\mathbb E[\epsilon],\qquad \operatorname{Var}(X_n)=n\operatorname{Var}(\epsilon).

Time dependence matters because values from the same path are connected. Even when the increments are independent, X4X_4 contains the first four increments and X5X_5 contains those same four plus one more. Stochastic-process models describe both uncertainty at one time and the way uncertainty is carried forward.

Worked Example 1

Summarize a Biased Five-Step Walk

Problem

Start at X0=0X_0=0. Each step is +1+1 with probability 0.60.6 and 1-1 with probability 0.40.4. Find E[X5]\mathbb E[X_5], Var(X5)\operatorname{Var}(X_5), and trace the increments [+1,1,+1,+1,+1][+1,-1,+1,+1,+1].

Step-by-step solution

1.The increment mean is E[ϵ]=0.6(1)+0.4(1)=0.2\mathbb E[\epsilon]=0.6(1)+0.4(-1)=0.2.

2.Because ϵ2=1\epsilon^2=1, Var(ϵ)=1(0.2)2=0.96\operatorname{Var}(\epsilon)=1-(0.2)^2=0.96.

3.Therefore E[X5]=5(0.2)=1\mathbb E[X_5]=5(0.2)=1 and Var(X5)=5(0.96)=4.8\operatorname{Var}(X_5)=5(0.96)=4.8.

Final answer and interpretation

The supplied increments produce the path 0101230\to1\to0\to1\to2\to3. One path ends at 33, while the average endpoint across many paths is 11.

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: P(Xt+1=jXt=i,Xt1,,X0)=P(Xt+1=jXt=i).P(X_{t+1}=j\mid X_t=i,X_{t-1},\ldots,X_0)=P(X_{t+1}=j\mid X_t=i). 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, PijP_{ij} is the probability of moving from state ii to state jj, so every row of PP sums to 11. With row-vector distributions, one step is pt+1=ptPp_{t+1}=p_tP and nn steps are pt+n=ptPnp_{t+n}=p_tP^n. The identity Pm+n=PmPnP^{m+n}=P^mP^n is the discrete Chapman-Kolmogorov relation.

A stationary distribution satisfies π=πP\pi=\pi P. 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

SSUNNYstate 0RRAINYstate 10.20.30.80.7each state's outgoing probabilities sum to 1
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
Jupyter Code Notebook Cell
Python 3 (ipykernel)
In [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))
Out [1]:
p1: [0.8 0.2]
p2: [0.7 0.3]
pi: [0.6 0.4]
pi @ P: [0.6 0.4]
Worked Example 1

Evolve a Two-State Markov Chain

Problem

Let the states be Sunny and Rainy, with P=[0.80.20.30.7]P=\begin{bmatrix}0.8&0.2\\0.3&0.7\end{bmatrix} and p0=[1,0]p_0=[1,0]. Find p1p_1 and p2p_2.

Step-by-step solution

1.One step gives p1=p0P=[1,0]P=[0.8,0.2]p_1=p_0P=[1,0]P=[0.8,0.2].

2.Multiply again: p2=[0.8,0.2]Pp_2=[0.8,0.2]P.

3.The Sunny probability is 0.8(0.8)+0.2(0.3)=0.700.8(0.8)+0.2(0.3)=0.70. The Rainy probability is 0.8(0.2)+0.2(0.7)=0.300.8(0.2)+0.2(0.7)=0.30.

Final answer and interpretation

After two steps, p2=[0.70,0.30]p_2=[0.70,0.30]. The entries still sum to 11.

Worked Example 2

Solve for the Stationary Distribution

Problem

For the same transition matrix, find π=[s,1s]\pi=[s,1-s] such that πP=π\pi P=\pi.

Step-by-step solution

1.Use the Sunny coordinate: s=0.8s+0.3(1s)s=0.8s+0.3(1-s).

2.Collect terms: s=0.5s+0.3s=0.5s+0.3, so 0.5s=0.30.5s=0.3 and s=0.6s=0.6.

3.The remaining probability is 1s=0.41-s=0.4.

Final answer and interpretation

The stationary distribution is π=[0.6,0.4]\pi=[0.6,0.4], and direct multiplication confirms πP=π\pi P=\pi.

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: dXt=f(Xt,t)dt+g(Xt,t)dWt.dX_t=f(X_t,t)\,dt+g(X_t,t)\,dW_t. The drift ff describes systematic motion, the diffusion coefficient gg controls noise strength, and a Brownian increment over a short interval satisfies ΔWN(0,Δt)\Delta W\sim\mathcal N(0,\Delta t).

Euler-Maruyama turns the continuous equation into small numerical steps. Write ΔWk=Δtϵk\Delta W_k=\sqrt{\Delta t}\,\epsilon_k with ϵkN(0,1)\epsilon_k\sim\mathcal N(0,1), then use: Xk+1=Xk+f(Xk,tk)Δt+g(Xk,tk)Δtϵk.X_{k+1}=X_k+f(X_k,t_k)\Delta t+g(X_k,t_k)\sqrt{\Delta t}\,\epsilon_k. Smaller time steps usually improve the approximation but require more computation.

Drift can depend on the current state. For example, dXt=θ(μXt)dt+σdWtdX_t=\theta(\mu-X_t)dt+\sigma dW_t pulls the process toward μ\mu 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.

Jupyter Code Notebook Cell
Python 3 (ipykernel)
In [1]:
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])
Out [1]:
[1.0, 0.908, 0.966, 0.974]
Worked Example 1

Take One Euler-Maruyama Step

Problem

Let X0=1X_0=1, f=0.2f=0.2, g=0.5g=0.5, Δt=0.04\Delta t=0.04, and ϵ0=1\epsilon_0=-1. Calculate X1X_1.

Step-by-step solution

1.The deterministic drift contribution is fΔt=0.2(0.04)=0.008f\Delta t=0.2(0.04)=0.008.

2.The Brownian increment is 0.04(1)=0.2\sqrt{0.04}(-1)=-0.2, so the noise contribution is 0.5(0.2)=0.10.5(-0.2)=-0.1.

3.Combine the start, drift, and noise: X1=1+0.0080.1=0.908X_1=1+0.008-0.1=0.908.

Final answer and interpretation

The drift nudges the state upward, but this particular random increment is larger and moves it downward to 0.9080.908.

4. Diffusion and Score-Based Models

A diffusion model defines a forward process that adds small amounts of Gaussian noise. If αt=1βt\alpha_t=1-\beta_t and αˉt=s=1tαs\bar\alpha_t=\prod_{s=1}^t\alpha_s, a noisy sample can be drawn directly from the clean input: xt=αˉtx0+1αˉtϵ,ϵN(0,I).x_t=\sqrt{\bar\alpha_t}x_0+\sqrt{1-\bar\alpha_t}\,\epsilon,\qquad \epsilon\sim\mathcal N(0,I). As αˉt\bar\alpha_t decreases, less of x0x_0 remains and the noise term becomes stronger.

The reverse process is learned. A common objective trains a neural network to predict the sampled noise: Lnoise=Ex0,t,ϵ[ϵϵθ(xt,t)22].\mathcal L_{noise}=\mathbb E_{x_0,t,\epsilon}\left[\lVert\epsilon-\epsilon_\theta(x_t,t)\rVert_2^2\right]. 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: DKL ⁣(q(xt1xt,x0)pθ(xt1xt)).D_{KL}\!\left(q(x_{t-1}\mid x_t,x_0)\,\|\,p_\theta(x_{t-1}\mid x_t)\right). 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 xlogpt(x)\nabla_x\log p_t(x), 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: xk+1=xk+η2xlogp(xk)+ηξk.x_{k+1}=x_k+\frac{\eta}{2}\nabla_x\log p(x_k)+\sqrt{\eta}\,\xi_k. 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

FIXED FORWARD PROCESS qsmall Gaussian noise incrementsx₀clean datax₁slightly noisyxₜpartly noisyxTGaussian noiseβ₁⋯ βₜ⋯ βTLEARNED REVERSE PROCESS pθpredict noise, then take one denoising steptraining pairs a known noise sample ε with the noisy state xₜ
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ₜ
Worked Example 1

Sample a Noisy Diffusion State

Problem

Let x0=2x_0=2, αˉt=0.81\bar\alpha_t=0.81, and ϵ=0.5\epsilon=-0.5. Calculate xtx_t from the closed-form forward process.

Step-by-step solution

1.The retained signal is 0.81(2)=0.9(2)=1.8\sqrt{0.81}(2)=0.9(2)=1.8.

2.The noise scale is 10.81=0.190.4359\sqrt{1-0.81}=\sqrt{0.19}\approx0.4359.

3.The noise contribution is 0.4359(0.5)0.21790.4359(-0.5)\approx-0.2179.

Final answer and interpretation

Therefore xt1.80.2179=1.5821x_t\approx1.8-0.2179=1.5821. This sample still retains most of the original signal because αˉt\bar\alpha_t is large.

5. Monte Carlo Estimation

Monte Carlo methods replace a difficult expectation with an average over sampled values. For independent samples x1,,xNp(x)x_1,\ldots,x_N\sim p(x): Ep[h(X)]μ^N=1Ni=1Nh(xi).\mathbb E_p[h(X)]\approx\hat\mu_N=\frac{1}{N}\sum_{i=1}^N h(x_i). The estimate changes from one sample set to another, but the law of large numbers makes it settle toward the true expectation as NN grows.

Estimate uncertainty with the sample variance sh2=1N1i(h(xi)μ^N)2s_h^2=\frac{1}{N-1}\sum_i(h(x_i)-\hat\mu_N)^2 and standard error SE(μ^N)=sh/N\operatorname{SE}(\hat\mu_N)=s_h/\sqrt N. The typical error shrinks like O(N1/2)O(N^{-1/2}), so reducing it by a factor of ten usually requires about one hundred times as many independent samples.

Jupyter Code Notebook Cell
Python 3 (ipykernel)
In [1]:
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))
Out [1]:
h(x): [0.01 0.16 0.64 0.81]
Estimate: 0.405
Standard error: 0.19
Worked Example 1

Estimate an Expectation with Four Samples

Problem

Use samples [0.1,0.4,0.8,0.9][0.1,0.4,0.8,0.9] to estimate E[X2]\mathbb E[X^2] and its standard error.

Step-by-step solution

1.Square the samples: h(xi)=[0.01,0.16,0.64,0.81]h(x_i)=[0.01,0.16,0.64,0.81].

2.Average them: μ^=(0.01+0.16+0.64+0.81)/4=0.405\hat\mu=(0.01+0.16+0.64+0.81)/4=0.405.

3.The sample standard deviation of the squared values is approximately 0.3810.381.

Final answer and interpretation

Divide by 4=2\sqrt4=2: SE(μ^)0.190\operatorname{SE}(\hat\mu)\approx0.190. Four samples give estimate 0.4050.405, 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 xx' from q(xx)q(x'\mid x) and accepts it with probability: a(x,x)=min(1,p(x)q(xx)p(x)q(xx)).a(x,x')=\min\left(1,\frac{p(x')q(x\mid x')}{p(x)q(x'\mid x)}\right). For a symmetric proposal, the proposal terms cancel.

At each step, draw uUniform(0,1)u\sim\operatorname{Uniform}(0,1). Move to xx' when u<au<a; 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.

Jupyter Code Notebook Cell
Python 3 (ipykernel)
In [1]:
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)
Out [1]:
acceptance: 0.487 u: 0.3
acceptance: 0.278 u: 0.6
path: [0.0, 1.2, 1.2]
Worked Example 1

Accept and Reject Metropolis Proposals

Problem

Target a standard normal density with a symmetric proposal. Start at x=0x=0, propose 1.21.2 with u=0.3u=0.3, then propose 2.02.0 with u=0.6u=0.6. Which moves are accepted?

Step-by-step solution

1.For 01.20\to1.2, the density ratio is exp(1.22/2)/exp(0)=exp(0.72)0.487\exp(-1.2^2/2)/\exp(0)=\exp(-0.72)\approx0.487.

2.Because 0.3<0.4870.3<0.487, accept the first proposal and set the state to 1.21.2.

3.For 1.22.01.2\to2.0, the ratio is exp(22/2+1.22/2)=exp(1.28)0.278\exp(-2^2/2+1.2^2/2)=\exp(-1.28)\approx0.278.

Final answer and interpretation

Because 0.6>0.2780.6>0.278, reject the second proposal. The recorded path is [0,1.2,1.2][0,1.2,1.2].

A rejection repeats the current state. Keeping that repeated value is part of the algorithm.

Interactive Practice Quiz

Test your understanding with instant feedback

QUESTION 01

What is a sample path of a stochastic process?

QUESTION 02

For the biased walk with P(ϵ=1)=0.6P(\epsilon=1)=0.6, what is E[X5]\mathbb E[X_5] when X0=0X_0=0?

QUESTION 03

What does the Markov property say?

QUESTION 04

For p0=[1,0]p_0=[1,0] and P=[0.80.20.30.7]P=\begin{bmatrix}0.8&0.2\\0.3&0.7\end{bmatrix}, what is p2p_2?

QUESTION 05

What condition defines a stationary distribution π\pi?

QUESTION 06

Why does Euler-Maruyama multiply a standard normal draw by Δt\sqrt{\Delta t}?

QUESTION 07

With X0=1X_0=1, f=0.2f=0.2, g=0.5g=0.5, Δt=0.04\Delta t=0.04, and ϵ=1\epsilon=-1, what is the Euler-Maruyama result?

QUESTION 08

In xt=αˉtx0+1αˉtϵx_t=\sqrt{\bar\alpha_t}x_0+\sqrt{1-\bar\alpha_t}\epsilon, what happens as αˉt\bar\alpha_t becomes smaller?

QUESTION 09

How does ordinary Monte Carlo standard error usually scale with the number of independent samples NN?

QUESTION 10

In Metropolis-Hastings, what should happen when a proposal is rejected?