arXiv:2608.31133stat.MLAug 2026

Manuscript Offprint

arXiv:2608.31133

Implementing neural network mixed-effects models in Template Model Builder (TMB)

Nan Zheng, Hoi Yiu Cheung, Vibhu Sharma, James T. Thorson, Noel G. Cadigan

Abstract

Neural network mixed-effects models (NMMs) have gained traction by combining the strong representation and predictive power of artificial neural networks with the capacity of mixed-effects modeling to capture complex correlation structures. However, existing estimation approaches rely heavily on manual derivations of objective functions and gradients, which inherently forces simplifying approximations and severely constrains the complexity and accuracy of NMMs. In this work, we introduce a general framework for implementing NMMs using Template Model Builder (TMB). By leveraging automatic differentiation and Laplace approximation, TMB requires users to specify only the negative joint log-likelihood and any regularization terms. The framework automatically integrates out random effects and evaluates the marginal objective function alongside its exact gradients, eliminating the need for manual derivations or ad hoc approximations. We demonstrate the efficiency, flexibility, and statistical performance of TMB-based NMMs across two numerical examples, including an application to monotonic NMMs. Reproducible code is provided to facilitate broader adoption.

Keywords: neural network mixed-effects model; TMB; monotonic neural network; feedforward neural network; Laplace approximation; fish maturation model

*Email: k33nz@mun.ca

1 Introduction

The development of technologies for implementing deep neural networks, that is, neural networks with multiple hidden layers, has significantly advanced the fields of artificial intelligence and machine learning (LeCun et al., 2015). Owing to their strong representational and predictive capabilities, neural networks have been increasingly adopted for analyzing conventional statistical datasets. Compared with modern deep learning applications, these datasets are typically much smaller, making relatively shallow network architectures a practical and commonly adopted choice (Hornik et al., 1989; Hastie et al., 2009; Goodfellow et al., 2016).

A standard feedforward neural network does not explicitly encode structural priors, such as spatial, temporal, or contextual dependencies, within its architecture. As a result, it must learn these relationships solely from the training data, leading to a hypothesis space that is often substantially larger than necessary for structured learning tasks (Bengio, 2009; Goodfellow et al., 2016). Subsequent developments have addressed this limitation by incorporating domain-specific correlation structures into network architectures. For example, convolutional neural networks exploit translation invariance and spatial hierarchies in image data, recurrent neural networks (RNNs) capture temporal dependencies in sequential data, and transformers model long-range contextual relationships in natural language (see, e.g., Chollet et al., 2022). Although these architectures substantially improve learning efficiency by embedding appropriate structural assumptions, they typically remain data-intensive and often require training data with specific structural characteristics that are not satisfied in many statistical applications. For example, RNNs are generally designed for regularly sampled sequential data and are most naturally applied to collections of sequences with comparable temporal structure, assumptions that are frequently violated by longitudinal datasets with irregular observation times or unequal sequence lengths (Mandel et al., 2023). In contrast, statistical mixed-effects models provide considerably greater flexibility for ac-commodating unbalanced longitudinal data, irregular observation schedules, and complex sampling designs while remaining effective with relatively small sample sizes. Motivated by the complementary strengths of these two paradigms, neural network mixed-effects models (NMMs) have emerged as a natural extension that combines the representational power of neural networks with the flexibility and interpretability of statistical mixed-effects models (Tandon et al., 2006; Tran et al., 2017; Mandel et al., 2023).

A NMM can be generally formulated as μ=g{fN(X)+Z⊤b}\boldsymbol{\mu} = g\{f_N(\mathbf{X}) + \mathbf{Z}^\top \mathbf{b}\}, where fN(X)f_N(\mathbf{X}) represents the output of a neural network with input X\mathbf{X}, Z\mathbf{Z} is the design matrix associated with the random effects (REs) b\mathbf{b}, μ\boldsymbol{\mu} denotes the vector of parameters governing the observational model (e.g., the mean vector), and g(⋅)g(\cdot) is an elementwise transformation analogous to the inverse link function in generalized linear mixed-effects models (GLMMs). Throughout this paper, boldface notation is used for vectors and matrices. The REs b\mathbf{b} are typically excluded from the neural network fN(X)f_N(\mathbf{X}), as their inclusion may lead to prohibitive computational costs. Together with the observational model f(D∣μ)f(\mathbf{D}|\boldsymbol{\mu}) for responses D\mathbf{D}, the RE prior f(b)f(\mathbf{b}), and the weight regularization term freg(w)f_{\text{reg}}(\mathbf{w}), the joint objective function is

f(D,b)=f(D∣μ)f(b)freg(w).(1)f(\mathbf{D},\mathbf{b})=f(\mathbf{D}|\boldsymbol{\mu})f(\mathbf{b})f_{\mathrm{r e g}}(\mathbf{w}). \tag{1}

The weight regularization term penalizes excessively large neural network weights, thereby reducing overfitting and improving the generalization ability of the model (see, e.g., Krogh and Hertz, 1991). Before applying optimization algorithms, such as stochastic gradient descent, in deep learning, the REs b must be appropriately accommodated to obtain the objective function and its gradients. To this end, Tran et al. (2017) perform estimation in a Bayesian framework using variational approximation, whereas Mandel et al. (2023) replace the conditional likelihood function f(D∣μ)f(\mathbf{D}|\boldsymbol{\mu}) with a quasi-likelihood function and integrate out b using the Laplace approximation to obtain the marginal objective function. In this work, we adopt the latter approach because of its computational simplicity and the availability of efficient modeling packages, such as the Template Model Builder (TMB;

Kristensen et al., 2016) within R (R Core Team, 2024), which automatically integrates out the REs from the joint likelihood and provides the marginal likelihood together with its gradients. By leveraging automatic differentiation alongside sparse matrix techniques and parallel computing, TMB enables rapid likelihood-based inference even in high-dimensional settings, and offers a highly competitive alternative to Bayesian methods in terms of speed, scalability, and model complexity (Thygesen et al., 2017).

Without leveraging modern computational frameworks such as TMB, Mandel et al. (2023) relied on manual derivations of the marginal objective function and its corresponding gradient to enable numerical optimization. This approach introduces several key limitations. First, as discussed previously, the quasi-likelihood function, rather than the full likelihood, must be used to facilitate manual derivation. Second, the approximation requires omission of a term involving the determinant of the covariance matrix of the REs and the Hessian matrix of the joint objective function with respect to the REs. Neglecting this term may reduce the accuracy and efficiency of inference for certain model parameters. Third, the analytical complexity increases substantially as the number of neural network layers grows, limiting the scalability of the approach (to two layers in Mandel et al., 2023) and making the derivation and implementation increasingly difficult and error-prone. Notably, Mandel et al. (2023) omitted the derivative of the RE estimators with respect to the model parameters when differentiating the objective function (see, e.g., Eq. 7 in Kristensen et al., 2016), an omission that may lead to suboptimal optimization or less precise parameter estimates.

To address these limitations, we propose and demonstrate the use of TMB for implementing NMMs. Rather than using a quasi-likelihood approximation, we directly provide the joint objective function (1) to TMB. TMB then automatically and efficiently computes the Laplace approximation to the marginal objective function, together with its corresponding gradients, without omitting any terms. Consequently, the proposed approach improves computational efficiency, inferential accuracy, ease of implementation, and scalability relative to the manual derivation approach.

The remainder of this paper is organized as follows. Section 2 details the proposed NMM framework and its implementation using TMB. Section 3 replicates the simulation studies from Mandel et al. (2023), demonstrating the computational efficiency and superior accuracy of our approach. In Section 4, we apply both the NMM and GLMM to an American plaice maturity dataset, illustrating the ease of implementing monotonic neural networks within this framework. Finally, Section 5 offers concluding remarks and directions for future research.