Neural Encoding, Decoding and Alignment¶
To bridge neuroscience and artificial intelligence quantitatively, we need mathematical microscopes that connect brain recordings to model activations. This file covers how we record from living brains, how neural encoding and decoding models map between stimuli and cortex, how RSA, CKA, and Procrustes measure representational alignment, and why cross-context transport is the ultimate test of generalisation.
Listening to the Living Brain¶
-
Imagine trying to understand a bustling city by eavesdropping on its residents. You could fly a satellite overhead and watch traffic heat-maps shift every minute (broad coverage, blurry detail), place microphones on rooftops to hear the roar of crowds instantaneously (razor-sharp timing, murky location), or drop tiny recorders right beside individual conversations (crystal-clear detail, tiny coverage). Measuring brain activity faces this exact three-way trade-off between spatial resolution, temporal resolution, and invasiveness.
- fMRI (Functional Magnetic Resonance Imaging and BOLD) non-invasively tracks local blood oxygenation across the entire human brain divided into 3D cubes called voxels (roughly 1 to 2 mm wide, each containing around 100,000 or more neurons). When a region works harder, extra oxygenated blood rushes in, producing the BOLD (Blood-Oxygen-Level-Dependent) signal. The catch is speed, because blood flow is sluggish and follows the haemodynamic response function (HRF), peaking roughly 5 to 6 seconds after neural firing.
- EEG (Electroencephalography) and MEG (Magnetoencephalography) use non-invasive sensors placed on or around the scalp to pick up the synchronised electrical (EEG) or magnetic (MEG) fields generated by tens of thousands of pyramidal neurons firing together. Both offer millisecond temporal resolution (~1 ms), ideal for tracking rapid speech or visual dynamics. EEG suffers spatial smearing (~1 to 3 cm) as currents pass through the skull, while MEG achieves sharper localisation (~5 to 10 mm) because magnetic fields pass undistorted through bone.
- Neuropixels electrophysiology uses hair-thin invasive silicon probes (primarily in animal research and rare clinical settings) packed with hundreds of recording sites, capturing exact single-neuron action potentials across hundreds to thousands of cells simultaneously at sub-millisecond (~30 kHz) precision.
- Two-photon calcium imaging is an invasive optical microscopy technique using genetically encoded fluorescent indicators (such as GCaMP) that glow whenever calcium floods into a firing neuron. It lets neuroscientists watch hundreds to thousands of anatomically identified cells light up in a cortical patch at cellular (~1 \(\mu\text{m}\)) resolution, with moderate temporal speed (~30 to 100 ms due to calcium decay).
| Modality | Spatial Resolution | Temporal Resolution | Invasiveness | What It Directly Measures |
|---|---|---|---|---|
| fMRI (BOLD) | ~1–2 mm (whole brain) | ~1–2 s (HRF lag ~5 s) | Non-invasive | Blood oxygenation proxy |
| EEG / MEG | ~5–30 mm (cortical) | ~1 ms | Non-invasive | Synchronised postsynaptic fields |
| Two-Photon Imaging | ~1 \(\mu\text{m}\) (local patch) | ~30–100 ms | Invasive | Intracellular calcium transients |
| Neuropixels | Single neurons (~20 \(\mu\text{m}\)) | <0.1 ms (30 kHz) | Invasive | Individual action potentials |
Neural Encoding Models from Stimulus to Brain¶
-
How do we test whether a computational model (say, layer 12 of a Vision Transformer from chapter 08 or a language model embedding from chapter 07) truly captures what a cortical area computes? Richard Feynman's rule applies nicely here. If you understand a system, you should be able to predict it. A neural encoding model tries to predict recorded brain activity \(\mathbf{y}\) on brand-new, held-out stimuli \(\mathbf{x}\).
-
Picture an encoding model as a two-stage translator. First, pass each stimulus \(\mathbf{x}_i\) (an image, spoken sentence, or movie clip) through a nonlinear candidate feature extractor \(\phi(\mathbf{x}_i) \in \mathbb{R}^P\) (for instance, a Gabor filterbank, a CNN hidden layer, or a Transformer representation) and stack all \(N\) stimuli into a feature matrix \(X \in \mathbb{R}^{N \times P}\). Second, learn a linear readout \(W \in \mathbb{R}^{P \times M}\) predicting the responses of \(M\) brain voxels or neurons \(Y \in \mathbb{R}^{N \times M}\).
-
Why keep the readout linear? If you put a powerful nonlinear neural network between \(\phi(\mathbf{x})\) and the brain, the readout itself could do all the heavy lifting and make even raw pixels look brain-like. Restricting the bridge to a regularised linear map ensures that high predictive accuracy only happens when the features \(\phi(\mathbf{x})\) have already untangled the stimulus into the same format as cortex.
-
Since \(P\) (thousands of AI units) is often larger than \(N\) (hundreds or thousands of trials), ordinary least squares overfits badly. Standard practice uses ridge regression (\(\ell_2\)-regularised linear regression, chapter 06).
- Here \(\|\cdot\|_F\) is the Frobenius norm (chapter 02) and \(\lambda > 0\) is the ridge regularisation strength chosen via cross-validation. When \(P \gg N\), the Woodbury identity lets us solve the exact same problem in the much smaller \(N \times N\) dual form, \(\hat{W} = X^T (X X^T + \lambda I_N)^{-1} Y\).
Noise Ceiling Normalisation¶
-
Suppose your best encoding model achieves a Pearson correlation of \(r = 0.55\) on held-out fMRI voxels. Is that mediocre or near-perfect? You cannot tell until you know how repeatable the brain data itself is.
-
Think of trying to predict tomorrow's noisy thermometer reading when the sensor itself jitters randomly by \(\pm 2^\circ\text{C}\). Even an omniscient physicist cannot achieve \(r = 1.0\). Living brains have trial-to-trial variability from attention shifts, spontaneous background firing, and scanner thermal noise, so showing the exact same photograph twice produces slightly different recordings \(Y^{(1)}\) and \(Y^{(2)}\).
-
By measuring the split-half reliability between repeated presentations of the same stimuli (adjusted via the Spearman-Brown formula), neuroscientists estimate the noise ceiling \(r_{\text{ceil}}\), which is the maximum correlation any deterministic model of the stimulus could theoretically reach. Dividing raw accuracy by the ceiling yields the noise-normalised score.
- An unnormalised \(r = 0.55\) on a voxel whose noise ceiling is \(r_{\text{ceil}} = 0.60\) actually explains \((0.55/0.60)^2 \approx 84\%\) of all explainable neural variance.
Bottleneck Latent-Space Encoding¶
-
Standard ridge regression maps \(P = 10{,}000\) AI features directly onto \(M = 10{,}000\) cortical voxels via a sprawling 100-million-parameter matrix \(W\). Even with \(\ell_2\) regularisation, this treats every voxel independently and tells us little about the shared structure of the cortical area.
-
Bottleneck latent-space encoding (closely related to reduced-rank regression) constrains the readout to pass through a narrow shared bottleneck of dimension \(k \ll \min(P, M)\).
- Picture funnelling a noisy 10,000-wire cable through a compact \(k\)-channel fibre-optic core \(\mathbf{z} = X U \in \mathbb{R}^{N \times k}\), then fanning it back out to predict every cortical voxel via \(V^T\). This offers two major scientific superpowers.
- It lets us discover effective dimensionality by sweeping bottleneck width \(k = 1, 2, 5, 10, 50, \dots\) and watching where held-out prediction accuracy plateaus before noise takes over.
- It delivers sharper generalisation and interpretability, because sharing statistical strength across all \(M\) voxels through compact latent axes \(\mathbf{z}\) denoises measurements and exposes dominant semantic dimensions (such as animacy, real-world size, or scene layout) organising high-level cortex.
Neural Decoding Models from Brain to Stimulus¶
- Flip the arrow around, going from brain activity \(\mathbf{y}\) back to stimulus or meaning \(\hat{\mathbf{x}}\), and you have a neural decoding model. If encoding asks which features explain how this region fires, decoding asks what information is explicitly accessible in this population right now.
-
Decoding has evolved across three increasingly ambitious generations.
- Classification decoding trains a linear classifier (logistic regression or linear SVM, chapter 06) on voxel patterns to decode discrete categories, such as whether a participant is viewing a face or a house. This proved that fine-grained spatial patterns across voxels carry far more information than average regional activation (Multi-Voxel Pattern Analysis, MVPA).
- Semantic and embedding decoding replaces fixed class labels with a ridge decoder \(\hat{\mathbf{z}} = \mathbf{y} W_{\text{dec}}\) mapping brain activity into a continuous multimodal embedding space (such as CLIP image and text embeddings, chapter 13). Now you can identify never-before-seen objects by nearest-neighbour matching in embedding space.
- Generative decoding with diffusion and LLM priors feeds decoded latent vectors \(\hat{\mathbf{z}}\) directly into a pre-trained latent diffusion model (chapter 08) to reconstruct vivid photographs of what a subject is viewing, or feeds decoded fMRI semantic vectors into an autoregressive large language model (chapter 07) to reconstruct continuous heard or imagined speech.
-
A vital scientific caution accompanies generative decoding. Modern diffusion models and LLMs have extraordinarily strong priors (chapter 05). If a decoder supplies only a coarse cue ("brown animal on grass"), a diffusion model will happily paint sharp fur, realistic blades of grass, and crisp shadows that were never read out of the brain. Rigorous decoding therefore evaluates both high-level semantic fidelity and low-level pixel or structural accuracy against shuffled baselines to separate true neural signal from prior hallucination.
Representational Alignment Between AI Layers and Brain Areas¶
-
Suppose you have activations \(X \in \mathbb{R}^{N \times P}\) from a Vision Transformer layer and neural firing rates \(Y \in \mathbb{R}^{N \times M}\) from macaque IT cortex collected on the same \(N\) images. Notice the headache. \(P\) does not equal \(M\), artificial units have arbitrary ordering and rotation, and biological spikes are measured in Hz rather than dimensionless floats. How can we quantify whether these two completely different systems represent the world with the same underlying geometry?
-
NeuroAI relies on four core representational alignment metrics, each embodying a different assumption about which transformations count as "the same representation".
1. Linear Predictivity and Brain-Score¶
- Linear predictivity fits a cross-validated ridge encoding model from \(X\) to \(Y\) and computes the noise-ceiling-normalised held-out correlation. This is the backbone of benchmarks like Brain-Score (Schrimpf et al., 2018).
- Notice that linear predictivity is asymmetric (\(X \to Y\) is not the same as \(Y \to X\)). A massive AI layer containing all brain features plus 5,000 irrelevant extra features can still predict \(Y\) perfectly, because the ridge weights simply zero out the extra dimensions.
2. Representational Similarity Analysis (RSA)¶
-
Think of comparing two maps of Europe, one drawn in miles rotated sideways and another drawn in kilometres right-side up. Rather than trying to overlay their coordinates, simply list the pairwise distances between every pair of cities (London to Paris, Paris to Rome, London to Berlin) on both maps and check whether the distance rankings agree.
-
Representational Similarity Analysis (RSA) (Kriegeskorte et al., 2008) applies this exact trick to neural representations. For both the AI layer \(X\) and the brain area \(Y\), compute an \(N \times N\) Representational Dissimilarity Matrix (RDM) whose \((i, j)\) entry records how differently stimuli \(i\) and \(j\) are represented (commonly correlation distance \(1 - \text{corr}(\mathbf{x}_i, \mathbf{x}_j)\) or cosine distance).
- Because both \(\text{RDM}_X\) and \(\text{RDM}_Y\) live in the same \(N \times N\) stimulus-by-stimulus space (completely independent of neuron counts \(P\) and \(M\)), we simply extract their upper triangles above the zero diagonal and compute their Spearman rank correlation \(\rho\). High RSA means stimuli that cluster together in the brain (say, faces near dogs and far from chairs and houses) also cluster together in the AI model.
3. Centered Kernel Alignment (CKA)¶
- Centered Kernel Alignment (CKA) (Kornblith et al., 2019) compares similarity structures via \(N \times N\) Gram (kernel) matrices \(K = X X^T\) and \(L = Y Y^T\) using the Hilbert-Schmidt Independence Criterion (HSIC).
- Letting \(H = I_N - \frac{1}{N}\mathbf{1}\mathbf{1}^T\) be the centring matrix (subtracting the mean across stimuli), the empirical HSIC is \(\text{HSIC}(K, L) = \frac{1}{(N-1)^2}\text{tr}(K H L H)\). For linear kernels with mean-centred matrices \(X\) and \(Y\), this simplifies beautifully to a normalised Frobenius inner product (chapter 02).
- Linear CKA lies in \([0, 1]\), is invariant to orthogonal transformations (rotations and reflections) and isotropic scaling, and requires no fitting or regularisation hyperparameters. Unlike RSA (which weights all pairwise distances equally by rank), CKA naturally emphasises the dominant high-variance principal components of the representations.
4. Orthogonal Procrustes and Canonical Correlation Analysis (CCA)¶
- Orthogonal Procrustes asks the strictest geometric question. After centring and scaling \(X\) and \(Y\), can we rigidly rotate one space onto the other using an orthogonal matrix \(Q\) (\(Q^T Q = I\)) so that their points coincide? Formally, we minimise \(\|X Q - Y\|_F\) over orthogonal \(Q\), which has a clean closed-form solution via the SVD of \(X^T Y\) (chapter 02) and preserves exact angles and Euclidean distances.
- Canonical Correlation Analysis (CCA) sits at the opposite, most permissive extreme. It searches for arbitrary linear projections \(X \mathbf{a}\) and \(Y \mathbf{b}\) with maximal correlation, making it invariant to any invertible linear transformation (including arbitrary stretching and shearing). Because unconstrained CCA can easily overfit noise when \(P\) or \(M\) approaches \(N\), practical variants like SVCCA first truncate noisy dimensions via SVD.
-
Together, these metrics form an invariance ladder from strictest to loosest. Orthogonal Procrustes (rigid rotations only) sits inside CKA and RSA (rotations plus isotropic scale), which sit inside Linear Predictivity (asymmetric linear readout), which sits inside CCA (all invertible linear warps). Choosing the right metric depends on your scientific hypothesis about what biological invariances matter.
-
Intriguingly, applying these exact alignment tools across modern AI reveals a striking convergence captured by the Platonic Representation Hypothesis (Huh et al., ICML 2024). As neural networks trained with different architectures, objectives, and even different modalities (such as vision and language) grow larger and more capable, their internal similarity geometries grow steadily more aligned with one another, as though independently recovering the same underlying statistical structure of physical reality. That convergence offers a compelling lens on NeuroAI itself, helping explain why stronger general-purpose foundation models often align more closely with biological sensory and semantic cortex without ever being trained on neural recordings.
Cross-Context Neural Transport and Generalisation¶
-
Imagine a student who memorises the exact phrasing of 100 practice exam questions. On an in-distribution quiz drawn from the same textbook, they score 98%. Hand them a real-world problem phrased differently, and their score collapses. Surprisingly, NeuroAI encoding models can fall into the exact same trap.
-
Suppose you fit a ridge encoding model \(\hat{W}\) predicting human visual cortex fMRI responses to static natural photographs (say, isolated objects on clean ImageNet backgrounds) and test it on other static photographs from the same dataset. A model that exploits low-level dataset shortcuts (background brightness, central framing, or co-occurring colour statistics) can look remarkably brain-like in-distribution.
-
Cross-context neural transport delivers the acid test. You take the encoding weights \(\hat{W}\) fitted on one context (for example, static natural images) and freeze them completely, then evaluate them zero-shot on brain responses recorded during a radically different context (such as dynamic natural movies, line drawings, or naturalistic narratives) without refitting a single weight.
-
Cross-context transport separates genuine scientific discovery from statistical illusion for two clear reasons.
- Shortcut features fail to transport, because spurious correlations tied to static-image framing or dataset-specific background biases break down immediately when cameras pan, objects move, and lighting shifts in a movie.
- Shared cortical mechanisms survive, because if an encoding model truly latches onto the causal features cortex computes (such as invariant object identity in IT or semantic structure in language cortex), its learned mapping \(\hat{W}\) transfers seamlessly across static images, movies, and novel domains.
-
In modern NeuroAI, in-distribution accuracy is necessary, never sufficient. True representational alignment means passing both noise-ceiling-normalised benchmarks and harsh out-of-distribution cross-context transport tests.
Take-Home¶
- Every brain recording modality trades space, time, and invasiveness, with fMRI seeing the whole brain slowly (~1 to 2 mm, ~1 to 2 s HRF lag), EEG and MEG tracking millisecond rhythms coarsely, and Neuropixels or two-photon imaging resolving individual neurons invasively.
- Encoding models (\(\mathbf{x} \to \mathbf{y}\)) test hypotheses via ridge regression and noise ceilings, requiring split-half reliability normalisation (\(r / r_{\text{ceil}}\)) and bottleneck latent-space encoding to uncover a cortical region's true effective dimensionality.
- Decoding models (\(\mathbf{y} \to \hat{\mathbf{x}}\)) invert the map, pairing linear decoders with diffusion or LLM priors to reconstruct rich images and speech while carefully controlling for what the generative prior fills in.
- Representational alignment bridges different neuron counts and coordinate frames, with RSA rank-correlating \(N \times N\) pairwise RDMs, Linear CKA comparing centred Gram matrices (\(\|Y^T X\|_F^2 / (\|X^T X\|_F \|Y^T Y\|_F)\)), Procrustes testing rigid rotation, and CCA allowing full linear warps.
- Cross-context neural transport is the acid test of alignment, freezing weights fitted on static images and evaluating zero-shot on dynamic movies to expose dataset shortcuts and prove genuine shared representations.
Coding Tasks (use CoLab or notebook)¶
-
Build a ridge neural encoding model, estimate the split-half noise ceiling from two repeated brain presentations, and sweep a bottleneck rank \(k\) (reduced-rank regression via SVD) to recover the true effective dimensionality of a synthetic visual cortex area.
import jax import jax.numpy as jnp import matplotlib.pyplot as plt key = jax.random.PRNGKey(42) k1, k2, k3, k4, k5 = jax.random.split(key, 5) # Synthetic dataset: 400 stimuli, 80 AI features, 60 voxels, true cortical rank = 5 N, P, M, true_rank = 400, 80, 60, 5 X = jax.random.normal(k1, (N, P)) U_true = jax.random.normal(k2, (P, true_rank)) / jnp.sqrt(P) V_true = jax.random.normal(k3, (M, true_rank)) / jnp.sqrt(true_rank) Y_signal = jnp.dot(jnp.dot(X, U_true), V_true.T) noise_std = 0.65 Y_rep1 = Y_signal + noise_std * jax.random.normal(k4, (N, M)) Y_rep2 = Y_signal + noise_std * jax.random.normal(k5, (N, M)) X_tr, X_te = X[:300], X[300:] Y_tr = 0.5 * (Y_rep1[:300] + Y_rep2[:300]) Y1_te, Y2_te = Y_rep1[300:], Y_rep2[300:] Y_te_avg = 0.5 * (Y1_te + Y2_te) def col_corr(A, B): """Mean Pearson correlation across columns (voxels).""" Ac = A - jnp.mean(A, axis=0, keepdims=True) Bc = B - jnp.mean(B, axis=0, keepdims=True) num = jnp.sum(Ac * Bc, axis=0) den = jnp.sqrt(jnp.sum(Ac ** 2, axis=0) * jnp.sum(Bc ** 2, axis=0) + 1e-8) return float(jnp.mean(num / den)) # Noise ceiling for the two-repeat average (Spearman-Brown) r_split = col_corr(Y1_te, Y2_te) r_ceil = float(jnp.sqrt(2.0 * r_split / (1.0 + r_split))) # Full-rank ridge regression lam = 25.0 W_ridge = jnp.linalg.solve(jnp.dot(X_tr.T, X_tr) + lam * jnp.eye(P), jnp.dot(X_tr.T, Y_tr)) r_full = col_corr(jnp.dot(X_te, W_ridge), Y_te_avg) # Sweep bottleneck rank k via SVD of predicted training responses (Reduced-Rank Ridge) Y_hat_tr = jnp.dot(X_tr, W_ridge) _, _, Vt = jnp.linalg.svd(Y_hat_tr, full_matrices=False) ranks = [1, 2, 3, 4, 5, 8, 12, 20, 40, 60] norm_scores = [] for k in ranks: P_k = jnp.dot(Vt[:k].T, Vt[:k]) W_k = jnp.dot(W_ridge, P_k) r_k = col_corr(jnp.dot(X_te, W_k), Y_te_avg) norm_scores.append(r_k / r_ceil) print(f"Split-half reliability r = {r_split:.3f}, Noise ceiling r_ceil = {r_ceil:.3f}") print(f"Full-rank ridge: raw r = {r_full:.3f}, noise-normalised = {r_full / r_ceil:.3f}") print(f"Best bottleneck rank k = {ranks[int(jnp.argmax(jnp.array(norm_scores)))]} " f"(true rank = {true_rank}), normalised r = {max(norm_scores):.3f}") plt.figure(figsize=(7.5, 4)) plt.plot(ranks, norm_scores, "o-", color="#3498db", lw=2, label="Bottleneck Encoding (r / r_ceil)") plt.axvline(true_rank, color="#27ae60", ls="--", lw=1.5, label=f"True cortical rank (k={true_rank})") plt.axhline(r_full / r_ceil, color="#e74c3c", ls=":", lw=1.5, label="Full-rank ridge") plt.xlabel("Bottleneck Dimension k") plt.ylabel("Noise-Normalised Correlation (r / r_ceil)") plt.title("Bottleneck Encoding Recovers Effective Cortical Dimensionality") plt.legend() plt.tight_layout() plt.show() -
Implement RSA (Spearman RDM correlation), Linear CKA, and Orthogonal Procrustes similarity from scratch, verify that all three are invariant to orthogonal rotations and isotropic scaling, and visualise the \(N \times N\) RDMs of a brain region versus an aligned AI layer and a misaligned AI layer.
import jax import jax.numpy as jnp import matplotlib.pyplot as plt def compute_rdm(Z): """Correlation-distance RDM: 1 - corr(z_i, z_j).""" Zc = Z - jnp.mean(Z, axis=1, keepdims=True) Zn = Zc / (jnp.linalg.norm(Zc, axis=1, keepdims=True) + 1e-8) return 1.0 - jnp.dot(Zn, Zn.T) def rank_vector(v): """Dense rank transform built purely via double argsort.""" order = jnp.argsort(v) return jnp.argsort(order).astype(jnp.float32) def rsa_spearman(X, Y): rdm_x = compute_rdm(X) rdm_y = compute_rdm(Y) iu = jnp.triu_indices(X.shape[0], k=1) rx = rank_vector(rdm_x[iu]) ry = rank_vector(rdm_y[iu]) rx = rx - jnp.mean(rx) ry = ry - jnp.mean(ry) return float(jnp.sum(rx * ry) / (jnp.linalg.norm(rx) * jnp.linalg.norm(ry) + 1e-8)) def linear_cka(X, Y): Xc = X - jnp.mean(X, axis=0, keepdims=True) Yc = Y - jnp.mean(Y, axis=0, keepdims=True) num = jnp.linalg.norm(jnp.dot(Yc.T, Xc), ord="fro") ** 2 den = (jnp.linalg.norm(jnp.dot(Xc.T, Xc), ord="fro") * jnp.linalg.norm(jnp.dot(Yc.T, Yc), ord="fro") + 1e-8) return float(num / den) def procrustes_similarity(X, Y): """1 - normalised Orthogonal Procrustes distance (for matched dims).""" Xc = X - jnp.mean(X, axis=0, keepdims=True) Yc = Y - jnp.mean(Y, axis=0, keepdims=True) Xc = Xc / (jnp.linalg.norm(Xc, ord="fro") + 1e-8) Yc = Yc / (jnp.linalg.norm(Yc, ord="fro") + 1e-8) U, _, Vt = jnp.linalg.svd(jnp.dot(Xc.T, Yc), full_matrices=False) Q = jnp.dot(U, Vt) dist = jnp.linalg.norm(jnp.dot(Xc, Q) - Yc, ord="fro") return float(1.0 - 0.5 * (dist ** 2)) key = jax.random.PRNGKey(10) k1, k2, k3, k4 = jax.random.split(key, 4) D = 24 prototypes = jax.random.normal(k1, (4, D)) * 2.0 Y_brain = jnp.repeat(prototypes, 10, axis=0) + 0.55 * jax.random.normal(k2, (40, D)) # Aligned AI: orthogonal rotation + isotropic scaling (3.5x) + small noise Q_rand, _ = jnp.linalg.qr(jax.random.normal(k3, (D, D))) X_aligned = 3.5 * jnp.dot(Y_brain, Q_rand) + 0.25 * jax.random.normal(k4, (40, D)) # Misaligned AI: unrelated random features X_random = jax.random.normal(jax.random.PRNGKey(99), (40, D)) for name, X_cand in [("Aligned AI (rotated + scaled)", X_aligned), ("Misaligned AI (random)", X_random)]: print(f"{name:32s} | RSA={rsa_spearman(X_cand, Y_brain):.3f} " f"| CKA={linear_cka(X_cand, Y_brain):.3f} " f"| Procrustes={procrustes_similarity(X_cand, Y_brain):.3f}") fig, axes = plt.subplots(1, 3, figsize=(12, 3.6)) for ax, mat, title in [ (axes[0], compute_rdm(Y_brain), "Brain Area RDM (4 Clusters)"), (axes[1], compute_rdm(X_aligned), "Aligned AI RDM (Matches!)"), (axes[2], compute_rdm(X_random), "Misaligned AI RDM (No Structure)"), ]: ax.imshow(mat, cmap="magma", vmin=0.0, vmax=1.5) ax.set_title(title) ax.set_xlabel("Stimulus j"); ax.set_ylabel("Stimulus i") plt.tight_layout() plt.show() -
Run a cross-context neural transport experiment by fitting two competing encoding models (a Shortcut Model relying on background colour correlated with objects in static photos and a True Semantic Model) on static-image brain responses, then freezing both models and evaluating them zero-shot on held-out static images versus dynamic natural movies where background statistics shift.
import jax import jax.numpy as jnp import matplotlib.pyplot as plt key = jax.random.PRNGKey(21) k1, k2, k3, k4, k5, k6 = jax.random.split(key, 6) # True brain responses depend ONLY on 8 invariant semantic object features N_train, N_test, d_sem, d_bg, M = 300, 150, 8, 8, 30 W_brain = jax.random.normal(k1, (d_sem, M)) / jnp.sqrt(d_sem) # Context A: Static Photos (background cue correlates strongly with semantics) sem_tr = jax.random.normal(k2, (N_train, d_sem)) bg_tr = 0.88 * sem_tr + 0.45 * jax.random.normal(k3, (N_train, d_bg)) Y_tr = jnp.dot(sem_tr, W_brain) + 0.35 * jax.random.normal(k4, (N_train, M)) # Held-out In-Distribution Static Photos sem_id = jax.random.normal(jax.random.PRNGKey(31), (N_test, d_sem)) bg_id = 0.88 * sem_id + 0.45 * jax.random.normal(jax.random.PRNGKey(32), (N_test, d_bg)) Y_id = jnp.dot(sem_id, W_brain) + 0.35 * jax.random.normal(jax.random.PRNGKey(33), (N_test, M)) # Context B: Dynamic Natural Movies (objects move across uncorrelated backgrounds) sem_ood = jax.random.normal(k5, (N_test, d_sem)) bg_ood = jax.random.normal(k6, (N_test, d_bg)) Y_ood = jnp.dot(sem_ood, W_brain) + 0.35 * jax.random.normal(jax.random.PRNGKey(44), (N_test, M)) def fit_ridge(X, Y, lam=5.0): P = X.shape[1] return jnp.linalg.solve(jnp.dot(X.T, X) + lam * jnp.eye(P), jnp.dot(X.T, Y)) def mean_r(Y_pred, Y_true): A = Y_pred - jnp.mean(Y_pred, axis=0, keepdims=True) B = Y_true - jnp.mean(Y_true, axis=0, keepdims=True) return float(jnp.mean(jnp.sum(A * B, axis=0) / (jnp.sqrt(jnp.sum(A ** 2, axis=0) * jnp.sum(B ** 2, axis=0)) + 1e-8))) # Model 1: True Semantic Model W_sem = fit_ridge(sem_tr, Y_tr) id_sem = mean_r(jnp.dot(sem_id, W_sem), Y_id) ood_sem = mean_r(jnp.dot(sem_ood, W_sem), Y_ood) # Model 2: Background Shortcut Model W_bg = fit_ridge(bg_tr, Y_tr) id_bg = mean_r(jnp.dot(bg_id, W_bg), Y_id) ood_bg = mean_r(jnp.dot(bg_ood, W_bg), Y_ood) print(f"True Semantic Model -> Static (ID): {id_sem:.3f} | Dynamic Movie (OOD Transport): {ood_sem:.3f}") print(f"Shortcut Model -> Static (ID): {id_bg:.3f} | Dynamic Movie (OOD Transport): {ood_bg:.3f}") labels = ["Static Images\n(In-Distribution)", "Dynamic Movies\n(Zero-Shot Transport)"] x_pos = jnp.array([0.0, 1.0]) width = 0.32 plt.figure(figsize=(7.5, 4.2)) plt.bar(x_pos - width / 2, [id_sem, ood_sem], width=width, color="#27ae60", label="True Semantic Model") plt.bar(x_pos + width / 2, [id_bg, ood_bg], width=width, color="#e74c3c", label="Background Shortcut Model") plt.axhline(0.0, color="#333333", lw=0.8) plt.xticks(x_pos, labels) plt.ylabel("Mean Prediction Correlation (r)") plt.ylim(-0.15, 1.05) plt.title("Cross-Context Neural Transport Exposes Shortcut Overfitting") plt.legend() plt.tight_layout() plt.show()