Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

18. The General Linear Model and Foundations of Analysis

Authors
Affiliations
Dartmouth College
Johns Hopkins University

The General Linear Model and Foundations of Analysis

Overview

The General Linear Model is arguably the most widely used statistical method for relating task manipulations to brain activity. Applied to fMRI, it identifies regions that respond to an event type, compares responses across conditions, and links brain activity to behavioral or clinical variables. In a typical analysis the outcome variable is the time series from a single voxel (or region of interest), and the analysis is massively univariate: a separate GLM is fit at every voxel, and the resulting parameter estimates are assembled into statistical maps.

The GLM is really a family of models in which one continuously distributed outcome (yy) is predicted by a linear combination of predictors (the columns of a design matrix XX). This family includes t-tests, multiple regression, ANOVA, and ANCOVA — the number, distribution, and grouping of predictors determines which label applies. GLMs have three big advantages: they have a closed-form solution so estimation is fast and reproducible; they are easy to interpret; and they are flexible, since nonlinear relationships can be captured with transformed predictors, piecewise terms, or splines. Extensions handle situations where the basic assumptions fail: generalized least squares for correlated or unequal-variance errors, linear mixed models for grouped observations such as participants, and generalized linear models (via link functions) for binary or count outcomes.

Modeling task-evoked BOLD signal begins with two ingredients: a neural stimulus function describing when neural activity is assumed to occur — brief events or sustained epochs (blocks) — and a hemodynamic response function describing the sluggish vascular response to a burst of neural activity. Assuming the brain behaves as a linear time invariant (LTI) system, the predicted signal is the convolution of the two:

x(t)=(sh)(t)x(t) = (s \ast h)(t)

x(t) — predicted BOLD signal · s(t) — neural stimulus function (1 during assumed activity, 0 elsewhere) · h(t) — hemodynamic response function · ∗ — convolution

where x(t)x(t) is the predicted BOLD signal, s(t)s(t) the neural stimulus function, h(t)h(t) the hemodynamic response function, and \ast the convolution operator.

LTI systems have three key properties: scaling (doubling neural activity doubles the BOLD response, so amplitude differences between conditions can be interpreted as neural differences), superposition (responses to nearby events sum), and time invariance (shifting a stimulus shifts its response). Linearity is a good approximation when events are spaced at least ~5 seconds apart, though nonlinearities (e.g., refractory effects) can be substantial for stimuli spaced under ~2 seconds.

Stimulus functions for block and event-related designs convolved with a canonical HRF to produce predicted responses

The linear system framework used in fMRI. An experimental stimulus function — a block design (left) or event-related design (right) — is convolved with a canonical HRF to obtain the predicted BOLD response. (Figure 18.2 from the book. © the authors and MIT Press; reproduced with permission — not covered by this site’s CC-BY license.)

A popular canonical HRF is the difference of two gamma functions, which captures the initial peak around 5–6 seconds and the subsequent undershoot:

h(t)=tα11β1α1eβ1tΓ(α1)    ctα21β2α2eβ2tΓ(α2)h(t) = \frac{t^{\alpha_1 - 1}\,\beta_1^{\alpha_1}\, e^{-\beta_1 t}}{\Gamma(\alpha_1)} \;-\; c\,\frac{t^{\alpha_2 - 1}\,\beta_2^{\alpha_2}\, e^{-\beta_2 t}}{\Gamma(\alpha_2)}

h(t) — HRF value at time t after a neural event · α₁, β₁ — shape and rate of the peak gamma · α₂, β₂ — shape and rate of the undershoot gamma · c — undershoot amplitude · Γ — gamma function

where tt is time since the neural event, α1,β1\alpha_1, \beta_1 are the shape and rate parameters of the first (peak) gamma function, α2,β2\alpha_2, \beta_2 those of the second (undershoot) gamma, cc scales the undershoot, and Γ()\Gamma(\cdot) is the gamma function.

with common choices α1=6\alpha_1 = 6, α2=16\alpha_2 = 16, β1=β2=1\beta_1 = \beta_2 = 1, and c=1/6c = 1/6.

To formulate the GLM, each condition’s indicator vector (1 during hypothesized neural activity, 0 elsewhere) is convolved with the HRF, and the resulting predicted time courses become columns of the design matrix XX, alongside an intercept and any nuisance covariates (head motion estimates, drift terms). With nn time points and pp predictors, the model is

y=Xβ+ϵ,ϵN(0,σ2I)y = X\beta + \epsilon, \qquad \epsilon \sim N(0, \sigma^2 I)

y — voxel time series (n × 1) · X — design matrix (n × p) · β — unknown amplitudes (p × 1) · ε — unexplained error, variance σ² · I — identity matrix

where yy is the n×1n \times 1 voxel time series, XX the n×pn \times p design matrix, β\beta a p×1p \times 1 vector of unknown amplitudes, ϵ\epsilon the vector of unexplained errors with variance σ2\sigma^2, and II the identity matrix.

fMRI data equals design matrix times betas plus residuals

A pictorial representation of the standard GLM setup. The fMRI time series from one voxel (left) is modeled as the design matrix — here an intercept plus two task regressors — multiplied by three beta values, plus residuals. (Figure 18.3 from the book. © the authors and MIT Press; reproduced with permission — not covered by this site’s CC-BY license.)

Estimation seeks the β\beta values that minimize the sum of squared errors (yXβ)T(yXβ)(y - X\beta)^T(y - X\beta). A closed-form solution exists — the ordinary least squares (OLS) estimate:

β^=(XTX)1XTy\hat{\beta} = (X^TX)^{-1}X^Ty

β̂ — estimated coefficients · X — design matrix (time × predictors) · y — voxel time series · ᵀ — transpose

where β^\hat{\beta} is the vector of estimated coefficients, XX the design matrix, yy the measured time series, and T^T the transpose operator.

with error variance estimated from the residuals r=yXβ^r = y - X\hat{\beta} as σ^2=rTrnp\hat{\sigma}^2 = \frac{r^Tr}{n - p}. Under the model assumptions, β^\hat{\beta} is the best linear unbiased estimate (BLUE), distributed as β^N(β,  σ2(XTX)1)\hat{\beta} \sim N(\beta,\; \sigma^2 (X^TX)^{-1}).

Inference on each β^i\hat{\beta}_i compares it with a null value of zero. Its standard error is the square root of the iith diagonal of σ^2(XTX)1\hat{\sigma}^2 (X^TX)^{-1}, and the ratio t=β^i/SE(β^i)t = \hat{\beta}_i / SE(\hat{\beta}_i) follows a Student’s t distribution with dfe=npdf_e = n - p error degrees of freedom. A low P value lets us declare a region activated (β^i>0\hat{\beta}_i > 0) or deactivated (β^i<0\hat{\beta}_i < 0) — always relative to the model’s intercept, which reflects unmodeled baseline periods. The same machinery extends to contrasts across conditions (Chapter 20).

Two refinements matter in practice. First, fMRI errors are not independent — they are autocorrelated — so OLS standard errors are too small and t-statistics inflated. The remedy is generalized least squares (GLS): assume a structured error covariance VV and prewhiten, giving β^=(XTV1X)1XTV1y\hat{\beta} = (X^TV^{-1}X)^{-1}X^TV^{-1}y, with VV and β\beta estimated iteratively (Chapter 19). Second, the canonical HRF’s shape varies across brain regions and individuals, and mis-modeling it reduces power and can produce false positives. Basis sets — such as the canonical HRF plus temporal and dispersion derivatives, or the highly flexible finite impulse response (FIR) model with one parameter per post-stimulus time point — let the fitted response adapt, at the cost of a fundamental tradeoff between flexibility and power: too much flexibility risks fitting noise.

Hands-on tutorial

In this tutorial you will build a design matrix from event onsets and fit a GLM to a simulated voxel time series — the core of every first-level fMRI analysis. The figure below shows the recipe: indicator functions marking event onsets are convolved with an assumed HRF, and the resulting predictors become columns of XX.

Indicator functions convolved with a canonical HRF form predictors that are placed into the design matrix

Creating a design matrix with four conditions. Indicator functions for the timing of conditions A–D are convolved with a canonical HRF to obtain four predicted responses, which become columns of the design matrix. (Figure 18.4 from the book. © the authors and MIT Press; reproduced with permission — not covered by this site’s CC-BY license.)

Step 1 — Build a design matrix from event onsets. We specify onset times (in seconds) for two event types, A and B, and convolve them with a canonical HRF.

MATLAB
Python
% Requires CanlabCore + SPM12 on your MATLAB path
% Adapted from CANlab tutorials (github.com/canlab)
TR = 2;                                       % repetition time (s)
n_scans = 180;                                % number of volumes (6-min run)

ons = {};
ons{1} = [10 60 110 160 210 260 310]';        % Condition A onsets (sec)
ons{2} = [35 85 135 185 235 285 335]';        % Condition B onsets (sec)

% Convolve onsets with canonical HRF; intercept is the last column
X = onsets2fmridesign(ons, TR, n_scans * TR);

plotDesign(ons, [], TR);                       % plot regressors and onsets
figure; imagesc(X); colormap gray;             % view X as an image
xlabel('Regressor'); ylabel('Time (TRs)');

Example output: running the Python tab draws the classic design-matrix image — 180 rows (one per volume) by 3 columns (regressors A and B, plus the constant/intercept):

Design matrix image with columns A, B, and constant; bright bands mark HRF-convolved events across 180 scans

The design matrix XX as an image: one row per volume, one column per regressor. Each bright band is the HRF-convolved response to one event. The MATLAB tab’s imagesc(X) view is analogous.

Step 2 — Fit the GLM to a voxel time series. We simulate a voxel with known true effects (βA=0.8\beta_A = 0.8, βB=0.4\beta_B = 0.4, intercept 100) plus modest Gaussian noise (σ=0.5\sigma = 0.5, where σ\sigma is the noise standard deviation) and recover them with the OLS formula β^=(XTX)1XTy\hat{\beta} = (X^TX)^{-1}X^Ty.

MATLAB
Python
% Simulate a voxel: y = X * beta_true + noise
rng(9);                                        % seed for reproducible noise
beta_true = [0.8 0.4 100]';                    % true effects: A, B, intercept (last col)
sigma_noise = 0.5;                             % noise SD; modest so this short 7-event demo recovers betas clearly
y = X * beta_true + sigma_noise * randn(n_scans, 1);

% Ordinary least squares: beta_hat = (X'X)^{-1} X'y
beta_hat = (X' * X) \ (X' * y);

r      = y - X * beta_hat;                     % residuals
dfe    = n_scans - size(X, 2);                 % error degrees of freedom (n - p)
sigma2 = (r' * r) / dfe;                       % error variance estimate
t_vals = beta_hat ./ sqrt(sigma2 * diag(inv(X' * X)));

disp(table(beta_true, beta_hat, t_vals))

Example output: the Python tab prints the recovered parameters — close to the true values, with clear t-statistics for both conditions (the MATLAB tab produces an analogous table):

           true   estimate            t
A           0.8   0.787951     6.314865
B           0.4   0.399651     3.223820
constant  100.0  99.964533  2647.254402

The estimates land close to the true values, with reliable t-statistics for both conditions. The full labs continue the arc: inspecting residuals and model fit (R2R^2), computing standard errors and P values, and testing a simple A − B contrast — the bridge to Chapter 20.

Go deeper

Open the full Python lab notebook or download the MATLAB live script, which mirrors it using CANlab tools.

Thought questions

  1. Suppose your experiment presents stimuli in rapid sequences, spaced 1–2 seconds apart. Which LTI assumptions are most at risk, how might your β^\hat{\beta} estimates be distorted, and what design or modeling choices could mitigate the problem?

  2. The HRF varies across brain regions and individuals — for instance, patients with vascular disease may show delayed or blunted responses. If you compare patients and controls using a fixed canonical HRF, how could HRF mis-modeling masquerade as group differences in “activation”?

  3. Adding nuisance regressors (motion, drift) can both improve and worsen your inferences. Using the concepts of residual variance and error degrees of freedom, explain when each outcome would occur.

  4. Activation in the GLM is always relative to the intercept (baseline). How does your choice of what to leave unmodeled change the interpretation of a significant positive beta? Give a concrete example where two labs modeling the same data differently would reach different verbal conclusions.

  5. The FIR basis set can fit almost any response shape, yet most researchers use a single canonical HRF. Drawing on the power–flexibility tradeoff, when would you recommend each approach, and what would you look at in the data to decide?

Quiz yourself

Q1. In a single-subject fMRI GLM, what is the outcome variable yy, and what does “massively univariate” mean?

Answer: yy is the BOLD time series from a single voxel (or region of interest). “Massively univariate” means a separate GLM is fit independently at every voxel in the brain, and the results are assembled into statistical maps.

Q2. What two ingredients are combined — and by what mathematical operation — to create a task predictor for the design matrix?

Answer: A stimulus (indicator) function coding when neural activity is assumed to occur is convolved with a hemodynamic response function (HRF). The convolution x(t)=(sh)(t)x(t) = (s \ast h)(t) gives the predicted BOLD time course, which becomes a column of XX.

Q3. Name and briefly define the three properties of a linear time invariant (LTI) system.

Answer: Scaling: multiplying the input by a factor scales the response by the same factor. Superposition: the response to two stimuli together is the sum of their individual responses. Time invariance: shifting a stimulus in time shifts its response by the same amount.

Q4. What is the OLS estimate of β\beta, and what optimality property does it have when errors are independent and identically distributed?

Answer: β^=(XTX)1XTy\hat{\beta} = (X^TX)^{-1}X^Ty. Under IID errors it is the best linear unbiased estimate (BLUE): among all linear unbiased estimators, it has the smallest variance.

Q5. With nn time points and pp predictors (including the intercept), what are the error degrees of freedom, and why do they matter?

Answer: dfe=npdf_e = n - p. The error degrees of freedom determine how precisely the error variance σ^2\hat{\sigma}^2 is estimated, and they define the t distribution used to compute P values — fewer dfedf_e means less certainty and wider tails.

Q6. Why does plain OLS give invalid inferences for fMRI time series, and what is the standard remedy?

Answer: fMRI errors are autocorrelated (and can be heteroskedastic), violating the independence assumption. As a result the variance of β^\hat{\beta} is underestimated, t-statistics are inflated, and P values are too liberal. The remedy is generalized least squares: model the error covariance VV, prewhiten, and estimate β^=(XTV1X)1XTV1y\hat{\beta} = (X^TV^{-1}X)^{-1}X^TV^{-1}y, iterating between estimates of β\beta and VV.

Q7. What is the finite impulse response (FIR) basis set, and what is its main advantage and main risk?

Answer: The FIR model includes one free parameter for each time point following stimulus onset, so the estimated betas trace out the average response shape with minimal assumptions. Its advantage is flexibility to capture HRF variation; its risk is overfitting — modeling noise as well as signal — which produces noisier, less generalizable estimates.

Cover of Elements of Functional Magnetic Resonance Imaging The book: Elements of Functional Magnetic Resonance Imaging — Wager & Lindquist, MIT Press


⌂ Back to home · Table of contents · How to use this site