Neural-Network Variance Functions

In clustered data, the between-cluster variance may vary systematically with cluster-level covariates. For example, clusters with different covariate profiles may exhibit different levels of variability. The standard random-intercept model assumes a common variance \(\sigma_G^2\) across all clusters, which cannot capture this heterogeneity. This vignette shows how to model cluster-specific variances using a small neural network within the covariance system of torch_openreml.

The construction follows the DeepMEGA design (Prevett, 2026), with variance updates based on the GBMixed score functions (Prevett et al., 2026); see references.

The model is a linear mixed model with a random-effect covariance matrix

\[\mathbf{G} = \operatorname{diag}(G_1, \ldots, G_K),\]

where each \(G_i\) is predicted by a neural network evaluated at the corresponding cluster’s covariates. The fixed-effects component remains linear, so REML profiles \(\boldsymbol{\beta}\) in the usual way. Only the covariance structure is learned by the network.

The simulation

We simulate \(K = 2000\) clusters, each containing \(n = 3\) observations, giving a total sample size of \(N = 6000\). Each cluster has two covariates \(\mathbf{c}_i = (c_{1i}, c_{2i})^\top \sim U(0, 1)^2\), while each observation has three independent covariates \(x_{1ij}, x_{2ij}, x_{3ij} \sim \mathcal{N}(0, 1)\). The conditional mean is

\[\mu_{ij} = 2\,(x_{1ij} + x_{2ij} + x_{3ij} + c_{1i} + c_{2i}).\]

The standard deviation of the cluster-specific random effect varies quadratically with the cluster-level covariates:

\[s_{G,i} = 1.00 + 0.45\,c_{1i} + 0.35\,c_{2i} + 0.10\,(c_{1i}^2 + c_{2i}^2) + 0.15\,c_{1i}c_{2i}.\]

The cluster-level variance is \(G_i = s_{G,i}^2\). We then generate the random effects and observation errors independently as

\[u_i \sim \mathcal{N}(0, G_i), \qquad \varepsilon_{ij} \sim \mathcal{N}(0, 0.5),\]

and obtain the response as

\[y_{ij} = \mu_{ij} + u_i + \varepsilon_{ij}.\]

The resulting marginal covariance matrix is

\[\boldsymbol{\Sigma} = \mathbf{Z}\mathbf{G}\mathbf{Z}^\top + 0.5\,\mathbf{I}_N,\]

where \(\mathbf{Z} = \mathbf{I}_K \otimes \mathbf{1}_n\) and \(\mathbf{G} = \operatorname{diag}(G_1, \ldots, G_K)\).

K = 2000, n = 3, N = 6000
Gtrue range: [1.0109, 4.4388]  mean 2.3110  sd 0.7207
Show simulation code
import torch

torch.set_default_dtype(torch.float64)

from torch_openreml import MixedModelREML
from torch_openreml.covariance import ScalarMatrix, SimpleMatrix

def simulate(K=2000, n=3, seed=7):
    gen = torch.Generator().manual_seed(seed)
    N = K * n
    g = torch.arange(K).repeat_interleave(n)
    Cc = torch.rand(K, 2, generator=gen)
    c1, c2 = Cc[:, 0], Cc[:, 1]
    sG = 1.00 + 0.45 * c1 + 0.35 * c2 + 0.10 * (c1**2 + c2**2) + 0.15 * c1 * c2
    G = sG**2
    u = torch.randn(K, generator=gen) * torch.sqrt(G)

    def draw_X():
        x1, x2, x3 = (torch.randn(N, generator=gen) for _ in range(3))
        return torch.stack((x1, x2, x3, Cc[g, 0], Cc[g, 1]), dim=1)

    X = draw_X()
    Xte = draw_X()
    mu, mu_te = 2.0 * X.sum(dim=1), 2.0 * Xte.sum(dim=1)
    eps = torch.randn(N, generator=gen) * 0.5**0.5
    eps_te = torch.randn(N, generator=gen) * 0.5**0.5
    y = mu + u[g] + eps
    yte = mu_te + u[g] + eps_te
    return {"X": X, "y": y, "Xte": Xte, "yte": yte, "Cc": Cc, "Gtrue": G,
            "K": K, "n": n, "N": N}

The covariance as a Matrix

The covariance system represents a covariance structure as an object that maps free parameters to a covariance matrix. SimpleMatrix provides a straightforward way to incorporate a neural network: it passes a flat parameter vector to a callable, which constructs the covariance matrix.

We use a one-hidden-layer network to predict each cluster’s variance:

\[\hat{G}_i = \exp\!\left( w_2^\top \operatorname{relu}(W_1 c_i + b_1) + b_2 \right),\]

where \(W_1 \in \mathbb{R}^{3 \times 2}\), \(b_1 \in \mathbb{R}^3\), \(w_2 \in \mathbb{R}^{1 \times 3}\) and \(b_2 \in \mathbb{R}\). The network has 13 free parameters, stored in a single vector:

Block

Size

Parameter indices

\(W_1\)

6

theta[0:6]

\(b_1\)

3

theta[6:9]

\(w_2\)

3

theta[9:12]

\(b_2\)

1

theta[12]

The residual covariance is assumed to have a common variance, \(\mathbf{R} = \sigma_R^2 \mathbf{I}_N\), and can therefore be represented by ScalarMatrix(N). Its single free parameter is appended to the 13 network parameters, giving 14 variance parameters in total.

from torch.nn.functional import linear, relu

def G_cov(theta):
    W1 = theta[0:6].reshape(3, 2)
    b1 = theta[6:9]
    w2 = theta[9:12].reshape(1, 3)
    b2 = theta[12:13]
    h = relu(linear(Cc, W1, b1))
    v = linear(h, w2, b2)[:, 0]
    return torch.diag(torch.exp(v))

The exponential transformation ensures that all predicted variances are strictly positive, without requiring explicit constraints during optimisation. It also prevents variances from reaching zero at finite parameter values.

Fitting the model

We construct the random-effect design matrix using the Kronecker product \(\mathbf{Z} = \mathbf{I}_K \otimes \mathbf{1}_n\) and pass the neural network as the G operand. The fixed-effects component uses the five-column design matrix X, with its coefficients profiled by MixedModelREML through REML.

We also need to initialise the network parameters. We draw \(W_1\) and \(w_2\) independently from \(N(0, 0.5^2)\), set both biases to zero, and initialise the residual variance \(\sigma_R^2\) to one.

def init_theta(seed, sd=0.5):
    gen = torch.Generator().manual_seed(seed)
    return torch.cat([
        (torch.randn(3, 2, generator=gen) * sd).reshape(-1),
        torch.zeros(3),
        (torch.randn(1, 3, generator=gen) * sd).reshape(-1),
        torch.zeros(1),
        torch.zeros(1),
    ])

Z = torch.kron(torch.eye(K), torch.ones(n, 1))
model = MixedModelREML((Z, SimpleMatrix(13, G_cov)))

names, theta = model.optimize(y, X, init_values=init_theta(1), verbose=1)
[  1] ∥∇∥:    1756.5081, ∥Δ∥: 1.1886, η: 1.00, ∥Δᶜ∥: 1.1886, accepted: True , log 𝓛: -3800.1345
[  2] ∥∇∥:    1528.4165, ∥Δ∥: 1.0121, η: 1.00, ∥Δᶜ∥: 1.0121, accepted: True , log 𝓛: -3611.5511
[  3] ∥∇∥:     325.3909, ∥Δ∥: 0.2426, η: 1.00, ∥Δᶜ∥: 0.2426, accepted: True , log 𝓛: -3592.2889
[  4] ∥∇∥:      17.5932, ∥Δ∥: 0.3748, η: 0.25, ∥Δᶜ∥: 0.0937, accepted: True , log 𝓛: -3592.2861
[  5] ∥∇∥:      14.8655, ∥Δ∥: 0.4890, η: 1.00, ∥Δᶜ∥: 0.4890, accepted: True , log 𝓛: -3592.2621
[  6] ∥∇∥:       8.3873, ∥Δ∥: 0.0110, η: 1.00, ∥Δᶜ∥: 0.0110, accepted: True , log 𝓛: -3592.2460
[  7] ∥∇∥:       0.0147, ∥Δ∥: 0.0000, η: 1.00, ∥Δᶜ∥: 0.0000, accepted: True , log 𝓛: -3592.2460

[∇: score, Δ: 𝐉⁻¹∇, η: step length, Δᶜ: clip(𝛉 + ηΔ, lb, ub) - 𝛉, 𝓛: restricted likelihood]

✓ Converged at iteration 7, total time: 17.10s

Non-zero initial weights are important here. If all network weights are initialised to exactly zero, the ReLU network becomes stationary because the hidden-layer gradients vanish. Consequently, optimisation cannot move away from the initial constant-variance model.

Ghat = torch.diag(G_cov(theta[:13]))
corr = torch.corrcoef(torch.stack([Ghat, Gtrue]))[0, 1]
rmse = torch.sqrt(((Ghat - Gtrue) ** 2).mean())

print(f"corr(Ghat, Gtrue): {corr:.4f}")
print(f"RMSE: {rmse:.4f}")
print(f"sigma_R^2: {torch.exp(2 * theta[13]):.4f}  (true 0.5)")
corr(Ghat, Gtrue): 0.9961
RMSE: 0.1179
sigma_R^2: 0.5080  (true 0.5)

The fitted surface closely matches the true surface. The correlation between \(\hat{G}_i\) and \(G_i\) is approximately 0.996, with an RMSE of 0.12 on the variance scale, compared with a true surface range of 1.01 to 4.44. The residual variance is also accurately recovered at 0.508, against the true value of 0.5.

How well is the surface recovered?

The correlation summarises agreement across the entire surface, but it is also useful to examine how well the fitted values capture its shape. We compare selected quantiles of the true and fitted variances.

qs = torch.tensor([0.0, 0.1, 0.25, 0.5, 0.75, 0.9, 1.0])
print(f"{'quantile':>8} {'Gtrue':>10} {'Ghat':>10}")
for q in qs:
    print(f"{q.item():>8.2f} "
          f"{torch.quantile(Gtrue, q).item():>10.4f} "
          f"{torch.quantile(Ghat, q).item():>10.4f}")
quantile      Gtrue       Ghat
    0.00     1.0109     1.0209
    0.10     1.4287     1.4106
    0.25     1.7612     1.7201
    0.50     2.2131     2.1075
    0.75     2.7851     2.6515
    0.90     3.3610     3.2102
    1.00     4.4388     4.3009

The largest discrepancies occur in the tails. The network produces a smoother surface than the underlying quadratic function, slightly underestimating the largest variances and overestimating the smallest. This reflects the bias-variance trade-off of a relatively small network rather than an optimisation failure. A larger network could reduce this bias, but, as discussed in the next section, would also make the model harder to identify.

A single start is not enough

AI-REML is a deterministic, monotone optimiser, so it cannot escape a local optimum or cross a likelihood barrier. This model has several challenging features: the constant-variance model is itself a local optimum, while the ReLU network introduces flat directions and scaling symmetries. As a result, different initialisations can converge to substantially different variance surfaces.

A ten-start experiment on the same data (seeds 0–9, max_iter=10) illustrates this sensitivity. The raw correlation ranged from 0.954 to 0.996, while the raw RMSE ranged from 0.11 to 0.66. The best-fitting surface in terms of RMSE came from seed 6 (correlation 0.995, RMSE 0.109), but this was not the start with the highest REML. Instead, seed 9 achieved the highest REML but had an RMSE of 0.659. Its estimated surface spiked to 6.62, well above the maximum true value of 4.44. A larger 20-start experiment showed a similar pattern: most initialisations recovered the underlying surface reasonably well, but a few converged to substantially worse stationary points.

In practice, we therefore recommend fitting the model from multiple random initialisations and retaining the fit with the highest REML. However, the recovered variance surface should also be inspected, since a higher likelihood does not necessarily imply a more accurate surface:

best = None
for seed in range(5):
    model = MixedModelREML((Z, SimpleMatrix(13, G_cov)), R=ScalarMatrix(N))
    _, theta = model.optimize(y, x=X, init_values=init_theta(seed), max_iter=50)
    ll, _ = model.loglik(y, X, theta)
    if best is None or ll > best[0]:
        best = (ll, theta)

Practical notes

  • Identifiability. The variance surface is informed primarily by the \(K\) cluster means, rather than the \(N\) individual observations. A flexible network therefore requires enough clusters to identify its parameters. In this example, \(K = 2000\) provides ample information for the 13-parameter network. With substantially fewer clusters, the surface may be poorly identified and the fit may favour boundary solutions.

  • Link function. The exponential function is a natural link for modelling variances. A squared link, \(\hat{G}_i = v_i^2\), is also possible, but introduces a boundary at zero and a sign symmetry. In practice, this makes the fit more prone to collapsing to the constant-variance model.

  • Beyond scalar random intercepts. The same construction extends to higher-dimensional random effects by returning a \(q \times q\) covariance matrix from the callable. For example, \(\operatorname{diag}(\exp(v))\) represents \(q\) independent random effects, while a full covariance matrix can be constructed as \(LL^\top\), with \(L\) parameterised by the network. Because the covariance system composes with other operators, a network can also serve as one operand in a sum or Kronecker product.

References

  • Prevett, M. L., Hui, F. K. C., Tho, Z. Y., Welsh, A. H., & Westveld, A. H. (2026). Gradient Boosted Mixed Models: Flexible Estimation of Mean and Variance Components for Clustered Data. arXiv:2511.00217 [stat.ML]. https://arxiv.org/abs/2511.00217

  • Prevett, M. L. (2026). Deep Mixed Models with Covariate-Dependent Variance. Talk, Australian National University, 14 September 2026. Unpublished draft.