Linear mixed-effects models are increasingly used for the analysis of data from experiments in fields like psychology where several subjects are each exposed to each of several different items.
In addition to a response, which here will be assumed to be on a continuous scale, such as a response time, a number of experimental conditions are systematically varied during the experiment.
In the language of statistical experimental design the latter variables are called experimental factors whereas factors like Subject
and Item
are blocking factors.
That is, these are known sources of variation that usually are not of interest by themselves but still should be accounted for when looking for systematic variation in the response.
The data from experiment 2 in Kronmueller and Barr (2007) are available in .rds
(R Data Set) format in the file kb07_exp2_rt.rds
in the github repository provided by Dale Barr.
Files in this format can be loaded using the RData package for Julia.
In [1]:
using BenchmarkTools, DataFrames, Distributions, FreqTables
using MixedModels, RData, Statistics, StatsBase, StatsModels
using Gadfly
In [2]:
kb07 = load("../kronmueller-barr-2007/kb07_exp2_rt.rds")
Out[2]:
In [3]:
describe(kb07)
Out[3]:
The blocking factors are subj
and item
with 56 and 32 levels respectively.
There are three experimental factors each with two levels: spkr
(speaker), prec
(precedence), and load
(cognitive load).
The response time, rt_raw
, is measured in milliseconds.
A few very large values, e.g. the maximum which is nearly 16 seconds, which could skew the results, are truncated in the rt_trunc
column.
In addition, three erroneously recorded responses (values of 300 ms.) have been dropped, resulting in a slight imbalance in the data.
In [4]:
subjitemtbl = freqtable(kb07, :subj, :item)
Out[4]:
In [5]:
countmap(vec(subjitemtbl))
Out[5]:
All of the experimental factors vary within subject and within item, as can be verified by examining the frequency tables for the experimental and grouping factors. For example
In [6]:
freqtable(kb07, :spkr, :subj)
Out[6]:
A table of mean responses and standard deviations for combinations of the experimental factors, as shown in Table 3 of the paper and on the data repository can be reproduced as
In [7]:
cellmeans = by(kb07, [:spkr, :prec, :load], meanRT = :rt_trunc => mean, sdRT = :rt_trunc => std, n = :rt_trunc => length)
Out[7]:
An interaction plot of these means
In [8]:
plot(cellmeans, x=:load, y=:meanRT, color=:prec, xgroup=:spkr, Geom.subplot_grid(Geom.point))
Out[8]:
shows that the dominant factor is the precedent with the response times under break being considerably larger than under maintain.
A simple model with main-effects for each of the experimental factors and with random effects for subject and for item is described by the formula rt_trunc ~ 1 + spkr + prec + load + (1|subj) + (1|item)
.
In the MixedModels package, which uses the formula specifications from the StatsModels package, a formula must be wrapped in a call to the @formula
macro.
The model is created as an instance of a LinearMixedModel
type then fit with a call to the fit!
generic.
(By convention, the names in Julia of mutating functions, which modify the value of one or more of their arguments, end in !
as a warning to the user that arguments, usually just the first argument, can be overwritten with new values.)
In [9]:
m1 = fit!(LinearMixedModel(@formula(rt_trunc ~ 1 + spkr + prec + load + (1|subj) + (1|item)), kb07))
Out[9]:
The first fit of such a model can take several seconds because the Just-In-Time (JIT) compiler must analyze and compile a considerable amount of code. (All of the code in the MixedModels package is Julia code.) Subsequent fits of this or similar models are much faster.
When timing fits that take a few seconds or less the @btime
macro will be used, as it performs the evaluation of the expression several times and takes the minimum of these evaluation times.
This is to eliminate the noise introduced by garbage collection and compilation.
Furthermore, in what follows the formulas and models will be declared const
, which in Julia means that the type of the value cannot be changed, although the values in, say, a vector can be.
Also the expression is written using $
before an argument name. This is an interpolation in a macro call. The effect is to time only the expression evaluation and not the name lookup for the arguments.
In [10]:
const f1 = @formula(rt_trunc ~ 1 + spkr + prec + load + (1|subj) + (1|item));
@btime fit!(LinearMixedModel($f1, $kb07));
The coding for the experimental factors in the model matrix for this model is the default or "dummy" coding, where the first level is the reference level and the estimated coefficients represent differences of the response at the indicated level relative to the first.
In this case the model matrix for the fixed effects is
In [11]:
m1.X
Out[11]:
In two-level factorial experiments like this it is an advantage to use a $\pm1$ coding, which can be derived from EffectsCoding
or HelmertCoding
(these codings are the same for a two-level factor).
In [12]:
const contrasts = Dict(:spkr=>HelmertCoding(), :prec=>HelmertCoding(), :load=>HelmertCoding());
In [13]:
m1 = @btime fit!(LinearMixedModel($f1, $kb07, $contrasts))
Out[13]:
The estimate of the (Intercept)
coefficient is now approximately the sample mean. (It may be slightly different from the sample mean due to the
slight imbalance in the design because of two unusually long response times being dropped.)
The coefficients for the experimental factors are half the previously estimated effects, because of the $\pm1$ coding, Their standard errors are also half those from the previous fit. The estimates of the variance components, the log-likelihood and other goodness of fit criteria, and the z statistics and p-values for the effects remain the same.
The model matrix for the fixed effects is now
In [14]:
m1.X
Out[14]:
The m1
object is created in the call to the constructor function, LinearMixedModel
, then the parameters are optimized or fit in the call to fit!
.
Usually the process of fitting a model will take longer than creating the numerical representation but, for simple models like this, the creation time can be a significant portion of the overall running time.
In [15]:
@btime LinearMixedModel($f1, $kb07, $contrasts);
In [16]:
@btime fit!($m1);
The optimization process is summarized in the optsum
property of the model.
In [17]:
m1.optsum
Out[17]:
For this model there are two parameters to be optimized because the objective function, negative twice the log-likelihood, can be profiled with respect to all the other parameters. (See section 3 of Bates et al. 2015 for details.) Both these parameters must be non-negative (i.e. both have a lower bound of zero) and both have an initial value of one. After 21 function evaluations an optimum is declared according to the function value tolerance, either $10^{-8}$ in absolute terms or $10^{-12}$ relative to the current value.
The optimization itself has a certain amount of setup and summary time but the majority of the time is spent in the evaluation of the objective - the profiled log-likelihood.
Each function evaluation is of the form
In [18]:
const θ1 = m1.θ;
In [19]:
@btime objective(updateL!(setθ!($m1, $θ1)));
Remember that this is a "best case" time. During the course of the optimization some of the function evaluations could take longer due to garbage collection or other factors.
On this machine 21 function evaluations, each taking 42 microseconds or more, gives the total function evaluation time of at least 0.85 ms., which is practically all of the time to fit the model.
The majority of the time for the function evaluation for this model is in the call to updateL!
In [20]:
@btime updateL!($m1);
This is an operation that updates the lower Cholesky factor (often written as L
) of a blocked sparse matrix.
There are 4 rows and columns of blocks. The first row and column correspond to the random effects for subject, the second to the random effects for item, the third to the fixed-effects parameters and the fourth to the response. Their sizes and types are
In [21]:
describeblocks(m1)
There are two lower-triangular blocked matrices: A
with fixed entries determined by the model and data, and L
which is updated for each evaluation of the objective function.
The type of the A
block is given before the size and the type of the L
block is after the size.
For scalar random effects, generated by a random-effects term like (1|G)
, the (1,1) block is always diagonal for both A
and L
.
Its size is the number of levels of the grouping factor, G
.
Because subject and item are crossed, the (2,1) block of A
is dense, as is the (2,1) block of L
.
The (2,2) block of A
is diagonal because, like the (1,1) block, it is generated from a scalar random effects term.
However, the (2,2) block of L
ends up being dense as a result of "fill-in" in the sparse Cholesky factorization.
All the blocks associated with the fixed-effects or the response are stored as dense matrices but their dimensions are (relatively) small.
In general, adding more terms to a model will increase the time required to fit the model. However, there is a big difference between adding fixed-effects terms and adding complexity to the random effects.
Adding the two- and three-factor interactions to the fixed-effects terms increases the time required to fit the model.
In [22]:
const f2 = @formula(rt_trunc ~ 1 + spkr*prec*load + (1|subj) + (1|item));
In [23]:
const m2 = @btime fit!(LinearMixedModel($f2, $kb07, $contrasts))
Out[23]:
(Notice that none of the interactions are statistically significant.)
In this case, the increase in fitting time is more because the number of function evaluations to determine the optimum increases than because of increased evaluation time for the objective function.
In [24]:
m2.optsum.feval
Out[24]:
In [25]:
const θ2 = m2.θ;
In [26]:
@btime objective(updateL!(setθ!($m2, $θ2)));
Another way in which the model can be extended is to switch to vector-valued random effects.
Sometimes this is described as having random slopes, so that a subject not only brings their own shift in the typical response but also their own shift in the change due to, say, Load
versus No Load
.
Instead of just one, scalar, change associated with each subject there is an entire vector of changes in the coefficients.
A model with a random slopes for each of the experimental factors for both subject and item is specified as
In [27]:
const f3 = @formula(rt_trunc ~ 1 + spkr*prec*load + (1+spkr+prec+load|subj) + (1+spkr+prec+load|item));
In [28]:
const m3 = @btime fit!(LinearMixedModel($f3, $kb07, $contrasts))
Out[28]:
There are several interesting aspects of this model fit.
First, the number of parameters optimized directly has increased substantially. What was previously a 2-dimensional optimization has now become 20 dimensional.
In [29]:
m3.optsum
Out[29]:
and the number of function evaluations to convergence has gone from under 40 to over 650.
The time required for each function evaluation has also increased considerably,
In [30]:
const θ3 = m3.θ;
In [31]:
@btime objective(updateL!(setθ!($m3, $θ3)));
resulting in much longer times for model fitting - about half a second for the "best case" on this machine.
Notice that the estimates of the fixed-effects coefficients and their standard errors have not changed substantially except for the standard error of P
(Precedent), which is also the largest effect.
The parameters in the optimization for this model can be arranged as two lower-triangular 4 by 4 matrices.
In [32]:
m3.λ[1]
Out[32]:
In [33]:
m3.λ[2]
Out[33]:
which generate the covariance matrices for the random effects. The cumulative proportion of the variance in the principal components of these covariance matrices, available as
In [34]:
m3.rePCA
Out[34]:
show that 93% of the variation in the random effects for subject is in the first principal direction and 99% in the first two principal directions. The random effects for item also have 99% of the variation in the first two principal directions.
Furthermore the estimates of the standard deviations of the "slope" random effects are much smaller than the those of the intercept random effects except for the P
coefficient random effect for item
, which suggests that the model could be reduced to rt_trunc ~ 1 + spkr*prec*load + (1|subj) + (1+prec|item)
or even RTtrunc ~ 1 + spkr+prec+load + (1|subj) + (1+prec|item)
.
In [35]:
const f4 = @formula(rt_trunc ~ 1 + spkr+prec+load + (1|subj) + (1+prec|item));
In [36]:
const m4 = @btime fit!(LinearMixedModel($f4, $kb07, $contrasts))
Out[36]:
In [37]:
m4.optsum.feval
Out[37]:
In [38]:
const θ4 = m4.θ;
In [39]:
@btime objective(updateL!(setθ!($m4, $θ4)));
These two model fits can be compared with one of the information criteria, AIC
or BIC
, for which "smaller is better".
They both indicate a preference for the smaller model, m4
.
These criteria are values of the objective, negative twice the log-likelihood at convergence, plus a penalty that depends on the number of parameters being estimated.
Because model m4
is a special case of model m3
, a likelihood ratio test could also be used.
The alternative model, m3
, will always produce an objective that is less than or equal to that from the null model, m4
.
The difference in these value is similar to the change in the residual sum of squares in a linear model fit.
This objective would be called the deviance if there was a way of defining a saturated model but it is not clear what this should be.
However, if there was a way to define a deviance then the difference in the deviances would be the same as the differences in these objectives, which is
In [40]:
diff(objective.([m3, m4]))
Out[40]:
This difference is compared to a $\chi^2$ distribution with degrees of freedom corresponding to the difference in the number of parameters
In [41]:
diff(dof.([m4, m3]))
Out[41]:
producing a p-value of
In [42]:
ccdf(Chisq(20), first(diff(objective.([m3,m4]))))
Out[42]:
The "maximal" model as proposed by Barr et al., 2013 would include all possible interactions of experimental and grouping factors.
In [43]:
const f5 = @formula(rt_trunc ~ 1 + spkr*prec*load + (1+spkr*prec*load|subj) + (1+spkr*prec*load|item));
In [44]:
const m5 = @btime fit!(LinearMixedModel($f5, $kb07, $contrasts))
Out[44]:
As is common in models with high-dimensional vector-valued random effects, the dominant portion of the variation is in the first few principal components
In [45]:
m5.rePCA
Out[45]:
For both the subjects and the items practically all the variation of these 8-dimensional random effects is in the first 4 principal components.
The dimension of $\theta$, the parameters in the optimization, increases considerably
In [46]:
const θ5 = m5.θ;
length(θ5)
Out[46]:
Of these 72 parameters, 36 are estimated from variation between items, yet there are only 32 items.
Because the dimension of the optimization problem has gotten much larger the number of function evaluations to convergence increases correspondingly.
In [47]:
m5.optsum.feval
Out[47]:
Also, each function evaluation requires more time
In [48]:
@btime objective(updateL!(setθ!($m5, $θ5)));
almost all of which is for the call to updateL!
.
In [49]:
@btime updateL!($m5);
To provide more granularity in the plots of execution time shown below, fit one more model without random effects for the third-order interaction of the experimental factors.
In [50]:
const f6 = @formula(rt_trunc ~ 1 + spkr*prec*load +
(1+spkr+prec+load+spkr&prec+spkr&load+prec&load|subj) +
(1+spkr+prec+load+spkr&prec+spkr&load+prec&load|item));
In [51]:
const m6 = @btime fit!(LinearMixedModel($f6, $kb07, $contrasts))
Out[51]:
In [52]:
const θ6 = m6.θ;
length(θ6)
Out[52]:
In [53]:
@btime objective(updateL!(setθ!($m6, $θ6)));
In [54]:
@btime updateL!($m6);
Apply the goodness of fit measures to m1
to m6
creating a data frame
In [55]:
const mods = [m1, m2, m3, m4, m5, m6];
gofsumry = DataFrame(dof=dof.(mods), deviance=deviance.(mods),
AIC = aic.(mods), AICc = aicc.(mods), BIC = bic.(mods))
Out[55]:
Here dof
or degrees of freedom is the total number of parameters estimated in the model and deviance
is simply negative twice the log-likelihood at convergence, without a correction for a saturated model. All the information criteria are on a scale of "smaller is better" and all would select model 4 as "best".
In [56]:
gofnms = (:AIC, :AICc, :BIC)
map(nm -> argmin(gofsumry[nm]), NamedTuple{gofnms, NTuple{3, Symbol}}(gofnms))
Out[56]:
In [57]:
nfe(m) = length(coef(m));
nre1(m) = MixedModels.vsize(first(m.reterms));
nlv1(m) = MixedModels.nlevs(first(m.reterms));
nre2(m) = MixedModels.vsize(last(m.reterms));
nlv2(m) = MixedModels.nlevs(last(m.reterms));
nθ(m) = sum(MixedModels.nθ, m.reterms);
nev = map(m -> m.optsum.feval, mods);
μsev = [42.035, 46.950, 589.784, 134.539, 2248, 1552];
fit = [0.002072, 0.004233, 0.428509, 0.015163, 5.536, 2.423]
dimsumry = DataFrame(p = nfe.(mods), q1 = nre1.(mods), n1 = nlv1.(mods),
q2 = nre2.(mods), n2 = nlv2.(mods), nθ = nθ.(mods),
npar = dof.(mods), nev = nev, μsev = μsev,
fit = fit)
Out[57]:
In this table, p
is the dimension of the fixed-effects vector, q1
is the dimension of the random-effects for each of the n1
levels of the first grouping factor while q2
and n2
are similar for the second grouping factor.
nθ
is the dimension of the parameter vector and npar
is the total number of parameters being estimated, and is equal to nθ + p + 1
.
nev
is the number of function evaluations to convergence.
Because this number will depend on the number of parameters in the model and several other factors such as the setting of the convergence criteria, only its magnitude should be considered reproducible.
μsev
is the best-case time, in microseconds, per function evaluation and fit
is the best-case time, in seconds, to fit the model.
As would be expected, the time required to fit a model increases with the complexity of the model. In particular, the number of function evaluations to convergence increases with the number of parameters being optimized.
In [58]:
plot(dimsumry, x=:nθ, y=:nev, Geom.point,
Guide.xlabel("# of parameters in the optimization"),
Guide.ylabel("Function evaluations to convergence"))
Out[58]:
The relationship is more-or-less linear, based on this small sample.
The time to evaluate the objective also increases with n$\theta$, the number parameters in the random-effects covariance matrices.
In [59]:
plot(dimsumry, x=:nθ, y=:μsev, Geom.point,
Guide.xlabel("# of parameters in the optimization"),
Guide.ylabel("Microseconds per function evaluation"))
Out[59]:
This relationship also appears linear, based on this small sample.
Finally, consider the time to fit the model versus the number of parameters in the optimization,
In [60]:
plot(dimsumry, x=:nθ, y=:fit, Geom.point,
Guide.xlabel("# of parameters in the optimization"),
Guide.ylabel("Time (s) to fit the model"))
Out[60]:
which, given the shape of the previous plots, would be expected to be approximately quadratic.