2

How could I get max gradient values after doing random effects models with lme4? By default, it is shown if it is more than 0.002, but I want to make an original function as below, which needs a returned value of max gradient, whether the value is more than 0.002 or not.

  1. Doing the original model
MM<- lmer(Y ~ 1 + X + (1 |cluster_ID ), data=data)
summary(MM)
  1. If the above original model have the max gradient more than 0.002, then do the below process.
MM_par <- getME(MM, c("theta", "fixef"))
RS_MM <- update(MM, start=MM_par, control=lmerControl(optCtrl = list(maxeval=1e4)))
summary(RS_MM)
Kaori
  • 23
  • 2

2 Answers2

1

Example:

library(lme4)
fm1 <- lmer(Reaction~Days+(Days|Subject), sleepstudy)

Extract the @optinfo slot and see what's there:

names(fm1@optinfo)

Check the $derivs element:

fm1@optinfo$derivs

Here's the gradient:

max(abs(fm1@optinfo$derivs$gradient))

But we want the scaled gradient (thanks @RobertLong for the reminder)

dd <- fm1@optinfo$derivs
sc_grad <- with(dd, solve(Hessian, gradient))
max(abs(sc_grad))

notes

  • extracting slots directly via @ is not 100% guaranteed to be future-proof (although lme4 is pretty stable)
  • increasing the maximum number of evaluations won't actually change the max gradient. You might consider tightening/decreasing the convergence tolerance instead (see ?lme4::convergence)
Ben Bolker
  • 211,554
  • 25
  • 370
  • 453
1

You can get the convergence error with:

myModel@optinfo$conv$lme4

And you can get the max gradient with:

myModel@optinfo$derivs %>% with(. , solve(Hessian, gradient))  %>% abs() %>% max()
Robert Long
  • 5,722
  • 5
  • 29
  • 50