Tutorials › Generalized Linear Mixed Models (GLMM) › Sparse Design Matrices for Complex Hierarchies

Crossed and Nested Random Effects · Tutorial 509 of 698

Sparse Design Matrices for Complex Hierarchies

Represent complex random-effects structures efficiently by translating observation membership into sparse design matrices and checking what each nonzero entry means.

Advanced 12 min read

What You'll Learn

  • Construct one-hot design matrices for nested random intercepts.
  • Assemble separate sparse blocks for crossed grouping factors.
  • Extend membership matrices to random slopes using covariate values.
  • Relate shared memberships to covariance in the random part of a linear predictor.
  • Check matrix dimensions, nonzero patterns, and common indexing errors.
  • Compare sparse representations with dense matrices and alternative model structures.

Why Membership Becomes a Matrix

In a complex hierarchy, the model may include random effects for several kinds of units: for example, schools and classes, or subjects and test items. The number of possible units can be large even though each observation belongs to only a few of them. A design matrix records exactly which units contribute to each observation. Its important feature is often not its number of columns, but how few entries in each row are nonzero.

The matrix representation makes the structure explicit. A row corresponds to one observation; a column corresponds to a random-effect coefficient; and an entry records whether, or how strongly, that coefficient contributes to the observation’s linear predictor. Correctly identifying the nonzero entries is essential: they encode the dependence implied by shared units.

Definition: For \(n\) observations and \(q\) random-effect coefficients, a random-effects design matrix \(Z\) is an \(n \times q\) matrix such that the vector \(Zb\) gives the random contribution to the linear predictor. The entry \(Z_{ij}\) is nonzero when coefficient \(b_j\) contributes to observation \(i\). The number of nonzero entries is denoted \(\operatorname{nnz}(Z)\); a matrix is sparse when most of its entries are zero.

For a GLMM, a standard conditional specification is

$$ g(\mu_i)=\mathbf{x}_i^\mathsf{T}\beta+\mathbf{z}_i^\mathsf{T}b, \qquad Y_i\mid b \sim \mathcal{F}(\mu_i,\phi), $$

where \(g\) is the link function, \(\mu_i=E(Y_i\mid b)\), \(\mathbf{x}_i\) is the fixed-effects design row, and \(\mathbf{z}_i\) is row \(i\) of \(Z\). The response distribution \(\mathcal{F}\) is chosen for the outcome, and observations are conditionally independent given the random effects and covariates in the usual GLMM formulation. Random effects are commonly modeled as mean-zero normal variables with a specified covariance matrix \(G\). The design matrix describes membership; by itself it does not establish that the chosen hierarchy, distribution, or covariance assumptions are appropriate.

One-Hot Membership for Nested Intercepts

For a random intercept at one level, each observation belongs to one unit at that level. Put one column in \(Z\) for each unit, and enter 1 in the column for the observation’s unit and 0 in the other columns. This is a one-hot membership row. When a second level is added, its membership indicators form another block of columns.

Worked Example: Schools and Classes

Consider six hypothetical observations. Observations 1–3 come from school A: the first two are in class A1 and the third is in class A2. Observations 4–6 come from school B, all in class B1. Suppose the model has a school random intercept and a class random intercept. Order the school columns as A, B and the class columns as A1, A2, B1. The combined random-effects design matrix is

$$ Z= \begin{bmatrix} 1&0&1&0&0\\ 1&0&1&0&0\\ 1&0&0&1&0\\ 0&1&0&0&1\\ 0&1&0&0&1\\ 0&1&0&0&1 \end{bmatrix}. $$

The first two columns encode school membership; the last three encode class membership. For example, row 3 has a 1 for school A and a 1 for class A2. If \(b=(b_{\text{school A}},b_{\text{school B}},b_{\text{class A1}},b_{\text{class A2}},b_{\text{class B1}})^\mathsf{T}\), then the random contribution for observation 3 is \(b_{\text{school A}}+b_{\text{class A2}}\).

There are \(n=6\) rows and \(q=5\) columns. Each row has two nonzero entries, so \(\operatorname{nnz}(Z)=6(2)=12\), and the density is \(12/(6\cdot5)=0.4\). If there were thousands of classes, a dense matrix would contain many zeros; a sparse representation stores the nonzero values and their positions instead.

Nested membership requires consistent unit identities. If class labels are reused within schools—for instance, each school has a “Class 1”—the columns must represent distinct classes. The membership key is then the school–class pair, not the local class label alone. Otherwise observations from different schools could be assigned to the same class coefficient.

Separate Blocks for Crossed Factors

For crossed factors, an observation belongs to one unit from each factor, but units from one factor are not contained within units of the other. Construct one membership block per factor and concatenate the blocks. Thus each row has one indicator for its subject and one for its item in a random-intercept model. The two sets of columns remain separate because a subject effect and an item effect are different coefficients.

Worked Example: Subjects Crossed With Items

Suppose four hypothetical responses are observed for combinations (subject 1, item 1), (subject 1, item 2), (subject 2, item 1), and (subject 3, item 2). Order the three subject columns first and the two item columns second. The membership matrix is

$$ Z= \begin{bmatrix} 1&0&0&1&0\\ 1&0&0&0&1\\ 0&1&0&1&0\\ 0&0&1&0&1 \end{bmatrix}. $$

The first row contains a 1 for subject 1 and a 1 for item 1. The matrix has \(4\cdot5=20\) possible entries but only \(4(2)=8\) nonzero entries; its density is \(8/20=0.4\). In general, with \(K\) crossed random-intercept factors and one membership per factor, each row has \(K\) nonzero entries, even when each factor has many levels.

For interpretation, suppose subject effects are independent with variance \(\tau_S^2\), item effects are independent with variance \(\tau_I^2\), and the two sets of effects are independent. The random contributions for rows 1 and 2 share subject 1 but not an item, so their covariance is \(\tau_S^2\). Rows 1 and 3 share item 1 but not a subject, so their covariance is \(\tau_I^2\). This refers to covariance in the random part of the linear predictor; it does not, by itself, give the observed-response covariance for a non-Gaussian outcome.

Random Slopes and Weighted Nonzeros

A random slope changes the entries from binary membership indicators to membership indicators multiplied by a covariate. If each class has a random intercept and a random slope for \(x\), then a row contributes the value 1 to that class’s intercept column and the observed \(x_i\) to that class’s slope column. All columns for other classes remain zero. The matrix can therefore be sparse even though its nonzero values are not all 1.

Worked Example: Class-Specific Intercepts and Slopes

Take four hypothetical observations: two in class C1 with \(x=0,2\), and two in class C2 with \(x=-1,1\). Order the columns as intercept C1, slope C1, intercept C2, slope C2. Then

$$ Z= \begin{bmatrix} 1&0&0&0\\ 1&2&0&0\\ 0&0&1&-1\\ 0&0&1&1 \end{bmatrix}. $$

For the second observation, the random contribution is \(b_{0,\mathrm{C1}}+2b_{1,\mathrm{C1}}\). For the third it is \(b_{0,\mathrm{C2}}-b_{1,\mathrm{C2}}\). The first row has only one nonzero entry because its slope value is \(x=0\); the other rows each have two. Thus \(\operatorname{nnz}(Z)=1+2+2+2=7\), and the density is \(7/(4\cdot4)=0.4375\). This example also illustrates why “one nonzero per grouping factor” is not a universal count: with random slopes, the count depends on the number of coefficients per unit and on the covariate values.

Why the Pattern Encodes Dependence

The relationship between membership and covariance can be seen directly for independent random intercepts. Suppose there are \(K\) grouping factors. Let \(g_k(i)\) denote the unit from factor \(k\) to which observation \(i\) belongs, and let \(b_{k,u}\) be the random intercept for unit \(u\) of factor \(k\). Assume \(b_{k,u}\) has mean zero and variance \(\tau_k^2\), and that distinct units and factors have independent effects. The random contribution is

$$ u_i=\sum_{k=1}^{K} b_{k,g_k(i)}. $$

Expanding the covariance of \(u_i\) and \(u_j\), any pair of distinct independent random effects contributes zero. A term contributes \(\tau_k^2\) precisely when observations \(i\) and \(j\) share the same unit of factor \(k\). Equivalently, the indicator columns in that factor’s membership block are both 1 for the same column. Therefore

$$ \operatorname{Cov}(u_i,u_j) = \sum_{k=1}^{K}\tau_k^2\, \mathbf{1}\{g_k(i)=g_k(j)\}. $$

This is a short derivation of the structural connection: common nonzero membership entries create covariance contributions under the stated independence and variance assumptions. With correlated random coefficients, the covariance calculation also depends on the corresponding entries of their covariance matrix; membership alone does not determine the numerical covariance.

Building and Checking Large Sparse Designs

For a large hierarchy, it is often useful to define the row and column meanings before constructing the matrix. A reliable sequence is:

1
Fix the observation order.
Decide which recorded outcome corresponds to each row, and keep that order consistent across every design block.
2
Define each coefficient’s unit.
For every random-effect block, identify the grouping factor and give every unit a unique column identity. For nested labels, include the parent identity when needed.
3
Assign entries from membership.
Use 1 for a random-intercept membership; for a random slope, use the relevant covariate value in the slope column. Keep entries for nonmember units at zero.
4
Check the pattern.
Inspect a few rows against the source records, verify expected block-specific memberships and dimensions, and count nonzero entries against the model’s membership rules.

Several failures have recognizable signatures. A row with no school indicator in a model that requires exactly one school membership may indicate a missing or incorrectly mapped label. Two school indicators in that row may indicate duplicated membership. Unexpectedly repeated class columns across different schools can signal that local labels were treated as globally unique. For a random slope, a row with a nonzero slope entry in another class’s block indicates a mapping error. These checks are structural: they do not establish that a random-effects distribution or link function fits the data.

Storage Choices, Alternatives, and Limits

A dense representation allocates space for all \(nq\) entries. A sparse representation stores nonzero values together with their row and column positions, so storage can be much smaller when \(\operatorname{nnz}(Z)\ll nq\). Sparse matrix operations can likewise avoid work on zeros. This is especially useful in crossed or multilevel models with many units and only a few memberships per observation.

Sparse \(Z\) does not imply that every matrix in model fitting is sparse. The random-effects covariance matrix \(G\) may contain nonzero covariance terms among coefficients, and computations involving it can have different storage and computational properties. Matrix factorizations may also create additional nonzero entries during computation. Sparse design matrices improve representation of membership; they do not guarantee that all estimation steps will be cheap.

A common alternative is to describe the model using grouping factors in statistical software and let the software construct the design internally. This can be convenient, but the implied matrix pattern is still the one defined by the memberships. Explicit matrix reasoning is useful for checking that the software’s grouping structure matches the scientific design. Conversely, manually storing a dense matrix is usually unnecessary when the membership pattern is sparse.

Another tempting alternative is to replace crossed subject and item effects with a single random intercept for each observed subject–item pair. That represents a different model: pair-specific effects do not, by themselves, give observations sharing only a subject a common subject effect, or observations sharing only an item a common item effect. Separate blocks preserve those distinct sources of dependence.

The representation also has limits. It cannot correct a wrong choice of grouping factors, compensate for insufficient replication, or resolve a mismatch between the assumed random-effects distribution and the data. A sparse matrix is a computational description of the specified model, not evidence that the model is scientifically or statistically adequate. The earlier material on covariance matrices from membership structure provides the broader covariance interpretation; here the emphasis is on how that structure appears entry by entry in \(Z\).

Common Mistake

Common pitfall: “There are many zeros in the matrix, so all computations involving the random effects will automatically be sparse and inexpensive.” This is not necessarily true. Sparse \(Z\) records limited membership, but covariance structures and matrix factorizations can introduce dense calculations or fill-in. The correction is to distinguish the sparsity of the design matrix from the structure of \(G\) and from the computational behavior of the full fitting algorithm.

A second practical safeguard is to treat column order as part of the model specification. Reordering columns is harmless only when the corresponding random-effect coefficients and covariance structure are reordered consistently. Otherwise a valid-looking sparse matrix can assign memberships to the wrong coefficients.

Check Your Understanding

Answer the questions, then compare your reasoning with the solutions below.

  1. A random-intercept model has 80 observations and 20 units, with exactly one unit membership per observation. How many nonzero entries are in its membership matrix?
  2. In a crossed subject–item random-intercept model, what does a row contain if each observation has one subject and one item?
  3. For a random intercept and slope within each group, what values appear in a group’s two columns for observation \(i\)?
  4. Why is a subject–item pair random intercept not generally equivalent to separate subject and item random intercepts?

Solutions. 1. There is one indicator per row, so \(\operatorname{nnz}(Z)=80\), regardless of the 20 columns. 2. It contains a 1 in the column for that observation’s subject and a 1 in the column for its item; other membership columns are zero. 3. The group’s intercept column receives 1 and its slope column receives \(x_i\); columns for other groups receive zero. 4. A pair effect is shared only by observations with the same pair. Separate subject and item effects also link observations that share a subject but have different items, or share an item but have different subjects, so they encode different dependence patterns.

Clinical Biostats