AI Wiki中文/EN

Gaussian processes: a prediction with two variances

高斯过程

Derive a two-point Gaussian-process prediction, solve it with Cholesky and distinguish latent, observation and numerical uncertainty.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Predict a curve and how uncertain it is

You observe a sensor at two inputs: x=0 gives y=1, and x=1 gives y=−1. A straight line joins the readings, but it says little about what other curves could plausibly explain noisy data. A Gaussian process places a distribution over functions, then conditions that distribution on observations.

“Gaussian” concerns the joint distribution of any finite collection of function values. It does not require the curve itself to have a bell shape. A covariance kernel expresses which inputs should have related values. Read Gaussian distributions and linear systems first.

A kernel determines finite joint distributions

Take a zero-mean prior with an RBF kernel, independent Gaussian observation noise, and fixed hyperparameters:

f∼GP(0,k),k(x,x′)=s2exp⁡(−(x−x′)22ℓ2),yi=f(xi)+ϵi,ϵi∼iidN(0,σn2).f\sim\mathcal{GP}(0,k),\qquad k(x,x')=s^2\exp\left(-\frac{(x-x')^2}{2\ell^2}\right),\qquad y_i=f(x_i)+\epsilon_i,\quad\epsilon_i\overset{\mathrm{iid}}\sim\mathcal N(0,\sigma_n^2).

A valid kernel gives positive-semidefinite Gram matrices for all finite input sets. The length scale ℓ controls how quickly covariance falls with distance; s² sets prior marginal variance. The Gaussian likelihood makes conditioning analytic. A different likelihood may require approximate inference.

Let K contain training covariances, C=K+σ_n²I, and k_* contain covariances between training inputs and one test input. Assuming C is positive definite, Gaussian conditioning gives:

μ∗=k∗⊤C−1y,vf=k(x∗,x∗)−k∗⊤C−1k∗,vy=vf+σn2.\mu_*=k_*^\top C^{-1}y,\qquad v_f=k(x_*,x_*)-k_*^\top C^{-1}k_*,\qquad v_y=v_f+\sigma_n^2.

The last addition is for a fresh, independently noisy observation, not for the latent function. Even at a training input, uncertainty about a new measurement remains when observation noise is nonzero. GPML Chapter 2, Section 2.2, equations 2.18–2.26, develops the joint Gaussian and predictive expressions.

Solve the two-point case on paper

Set s²=1, σ_n²=1/4 and ℓ=√(1/(2log2)), so the covariance between 0 and 1 is 1/2. The training covariance and solution are:

C=(5/41/21/25/4),C−1=(20/21−8/21−8/2120/21),C−1(1−1)=(4/3−4/3).C=\begin{pmatrix}5/4&1/2\\1/2&5/4\end{pmatrix},\qquad C^{-1}=\begin{pmatrix}20/21&-8/21\\-8/21&20/21\end{pmatrix},\qquad C^{-1}\begin{pmatrix}1\\-1\end{pmatrix} =\begin{pmatrix}4/3\\-4/3\end{pmatrix}.

At x_=0, k_=(1,1/2), giving mean 2/3 and latent variance 4/21. Fresh-observation variance is 4/21+1/4=37/84. At x_*=1 the mean changes sign, while both variances are unchanged. The readings are not interpolated because the model allows measurement noise.

Solve linear systems instead of forming an inverse

This complete Python 3.12 program uses NumPy 1.26.4. Cholesky factors C=LLᵀ; two solves obtain α=C⁻¹y, and solving Lv=k_* yields k_ᵀC⁻¹k_=vᵀv. The displayed inverse above is an independent hand calculation, not the implementation strategy. GPML Algorithm 2.1 uses this approach; NumPy 1.26’s Cholesky documentation specifies positive-definite inputs and failure behavior.

import numpy as np
from math import isfinite, log, sqrt
from numbers import Real


def gp_predict(x, y, test, length=1.0, signal_variance=1.0,
               noise_variance=0.25, jitter=0.0):
    def scalar(v, low, high, name, strict=False):
        if isinstance(v,(bool,np.bool_)) or not isinstance(v,Real) or not isfinite(v) or not low<=v<=high or (strict and v==low):
            raise ValueError('invalid '+name)
        return float(v)
    def vector(values, cap, bound, name):
        values=list(values)
        if not 1<=len(values)<=cap:raise ValueError('invalid '+name+' length')
        for v in values:scalar(v,-bound,bound,name)
        return np.array(values,dtype=float)
    x=vector(x,32,1000,'training inputs');y=vector(y,32,1e6,'targets')
    test=vector(test,64,1000,'test inputs')
    if len(x)!=len(y):raise ValueError('training inputs and targets must match')
    length=scalar(length,1e-3,1e3,'length scale')
    signal_variance=scalar(signal_variance,0,1e3,'signal variance',True)
    noise_variance=scalar(noise_variance,0,1e3,'noise variance')
    jitter=scalar(jitter,0,.01,'jitter')
    def kernel(a,b):return signal_variance*np.exp(-.5*((a[:,None]-b[None,:])/length)**2)
    covariance=kernel(x,x)+(noise_variance+jitter)*np.eye(len(x))
    lower=np.linalg.cholesky(covariance)
    alpha=np.linalg.solve(lower.T,np.linalg.solve(lower,y))
    cross=kernel(x,test);v=np.linalg.solve(lower,cross)
    mean=cross.T@alpha
    latent=signal_variance-np.sum(v*v,axis=0)
    if np.any(latent < -1e-10*signal_variance):
        raise ArithmeticError('materially negative predictive variance')
    latent=np.maximum(latent,0)
    return mean,latent,latent+noise_variance


if __name__=='__main__':
    length=sqrt(1/(2*log(2)))
    mean,latent,observed=gp_predict([0,1],[1,-1],[0,1],length=length)
    print('RBF length scale:',f'{length:.12f}')
    print('posterior means:',*[f'{v:.12f}' for v in mean])
    print('latent variances:',*[f'{v:.12f}' for v in latent])
    print('fresh-observation variances:',*[f'{v:.12f}' for v in observed])
    exact=gp_predict([0,1],[1,-1],[0,1],length=length,noise_variance=0)
    print('noise-free means:',*[f'{v:.12f}' for v in exact[0]])
    print('noise-free maximum latent variance:',f'{max(exact[1]):.3g}')

Output:

RBF length scale: 0.849321800288
posterior means: 0.666666666667 -0.666666666667
latent variances: 0.190476190476 0.190476190476
fresh-observation variances: 0.440476190476 0.440476190476
noise-free means: 1.000000000000 -1.000000000000
noise-free maximum latent variance: 0

Inputs are one-dimensional real numeric sequences: up to 32 training points and 64 test points, within the bounds enforced by the code. Hyperparameters are supplied, not learned. Zero noise is allowed when the training Gram matrix is positive definite. Duplicate noiseless training inputs make it singular and raise LinAlgError; the program does not silently add regularization.

The optional jitter adds an explicitly requested diagonal perturbation to the training matrix. It changes the numerical problem. It is not added to fresh-observation variance as if it were measured sensor noise. Materially negative predictive variance raises an error; tiny negative roundoff values are clipped to zero. No clipping is used to conceal a failed factorization.

Dense training costs O(n³) time and O(n²) storage. Solving for m test covariances costs O(n²m), with O(nm) intermediate storage; only marginal variances are returned. np.linalg.solve is a general dense solver, so dedicated triangular solvers can improve constants. This example does not implement sparse inducing-point or iterative approximations.

Uncertainty is conditional on modeling choices

A pointwise 95% posterior interval for the latent value is mean±1.96√v_f under this Gaussian model. It is conditional on the kernel, hyperparameters, noise assumptions and observations. It is neither a simultaneous 95% band for an entire function nor a guarantee of 95% frequentist coverage under model misspecification.

Far from all training points, this RBF kernel makes k_* approach zero. The mean returns toward the prior mean zero and latent variance toward s². A confident extrapolation may instead come from a long length scale; it should be evaluated against the application, not accepted because a formula returned a small variance.

Changing input units without adjusting ℓ changes the prior. Choosing hyperparameters after extensive trial and error, then treating them as known, omits uncertainty about that choice. Predictive checks and held-out evaluation remain useful even when the conditional posterior calculation is exact.

Which uncertainty are you reporting?

  1. What is the predicted mean at the first training input in the noisy example?

Answer 1: 2/3, not 1; the observation can contain noise.

  1. What is the difference between fresh-observation and latent variance?

Answer 2: The independent noise variance 1/4, giving 37/84 versus 4/21.

  1. What happens with duplicated inputs and zero noise, without jitter?

Answer 3: The training covariance is singular and Cholesky fails. An explicit model or numerical change is required.

  1. Does a pointwise 95% interval cover the entire function with 95% probability?

Answer 4: No. Pointwise and simultaneous coverage are different statements.

Test the prior, not just the solver

Project: sweep ℓ while keeping the data fixed. Plot posterior means and both types of marginal interval at a grid of test inputs. Then rescale all inputs by 100 and ℓ by 100; predictions should agree up to roundoff. Keep the test grid fixed before evaluating held-out observations.

Gaussian processes are useful for small-data regression, surrogate modeling and Bayesian optimization. Kernel design, scalable approximations and non-Gaussian likelihoods extend the basic calculation. Bayesian decision theory explains why a predictive distribution still needs a loss function before it determines an action.

Make a prediction, then check

Why is fresh-observation variance larger in the example?

Choose one answer

Learning objectives

  • Derive latent and observation predictive variances.
  • Verify a Cholesky implementation against a two-point analytic solution.
  • Explain kernel assumptions, jitter and conditional uncertainty.

Prerequisites & connections

Explore related knowledge →

References

  1. Gaussian Processes for Machine Learning — Chapter 2: Regression
    Carl Edward Rasmussen; Christopher K. I. Williams · 2006
  2. numpy.linalg.cholesky — NumPy 1.26
    NumPy developers

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-06 · Codex single-agent authored technical review: cited primary-source scope, explicit assumptions, original calculations and counterexamples, runnable tests and bilingual review; not independent human or second-agent review.

  • Single-agent authored technical review: bounded primary-source locations, assumptions, original derivations, exact/literal references and matching bilingual equations/examples/exercises. Not independent human or second-agent review.
  • Four focused CPython3.12.4 tests passed per chapter. IS and decisions use exact fractions; VI and GP use floating-point calculations checked against analytic constants, invariance and meaningful boundaries. NumPy1.26.4 used for GP.
  • Promoted the full prose, equations, code and exercises. Tests read formal MDX only; removed temporary fallbacks/draft skips and updated review assertion to checked. Algorithm and independent references are unchanged; final record binds both locale hashes.
  • Publication navigation points published topics to complete articles and removes corresponding pending wording, retaining directory entries for unwritten targets. Principles, equations, programs and exercises are unchanged; final article SHA values rebound.

Source locations checked:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.