Random-Intercept Models¶
A random intercept allows the baseline response to vary across groups.
It is represented by a (Z, G) pair, where Z is the random-effects
design matrix and G specifies the covariance structure.
For a grouping factor g with m groups, each observation belongs
to one group. The design matrix Z contains one column per group,
with an indicator identifying the group to which each observation
belongs. The corresponding covariance matrix is
where I_m is an m-dimensional identity matrix. This specifies
a common random-intercept variance sigma^2 across groups, with
independent random intercepts.
In torch-openreml, construct this pair using
DummyMatrix for Z and
ScalarMatrix for G:
Z = DummyMatrix(g)
G = ScalarMatrix(g)
Add one (Z, G) pair per grouping factor. This page is a quick
reference. See Introduction to Mixed Model REML Estimation for the full API.
Simulate a small sleep study¶
Six sites, six subjects per site, and six days per subject.
| site | subject | day | y | |
|---|---|---|---|---|
| 0 | site_00 | subject_00 | 0 | 235.884 |
| 1 | site_00 | subject_00 | 1 | 246.583 |
| 2 | site_00 | subject_00 | 2 | 220.882 |
| 3 | site_00 | subject_00 | 3 | 305.301 |
| 4 | site_00 | subject_00 | 4 | 270.126 |
A per-column summary:
| count | unique | top | freq | mean | std | min | max | |
|---|---|---|---|---|---|---|---|---|
| site | 216 | 6 | site_00 | 36 | NaN | NaN | NaN | NaN |
| subject | 216 | 36 | subject_00 | 6 | NaN | NaN | NaN | NaN |
| day | 216.0 | NaN | NaN | NaN | 2.5 | 1.712 | 0.0 | 5.0 |
| y | 216.0 | NaN | NaN | NaN | 279.678 | 43.081 | 180.067 | 393.598 |
Show simulation code
# Same code as the hidden cell above.
import pandas as pd
import torch
from torch_openreml import MixedModelREML
from torch_openreml.covariance import DummyMatrix, ScalarMatrix
torch.set_default_dtype(torch.float64)
torch.set_printoptions(precision=3, sci_mode=False)
pd.set_option("display.precision", 3)
generator = torch.Generator().manual_seed(2026)
n_sites, n_per_site, n_days = 6, 6, 6
n_subjects = n_sites * n_per_site
site_of_subject = torch.arange(n_subjects) // n_per_site
subject = torch.arange(n_subjects).repeat_interleave(n_days)
site = site_of_subject[subject]
day = torch.arange(n_days).repeat(n_subjects)
b_site = 20.0 * torch.randn(n_sites, generator=generator)
b_subject = 25.0 * torch.randn(n_subjects, generator=generator)
y = (
250.0
+ 10.0 * day
+ b_site[site]
+ b_subject[subject]
+ 25.0 * torch.randn(len(day), generator=generator)
)
data = pd.DataFrame(
{
"site": [f"site_{s:02d}" for s in site.tolist()],
"subject": [f"subject_{i:02d}" for i in subject.tolist()],
"day": day.numpy(),
"y": y.numpy(),
}
)
y = torch.tensor(data["y"].values)
X = torch.stack(
[
torch.ones(len(data)),
torch.tensor(data["day"].values, dtype=torch.float64),
],
dim=1,
)
X contains only the fixed effects: an intercept and day.
One random intercept¶
For a subject-level intercept, pass the same label column to both classes:
DummyMatrix builds Z, and ScalarMatrix uses the distinct labels to
size G.
Z_subject = DummyMatrix(data["subject"])
G_subject = ScalarMatrix(data["subject"])
reml_subject = MixedModelREML(subject=(Z_subject, G_subject))
reml_subject.optimize(y, X)
reml_subject.build_params(out_format="dict")
{'G/sigma^2': tensor([943.292]), 'R/sigma^2': tensor([626.368])}
The dictionary maps parameter names to variances. Because R is omitted,
it defaults to \(\sigma^2 \boldsymbol{I}\), sized from the random-effect design. With one
random term, the names are G/sigma^2 and R/sigma^2.
Multiple random intercepts¶
Add another pair. Here site and subject are both random intercepts:
Z_site = DummyMatrix(data["site"])
G_site = ScalarMatrix(data["site"])
reml_site_subject = MixedModelREML(
site=(Z_site, G_site),
subject=(Z_subject, G_subject),
)
reml_site_subject.optimize(y, X)
reml_site_subject.build_params(out_format="dict")
{'G/site/sigma^2': tensor([400.603]),
'G/subject/sigma^2': tensor([599.918]),
'R/sigma^2': tensor([626.368])}
With several terms, the names include the term name:
G/site/sigma^2 and G/subject/sigma^2.
After fitting¶
The fitted object keeps the data and parameters, so post-fit quantities are one call away:
print("converged:", reml_site_subject.is_converged())
print("loglik:", reml_site_subject.loglik()[0])
print("fixed effects:", reml_site_subject.blue())
print("fixed-effect SEs:", torch.sqrt(reml_site_subject.var_blue()))
blups = reml_site_subject.blup_per_term()
print("site BLUPs:", blups["site"])
print("subject BLUPs:", blups["subject"])
converged: True
loglik: tensor(-839.103)
fixed effects: tensor([253.917, 10.304])
fixed-effect SEs: tensor([9.620, 0.997])
site BLUPs: tensor([ 3.652, 22.372, 7.508, 1.140, -31.056, -3.616])
subject BLUPs: tensor([-21.999, -20.279, 13.691, -0.570, -19.636, 54.262, 10.334, 11.152,
-17.769, 13.907, 3.818, 12.062, 17.656, 2.102, -16.764, -5.089,
29.307, -15.969, -1.672, -3.721, 7.575, -9.574, 31.633, -22.533,
-2.461, 9.094, 8.465, -33.614, -7.788, -20.204, -22.499, 64.960,
-10.189, -12.085, -4.996, -20.607])
blue() returns the fixed effects, var_blue() their variances, and
blup_per_term() one prediction vector per random term.