Overview
A stochastic process is a whole collection of random variables, one for each time or input, tied together by rules about how they relate. The simplest is a random walk: start at zero and add a random step at each tick. Shrink the steps and speed up the clock in the right proportion and you get Brownian motion, a continuous jittery path. Variations add a trend, keep the path positive, or pull it back toward a mean. A Gaussian process takes a different view. It puts a probability distribution on functions themselves, by saying how strongly the values at any two inputs move together, and that lets you fit a curve to data with error bars.
A short history
Robert Brown described the irregular motion of particles in water in 1827. Louis Bachelier modelled stock prices as a random motion in his 1900 thesis, Albert Einstein explained Brownian motion physically in 1905, and Norbert Wiener gave it a rigorous mathematical construction in 1923. Gaussian processes entered prediction through kriging in mining geology in the 1950s and 1960s, and became a common machine learning tool in the 2000s.
How it works
- Random walk: start at a value and repeatedly add with probability or otherwise. The position is the running sum of the steps.
- Brownian motion: replace each step by an independent normal draw with mean and variance , and accumulate.
- Geometric Brownian motion: simulate Brownian motion for the logarithm and exponentiate, which keeps the path positive.
- Ornstein-Uhlenbeck process: at each step move a fixed fraction of the way back toward a long-run mean, then add noise.
- Gaussian process prior: choose a kernel that gives the covariance between function values at any two inputs, build the covariance matrix and draw a correlated normal vector.
- Gaussian process posterior: condition that joint normal distribution on observed points to get a predicted mean and covariance at new inputs.
Watch out for
- The spread of a random walk or Brownian motion grows without bound, like . One path wandering far from zero is expected, not a sign of a trend.
- Brownian increments scale with , not . Scaling the noise by is a common bug that makes paths far too smooth.
- The average of geometric Brownian motion grows at rate , but a typical path grows at . With high volatility most paths can fall while the average rises.
- Exact Gaussian process regression factorizes an matrix, which costs on the order of operations. It is impractical beyond a few thousand training points without approximations.
- Kernel matrices are often close to singular. The jitter added to the diagonal makes the factorization succeed, and too little of it produces errors or noisy output.
Use cases
When to use it
Modelling noise that accumulates over time (prices, sensor drift, diffusion), building the forward process of diffusion models, and doing regression with calibrated uncertainty on small data sets.
In industry
- Finance
- The Black-Scholes option pricing model assumes the share price follows geometric Brownian motion.
- Mining and geoscience
- Kriging, which is Gaussian process regression, estimates ore grade or pollutant levels between drill holes and reports the uncertainty.
- Machine learning
- Bayesian optimisation uses a Gaussian process as a surrogate for an expensive function when tuning hyperparameters.
- Physics and biology
- Diffusion of molecules and animal movement paths are modelled as random walks and Brownian motion.
Choosing it: what must hold
- A quantity indexed by time or by an input, where values at nearby indices are related.
- A stated dependence structure: independent increments for a walk, or a covariance function for a Gaussian process.
- For Gaussian process regression, a small or medium data set, because exact fitting cost grows with the cube of the number of points.
When to choose something else
| If | Use instead |
|---|---|
| States are a finite set with fixed transition probabilities | Markov chains |
| You have a regularly sampled series with trend and seasonality to forecast | Time series analysis |
| The data set is too large for an exact Gaussian process | A sparse Gaussian process, or a tree or neural model |
Math foundations
Simple random walk
Each step is with probability and otherwise. Means and variances of independent steps add, so the standard deviation grows like .
Brownian motion with drift
Increments over separate time intervals are independent and normal. The variance, not the standard deviation, is proportional to elapsed time. This is the limit of a random walk with many tiny steps.
Geometric Brownian motion
The logarithm of is a Brownian motion, so stays positive and changes by random percentages. The correction is what makes the mean grow at exactly rate .
Ornstein-Uhlenbeck process
The exact one-step rule for the mean-reverting equation . The gap to the mean decays by a fixed factor each step, and in the long run is normal with mean and variance .
RBF kernel
The covariance between function values at two inputs. Nearby inputs have almost the same value, and inputs further apart than a few length scales are almost unrelated. A Gaussian process is defined by saying that any finite set of function values is jointly normal with this covariance.
Gaussian process posterior
Conditioning a joint normal on the observed values. The mean is a weighted combination of the training targets, and the covariance is the prior covariance minus what the data explained. The template computes both with a Cholesky factorization.
Symbols
- the position of the random walk after steps
- the step size and the probability of a step up
- the value of a continuous-time process at time
- the time between two simulated points (dt in the config)
- the drift and the volatility
- standard Brownian motion: zero drift and unit volatility
- the speed of mean reversion and the long-run mean
- the kernel: covariance between function values at and
- the kernel length scale and signal variance
- the kernel matrix between training inputs
- the kernel matrices between test and training inputs, and among test inputs
- the observed training targets
- the variance of the observation noise
- the posterior mean and covariance at the test inputs
Worked by hand
First take a symmetric random walk with and step after steps. Then take standard Brownian motion (, ) with the default after 1000 steps, which is time .
After 100 fair steps the walk is typically about 10 away from the start, not 100 and not 0. The Brownian path at time 10 is typically about 3.2 away. In both cases the spread grows with the square root of elapsed time.
Visual example
Loading the example.
Try this
- Press Draw again a few times on the random walk: the paths change, the band does not.
- Switch to Brownian motion and give it a drift of 0.5. Watch the centre line outrun the widening band.
- Choose Ornstein-Uhlenbeck and raise θ: the paths fall from 3 to the long run mean faster and the band levels off sooner.
Code sample
import numpy as np
from impl import StochasticProcesses
from config import StochasticProcessesConfig
sp = StochasticProcesses(StochasticProcessesConfig(n_steps=250, n_paths=1000, dt=1 / 250))
w = sp.brownian_motion() # (1000, 251); w[:, -1] has variance 1 (one unit of time)
s = sp.geometric_brownian_motion(start=100.0, drift=0.05, volatility=0.2) # mean of s[:, -1] is 100 e^0.05
x = np.array([0.0, 1.0, 2.0])
mean, cov = sp.gp_posterior(x, np.sin(x), np.linspace(0, 2, 5)) # passes through the three pointsRead the implementation (120 lines)
"""Stochastic processes: random walks, Brownian motion and relatives, Gaussian processes.
Simulators return whole paths as arrays (n_paths, n_steps + 1). Brownian motion, geometric Brownian motion and
the Ornstein-Uhlenbeck process are sampled from their exact transition laws, so the step size does not bias
them. The Gaussian process part draws functions from an RBF prior and computes the exact posterior given data.
"""
from __future__ import annotations
import math
import numpy as np
try:
from .config import StochasticProcessesConfig
except ImportError: # run from the template's own folder
from config import StochasticProcessesConfig
class StochasticProcesses:
"""Path simulators and Gaussian process tools sharing one seeded generator (`self.rng`)."""
def __init__(self, config: StochasticProcessesConfig | None = None) -> None:
self.config = config or StochasticProcessesConfig()
self.rng = np.random.default_rng(self.config.seed)
def times(self) -> np.ndarray:
"""Time of every path point: 0, dt, 2 dt, ..., array (n_steps + 1,)."""
return np.arange(self.config.n_steps + 1) * self.config.dt
def _shape(self) -> tuple[int, int]:
return self.config.n_paths, self.config.n_steps
@staticmethod
def _from_increments(increments: np.ndarray, start: float) -> np.ndarray:
zeros = np.zeros((increments.shape[0], 1))
return start + np.concatenate([zeros, np.cumsum(increments, axis=1)], axis=1)
def random_walk(self, p_up: float = 0.5, step: float = 1.0, start: float = 0.0) -> np.ndarray:
"""Simple random walk: each step is +step with probability p_up, else -step.
Returns array (n_paths, n_steps + 1). After n steps the mean is n step (2 p_up - 1) and the variance
is 4 n step^2 p_up (1 - p_up).
"""
if not 0 <= p_up <= 1:
raise ValueError("p_up must lie in [0, 1]")
moves = np.where(self.rng.random(self._shape()) < p_up, step, -step)
return self._from_increments(moves, start)
def brownian_motion(self, drift: float = 0.0, volatility: float = 1.0, start: float = 0.0) -> np.ndarray:
"""Brownian motion with drift: X_t = start + drift t + volatility W_t.
Returns array (n_paths, n_steps + 1). Increments over dt are independent N(drift dt, volatility^2 dt).
"""
dt = self.config.dt
increments = drift * dt + volatility * math.sqrt(dt) * self.rng.normal(size=self._shape())
return self._from_increments(increments, start)
def geometric_brownian_motion(self, start: float = 1.0, drift: float = 0.0, volatility: float = 0.2) -> np.ndarray:
"""Geometric Brownian motion S_t = start exp((drift - volatility^2 / 2) t + volatility W_t).
Always positive, with E[S_t] = start exp(drift t). Returns array (n_paths, n_steps + 1).
"""
if start <= 0:
raise ValueError("start must be positive")
log_paths = self.brownian_motion(drift - 0.5 * volatility**2, volatility)
return start * np.exp(log_paths)
def ornstein_uhlenbeck(self, theta: float = 1.0, mean: float = 0.0, volatility: float = 1.0,
start: float = 0.0) -> np.ndarray:
"""Mean-reverting process dX = theta (mean - X) dt + volatility dW, sampled exactly.
theta > 0 is the speed of reversion. The stationary distribution is N(mean, volatility^2 / (2 theta)).
Returns array (n_paths, n_steps + 1).
"""
if theta <= 0:
raise ValueError("theta must be positive")
decay = math.exp(-theta * self.config.dt)
noise_std = volatility * math.sqrt((1.0 - decay**2) / (2.0 * theta))
noise = noise_std * self.rng.normal(size=self._shape())
paths = np.empty((self.config.n_paths, self.config.n_steps + 1))
paths[:, 0] = start
for t in range(self.config.n_steps):
paths[:, t + 1] = mean + (paths[:, t] - mean) * decay + noise[:, t]
return paths
def poisson_process(self, rate: float = 1.0) -> np.ndarray:
"""Counting process N_t with independent Poisson(rate dt) increments. Returns array (n_paths, n_steps + 1)."""
if rate <= 0:
raise ValueError("rate must be positive")
return self._from_increments(self.rng.poisson(rate * self.config.dt, size=self._shape()).astype(float), 0.0)
def rbf_kernel(self, xa, xb) -> np.ndarray:
"""Squared-exponential kernel k(a, b) = signal_variance exp(-|a - b|^2 / (2 length_scale^2)).
xa: array (n,) or (n, d); xb: array (m,) or (m, d). Returns array (n, m).
"""
xa = np.asarray(xa, dtype=float).reshape(len(xa), -1)
xb = np.asarray(xb, dtype=float).reshape(len(xb), -1)
sq = (xa**2).sum(axis=1)[:, None] + (xb**2).sum(axis=1)[None, :] - 2.0 * xa @ xb.T
return self.config.signal_variance * np.exp(-0.5 * np.maximum(sq, 0.0) / self.config.length_scale**2)
def gp_sample(self, x, n_samples: int = 1) -> np.ndarray:
"""Draw functions from the zero-mean Gaussian process prior at inputs x. Returns array (n_samples, n)."""
K = self.rbf_kernel(x, x)
L = np.linalg.cholesky(K + max(self.config.jitter, 1e-10) * self.config.signal_variance * np.eye(len(K)))
return (L @ self.rng.normal(size=(len(K), n_samples))).T
def gp_posterior(self, x_train, y_train, x_test, noise_variance: float = 0.0) -> tuple[np.ndarray, np.ndarray]:
"""Gaussian process regression: the distribution of f(x_test) given noisy observations of f.
x_train: array (n,) or (n, d); y_train: array (n,); x_test: array (m,) or (m, d).
noise_variance: variance of the observation noise on y_train.
Returns (mean array (m,), covariance array (m, m)).
"""
y = np.asarray(y_train, dtype=float).ravel()
K = self.rbf_kernel(x_train, x_train) + (noise_variance + self.config.jitter) * np.eye(y.size)
K_star = self.rbf_kernel(x_test, x_train)
L = np.linalg.cholesky(K)
alpha = np.linalg.solve(L.T, np.linalg.solve(L, y))
v = np.linalg.solve(L, K_star.T)
return K_star @ alpha, self.rbf_kernel(x_test, x_test) - v.T @ v- Repository
- Not published yet
- Needs
- Python 3.10 and NumPy
- Tests
- 9, run with
python3 -m unittest -v
Practice
Create StochasticProcesses with StochasticProcessesConfig(n_paths=2000, n_steps=1000). Call random_walk and brownian_motion and compare the variance of the final column with the formulas. Call ornstein_uhlenbeck(theta=2.0, start=5.0) and check the late-time variance against . Then fit gp_posterior to five points of a sine curve and plot the mean with two standard deviations from the diagonal of the covariance.
Check on learning
- Halve the time step of a Brownian simulation. By what factor must the standard deviation of each increment change, and what goes wrong if you scale it by ?
A way to think about it
Variances of independent increments add. Work out the total variance at a fixed time for both scalings as the step count doubles.
- For geometric Brownian motion with and , the mean grows but most paths shrink. How can both hold?
A way to think about it
Compare with . A few very large paths can lift an average that the median path never reaches.
- What happens to draws from a Gaussian process prior when the length scale is made very small, and when it is made very large?
A way to think about it
The kernel decides how far apart two inputs can be and still agree. Consider the limits where no pair agrees and where every pair does.
- Away from all training points, what do the Gaussian process posterior mean and variance return to, and why is that sensible?
A way to think about it
Look at when the test input is many length scales from the data. With no nearby evidence the prior is all that is left.
- An Ornstein-Uhlenbeck path and a Brownian path look alike over a short window. Which measurement over a long window tells them apart?
A way to think about it
Track the variance across many paths as time grows. One keeps growing in proportion to time and the other levels off.