Building models
m2n2 builds a model with the MixedModelNN constructor, from a pandas DataFrame and one or several PyTorch networks.
Build a m2n2 model
model = MixedModelNN(
data = data,
response = "DTF1",
fixed = "1 + country",
embedding = {
"geno": Embedding(network),
},
random = [
RandomNN(
embedding = "geno"
),
RandomNN(
embedding = "geno",
group = "country"
),
],
residual = Residual(),
)
model.fit()| Argument | Meaning |
|---|---|
data |
One row per individual. |
response |
One response column, or a list of them (see Several responses). |
fixed |
A patsy formula for \(X\). Defaults to the intercept "1". |
embedding |
The networks, as a dictionary of named Embedding. |
random |
The random effects, a list of RandomNN and pyreml Random terms. |
residual |
The residual, a pyreml Residual. Defaults to Residual(): \(\sigma^2_R I\). |
Embeddings
An Embedding wraps a network:
Embedding(network)It also carries the training settings of the network, its optimizer and its learning-rate scheduler, which can be passed at construction:
Embedding(
network,
optimizer = partial(torch.optim.AdamW, lr=1e-3, weight_decay=1e-1),
scheduler = None,
)| Argument | Meaning |
|---|---|
network |
The network \(\nu\), an nn.Module returning the embeddings (see the network). |
optimizer |
Factory of the optimizer of the network. Defaults to partial(torch.optim.AdamW, lr=1e-3, weight_decay=1e-1). |
scheduler |
Factory of the learning-rate scheduler of the network. Defaults to None: constant learning rate. |
Both can also be set or changed after construction, by model.set_optimizer() and model.set_scheduler(): see Optimizers and schedulers.
Its name in embedding is the handle by which the random effects refer to it. Several random effects can share the same embedding: the network is then embedded once per minibatch, and stepped once by its optimizer.
The network
The network is user-defined, under the following contract:
network()returns the \(n \times d\) embedding of every row ofdata, in the same order.network(rows), withrowsa boolean mask over the rows ofdata, returns the embeddings of the selected rows only. Training feeds the labelled rows of each minibatch alone, so that batch statistics (e.g. BatchNorm) never see the others.- The networks must share their device. The mixed model runs in double on that device; the networks keep their own dtype.
The features \(z\) are typically stored in the network as a buffer:
class Network(nn.Module):
def __init__(self, z):
super().__init__()
self.register_buffer("z", z)
self.body = nn.Sequential(
nn.Dropout(0.1), nn.Linear(z.shape[1], 256),
nn.BatchNorm1d(256), nn.GELU(),
nn.Dropout(0.5), nn.Linear(256, 128),
nn.BatchNorm1d(128), nn.GELU(),
nn.Dropout(0.5), nn.Linear(128, 64),
)
def forward(self, rows=None):
return self.body(self.z if rows is None else self.z[rows])Different embeddings can read the same features, or different ones.
The embeddings are projected on the unit sphere before entering the mixed model (see Deep kernel). Dropout and BatchNorm belong to the network: m2n2 switches it to train() mode for the gradient steps, and to eval() mode for validation and prediction.
Neural random effects
A RandomNN term is a random effect \(Z_j u_j\) built upon an embedding:
RandomNN(
embedding = "geno",
group = None,
left_hand = "iid",
n_axes = None,
)| Argument | Meaning |
|---|---|
embedding |
Name of the embedding, a key of the embedding dictionary. |
group |
Qualitative column defining the \(q_j\) groups of the term. Defaults to None: a single group, the general effect. |
left_hand |
Structure of \(S_j\), the covariance of the term across the responses: the left-hand factor of \(S_j \otimes I_{q_j d}\), as left_hand in pyreml and in Residual. "iid", "diag", "full" or "fa". Defaults to "iid". Irrelevant with one response. |
n_axes |
Number of factors of the "fa" structure. |
With \(Z = \nu(z, \theta)\) the embedding, the term reads:
- \(Z_j = \bigoplus_{k=1}^{q_j} \nu(z_{(k)}, \theta)\), of dimension \(n \times q_j d\): the embedding of each individual in the columns of its group, zeros elsewhere;
- \(u_j \sim N(0, \sigma^2_{u_j} I)\), \(u_j \in \mathbb{R}^{q_j d}\): one embedding effect vector per group.
With \(m\) responses, each response receives its own effects, upon the same embedding: \(u_j \sim N(0, S_j \otimes I_{q_j d})\), \(u_j \in \mathbb{R}^{m q_j d}\), with \(S_j\) the \(m \times m\) covariance of the term across the responses, structured by left_hand.
Without group, \(Z_j = Z\): the effects \(u_j\) are shared by all individuals. With group, each group receives its own effects: combined with a general term on the same embedding, they capture what is specific to the group (see Deep kernel). The terms are independent: several groupings, crossed or nested, are as many terms.
Several responses
With a list of \(m\) responses, data keeps one row per individual, and \(y\) stacks the observed responses, response by response, as in pyreml. The fixed formula is shared by the responses, with one coefficient per response and per term. The residual covariance across the responses of an individual follows the left_hand of Residual.
For a RandomNN term, the observation of response \(r\) on individual \(i\) reads its embedding in the columns of response \(r\) and of the group of \(i\). \(S_j\) carries the covariance of the term across the responses: "iid" gives them independent effects of a common variance, on the standardized scale of the responses, "diag" independent effects of their own variances, "full" an unstructured covariance, and "fa" a factor-analytic one, of n_axes factors (see pyreml variance structures).
Data layout and missing values
- A row missing every response is left out of the fit, but still predicted. A row missing some responses is fitted on the others, and predicted on all.
- A row missing a fixed covariate is left out of the fit.
groupmust be qualitative and complete: numeric codes are to be cast tostr.
The random design \([Z_1 \mid Z_2 \mid \dots]\) has \(m \sum_j q_j d_j\) columns over the RandomNN terms, plus those of the Random terms.
The fitted model
After .fit() (see Training models):
| Accessor | Content |
|---|---|
model.estimates |
Fixed-effect estimates (BLUE) as a long table response · term · estimate · SE · t. |
model.residual |
The pyreml Residual: .residuals and .table of the labelled rows, .variance. |
model.varcomp() |
Raw and unit variances, one row per term and per response, the residual last (see Deep kernel). The covariances across responses are in the .variance of each term. |
model.loss, model.score |
Training curves (see Monitoring). |
model.plot() |
Plot of the training curves, returns the figure (see Monitoring). |
model.convergence |
Whether the REML of the polish converged, None with full_REML = False (see Polish). |
model.random[j] |
The \(j\)-th random effect, in the order of random. |
Each RandomNN term exposes:
| Accessor | Content |
|---|---|
.prediction |
\(Z_j \hat u_j\) for every row of data, missing responses included, of shape (n,), or (n, m) with \(m\) responses. |
.uhat |
\(\hat u_j\), of shape (q_j, d), or (m, q_j, d) with \(m\) responses, one row per level of .levels. |
.variance |
The pyreml variance of the term: ["sigma"] is \(S_j\), its covariance across the responses in natural units, a scalar with "iid". |
.levels |
The levels of group, [None] without it. |
.PEV |
Prediction error variance of \(\hat u_j\). |
.pca |
PCA of the embeddings "Z" and of the weighted embeddings "Z*u", \(Z \odot \hat u_{j,k(i)}\), with \(k(i)\) the group of individual \(i\): coords, inertia, eigvec per embedding. With several responses, "Z*u" is a dictionary by response. |
.plot(plan=(0, 1), group_by=None, response=None) |
Individual projections on the principal plan plan, colored by group_by, a qualitative column of data. Defaults to the term’s group, monochrome without it. response selects the weighted embeddings, the first response by default. |
The Random and Residual terms expose their pyreml accessors.