Predictive coding
预测编码
Infer two levels of hidden state from prediction errors, and check the answer with a linear solve.
predictive-codingStart with the problem
You hear a partly obscured word. A possible sentence suggests what the missing sound might be; the sound you actually hear can force that interpretation to change. Predictive coding studies this kind of interaction with a hierarchy: higher states predict lower states, and discrepancies help revise the states. It is a family of models, not a demonstrated universal algorithm of the brain.
Rao and Ballard’s 1999 visual-cortex model used downward predictions and upward error signals to interpret some receptive-field effects. Their account distinguishes fast inference of the current input from slower adaptation of model parameters. Predictive coding in the visual cortex: a functional interpretation of some extra-classical receptive-field effects
Here we solve a two-level linear Gaussian model. Every error, state update and final answer can be checked against a four-by-four linear system. This provides a precise computational example while keeping the neuroscience claim at its actual scope.
Definitions and derivation
The observation is , lower latent state , upper state , and fixed prediction matrices . Assume is Gaussian with mean and identity covariance; has mean and precision ; has zero mean and precision . Positive precision is inverse variance. Dropping constants gives the negative log posterior:
A lower state receives two pressures: explain the observation and respect the upper prediction. Differentiating each squared residual yields:
For , this quadratic has a symmetric precision matrix. With it is positive definite, so the posterior mode is unique even if A is rank deficient:
The step bound makes every eigenmode of fixed-step gradient descent contract. It applies to this fixed positive-definite quadratic, not all nonlinear predictive-coding networks. Holding inferred states fixed, parameter gradients are for A and for B. Updating those matrices is learning; updating r and s for the current x is inference. The Gaussian hierarchy and error-based update interpretation connect to Bogacz’s tutorial; the numbers and derivation here are our constructed model. A tutorial on the free-energy framework for modelling perception and learning
Run the calculation
Run CPython 3.12.4 with NumPy 1.26.4. We start all four state entries at zero, use alpha 2 and prior precision 0.7, and take 400 steps of size 0.05. Energy falls from 0.625 to 0.280793808. The state differs from the direct linear-system solution by about 5.54e−8. The computed safe step upper bound is 0.350946671. Parameter gradients are printed at the final state, but the program does not run a parameter-learning loop.
import numpy as np
A=np.array([[1.,.4],[-.2,1.2]]);B=np.array([[.8,.1],[.3,1.]]);X=np.array([1.,-.5]);ALPHA=2.;PRIOR=.7
def energy_gradient(state):
r,s=np.asarray(state[:2]),np.asarray(state[2:]);e0=X-A@r;e1=r-B@s;energy=.5*(e0@e0+ALPHA*(e1@e1)+PRIOR*(s@s));gradient=np.r_[-A.T@e0+ALPHA*e1,-ALPHA*B.T@e1+PRIOR*s]
return float(energy),gradient,e0,e1
def precision():return np.block([[A.T@A+ALPHA*np.eye(2),-ALPHA*B],[-ALPHA*B.T,ALPHA*B.T@B+PRIOR*np.eye(2)]])
def infer(steps=400,rate=.05):
z=np.zeros(4);trace=[]
for _ in range(steps):energy,g,_,_=energy_gradient(z);trace.append(energy);z-=rate*g
return z,trace
if __name__=='__main__':
z,trace=infer();exact=np.linalg.solve(precision(),np.r_[A.T@X,[0.,0.]]);loss,g,e0,e1=energy_gradient(z);print('inferred lower / upper state',z[:2].round(9).tolist(),z[2:].round(9).tolist());print('energy before/after',trace[0],round(loss,9),'posterior-mode discrepancy',float(np.max(np.abs(z-exact))))
print('bottom / top prediction errors',e0.round(9).tolist(),e1.round(9).tolist(),'safe fixed-step upper bound',round(float(2/np.linalg.eigvalsh(precision()).max()),9))
print('weight gradients at fixed inferred state',(-np.outer(e0,z[:2])).round(9).tolist(),(-ALPHA*np.outer(e1,z[2:])).round(9).tolist())
inferred lower / upper state [0.609771879, -0.088316363] [0.481567186, -0.154657863]
energy before/after 0.625 0.280793808 posterior-mode discrepancy 5.542248288081808e-08
bottom / top prediction errors [0.425554666, -0.272065989] [0.239983917, -0.078128656] safe fixed-step upper bound 0.350946671
weight gradients at fixed inferred state [[-0.259491268, 0.03758344], [0.165898189, -0.024027879]] [[-0.231136759, 0.074230799], [0.075248394, -0.024166422]]
When the method fails
At the optimum neither residual must vanish. The observation, intermediate prediction and prior compete, so explaining every pixel exactly may increase the total energy. Increasing a precision strengthens that source of evidence; it does not make that evidence correct.
A direct solve for n latent entries costs with a generic dense factorization; each dense iterative update costs . Sparse or structured predictors can change both costs. Iteration is useful when local operations are available, but “uses local errors” does not by itself prove biological plausibility: this example uses transpose prediction matrices and simultaneous state updates.
The visual-cortex paper is a model-based interpretation of specific effects, not proof that every cortical circuit runs these equations. Predictive coding is also not synonymous with contrastive predictive coding, which learns representations with a contrastive prediction objective. Our example does not calculate a variational free-energy bound, entropy term or full posterior covariance; in this Gaussian case it finds a mode, which also equals the mean. Predictive coding in the visual cortex: a functional interpretation of some extra-classical receptive-field effects; A tutorial on the free-energy framework for modelling perception and learning
Exercises with answers
- Why is the precision matrix positive definite?
Answer 1: Its quadratic form is the sum of squared A r, alpha times squared r−B s, and lambda times squared s. Zero requires s=0 and then r=0.
- Must bottom error vanish at the mode?
Answer 2: No. Reducing it further may worsen the inter-layer mismatch or prior penalty.
- What changes when alpha increases?
Answer 3: The conditional variance of r given s decreases, so deviations from B s are penalized more strongly.
- Is the printed weight gradient evidence that the model learned A and B?
Answer 4: No. The program keeps A and B fixed; a training procedure must actually update and evaluate them.
Sources and next steps
Read Rao and Ballard’s hierarchy description for the historical hypothesis, and Bogacz’s Section 4.2 for a Gaussian multi-level account. The tutorial appeared online in 2015 and in the 2017 journal volume; those are different publication dates. Extend the code by generating observations from known A and B, separating training signals from evaluation signals, and reporting inference error separately from parameter recovery. Predictive coding in the visual cortex: a functional interpretation of some extra-classical receptive-field effects; A tutorial on the free-energy framework for modelling perception and learning
Make a prediction, then check
In this program, which operation is inference?
Learning objectives
- Derive state updates and verify a Gaussian posterior mode independently.
- Distinguish inference, parameter learning and a neuroscience hypothesis.
Prerequisites & connections
Explore related knowledge →References
- Predictive coding in the visual cortex: a functional interpretation of some extra-classical receptive-field effects
Rajesh P. N. Rao; Dana H. Ballard · 1999 - A tutorial on the free-energy framework for modelling perception and learning
Rafal Bogacz · 2017
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-07 · Codex single-AI-author technical check: primary-source scope, explicit assumptions, original calculations, independent mathematical references and bilingual tests; not independent human or second-agent review.
- Single-AI-author technical check: bounded primary-source reading, explicit assumptions, original calculations, runnable examples and matching bilingual equations, code and exercises. Not an independent human or second-agent review.
- Four focused CPython 3.12.4 tests passed per chapter: finite-difference gradients, sample covariance, teacher/center update order, hidden-input isolation, independent least squares, PSD projection, margin feasibility, tied-branch derivatives and transported factor actions as applicable, plus bilingual structure. All eight programs use NumPy 1.26.4; teaching calculations, not image benchmarks.
- 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.
Source locations checked:
- Predictive coding in the visual cortex: a functional interpretation of some extra-classical receptive-field effects · Physical pages 1–2, hierarchy, upward errors/downward predictions and fast inference versus slow learning; read author PDF at https://www.ni.cmu.edu/~tai/microns_papers/rao_ballard.pdf.
- A tutorial on the free-energy framework for modelling perception and learning · Journal metadata (2017 volume, online 2015); physical page 9 Section 4.2 Gaussian hierarchy and preceding Eq. 50 learning rule; read PDF at https://www.tnu.ethz.ch/fileadmin/user_upload/teaching/cpcourse/2020/Literature/Bogacz_2017.pdf.
Related topics