Testing Structural Equation Models Built with RTMB
R, RTMB
After fitting a Structural Equation Model, we have to assess whether the fit is any good. This typically falls into two main branches of questions:
Does my model reproduce the structure of my data?
Are there any missing links in my model? I.e., does my model satisfy all conditional independence claims that its structure implies?
With an SEM fit using RTMB, we can test both with a little extra elbow grease.
The Model For Your Consideration
Testing Model Fit with $chi^2$
OK, first things first. Let’s load the data and get some packages setup.
library(RTMB)
library(RTMBdist)
library(dplyr) # for playing with coefficient tables
library(ggplot2) # for viz
data("keeley", package = "piecewiseSEM")Great, now, using the DAG above, let’s setup a model. Remember, richness is negative binomial with a log link.
keeley_mod <- function(data, params){
# let's goooooooo!
getAll(data, params)
# Setup for SEM separating endogenous variables out
rich <- OBS(rich)
cover_obs <- cover
cover <- OBS(cover)
firesev_obs <- firesev
firesev <- OBS(firesev)
age_obs <- age
age <- OBS(age)
# age predictors
age_sigma <- exp(log_age_sigma)
age_hat <- distance_age * distance + age_int
age %~% dnorm(age_hat, age_sigma)
# firesev predictors
firesev_sigma <- exp(log_firesev_sigma)
firesev_hat <- age_firesev * age_obs + firesev_int
firesev %~% dnorm(firesev_hat, firesev_sigma)
# cover predictors
cover_sigma <- exp(log_cover_sigma)
cover_hat <- firesev_cover * firesev_obs + cover_int
cover %~% dnorm(cover_hat, cover_sigma)
# predictors of richness
# GLM with a log link
log_rich_hat <-
cover_rich * cover_obs +
distance_rich * distance +
rich_int
rich_hat <- exp(log_rich_hat) # inverse link function!
theta = exp(log_theta)
rich %~% dnbinom2(mu = rich_hat, size = theta)
}Now, let’s setup a list of parameter start values. I’m gonna be lame and set them to 1 or use the SD values from the data. This works just fine.
keeley_params <- list(
cover_rich = 1,
distance_rich = 1,
rich_int = 1,
firesev_cover = 1,
cover_int = 1,
age_firesev = 1,
firesev_int = 1,
distance_age = 1,
age_int = 1,
log_cover_sigma = log(sd(keeley$cover)),
log_firesev_sigma = log(sd(keeley$firesev)),
log_age_sigma = log(sd(keeley$age)),
log_theta = 1
)breathes hard like I just ran a marathon I’m not gonna lie. The above two steps is really making me wonder if there is some code that can work from a lavaan-like specification to a list of parameters and RTMB code so I don’t have to type so damn much.
OK, let’s fit it and make sure we converge.
cmb <- function(f, d) function(p) f(p, d)
# RTMB object
keeley_fit <- cmb(keeley_mod, keeley) |>
MakeADFun(keeley_params,
silent = TRUE)
#optimize
keeley_opt <- with(keeley_fit,
nlminb(par, fn, gr))
keeley_opt$message[1] "relative convergence (4)"
We’re good. I leave it to you to look at the sdreport - but, I ran this and compared it to a piecewiseSEM fit, and we’re good. The point here, though, is to compare to a fully saturated model to test the hypothesis that our model fit is not different from said saturated model’s fit.
We want a $^2$ likelihood ratio test! We want to ask if the observed Likelihood-Ratio, or a more extreme LR, is different from and LR produced if our null hypothesis - that the models are the same - is true.
With covariance-based SEM, one would merely compare the model-produced covariance matrix to the observed covariance matrix noting the degrees of freedom (from the number of parameters versus number of entries on the VCOV). We can’t do that here as we’re already beyond the world of the gaussian (I mean, we could, but the results wouldn’t be right). Instead, we need to fit a saturated model and use that. What would that be? Looking at the model we are fitting, we can modify it slightly. Red indicates a path we need to add.
We can setup a new model and parameter set for this and fit as usual.
keeley_mod_saturated <- function(data, params){
# let's goooooooo!
getAll(data, params)
# Setup for SEM separating endogenous variables out
rich <- OBS(rich)
cover_obs <- cover
cover <- OBS(cover)
firesev_obs <- firesev
firesev <- OBS(firesev)
age_obs <- age
age <- OBS(age)
# age predictors
age_sigma <- exp(log_age_sigma)
age_hat <- distance_age * distance + age_int
age %~% dnorm(age_hat, age_sigma)
# firesev predictors
firesev_sigma <- exp(log_firesev_sigma)
firesev_hat <- age_firesev * age_obs +
distance_firesev * distance +
firesev_int
firesev %~% dnorm(firesev_hat, firesev_sigma)
# cover predictors
cover_sigma <- exp(log_cover_sigma)
cover_hat <- firesev_cover * firesev_obs +
distance_cover * distance +
age_cover * age_obs +
cover_int
cover %~% dnorm(cover_hat, cover_sigma)
# predictors of richness
# GLM with a log link
log_rich_hat <-
cover_rich * cover_obs +
distance_rich * distance +
firesev_rich * firesev_obs +
age_rich * age_obs +
rich_int
rich_hat <- exp(log_rich_hat) # inverse link function!
theta = exp(log_theta)
rich %~% dnbinom2(mu = rich_hat, size = theta)
}
# params - just add to what we already have!
keeley_params_saturated <- c(
keeley_params,
list(
firesev_rich = 1,
age_rich = 1,
age_cover = 1,
distance_cover = 1,
distance_firesev = 1
)
)
# RTMB object
keeley_fit_saturated <- cmb(keeley_mod_saturated,
keeley) |>
MakeADFun(keeley_params_saturated,
silent = TRUE)
#optimize
keeley_opt_saturated <- with(keeley_fit_saturated,
nlminb(par, fn, gr))
keeley_opt_saturated$message[1] "relative convergence (4)"
Whew! Big, but, it converged. Now, we just need to compare. Fortunately, our objective has both the negative log-likelihood of each model and the number of parameters. So, we can do this by hand (or write a function to do this for any set of nested models).
# first the LRT
lrt <- 2 * (keeley_opt$objective -
keeley_opt_saturated$objective)
# difference in parameters = DF
df <- keeley_opt_saturated$par|> length() -
keeley_opt$par|> length()
pchisq(lrt, df, lower.tail = FALSE)[1] 0.0402467
OK! And there’s your test! Did it fit. Well. Not quite… So, at this point, what do you do? You can do a lot! You can look at the parameter values in the saturated model and see if anything is obvious (it’s not) or you can begin to diagnose is there are other problems. Maybe there’s something else wrong here - who knows! The conundrum of SEM!
Tests of Directed Separation
What’s interesting is that in order to create a saturated model…. you need to fill out the basis set! It’s a convenient bit. If you are worried, you can always fill out a model and use dagitty and ggdag to see the conditional independence claims. Note - this is not the basis set, it’s more expansive.
library(dagitty)
library(ggdag)
mod_dag <- ggdag::dagify(
age ~ distance,
firesev ~ age,
cover ~ firesev,
rich ~ cover + distance
)
impliedConditionalIndependencies(mod_dag)age _||_ covr | frsv
age _||_ rich | covr, dstn
age _||_ rich | dstn, frsv
covr _||_ dstn | age
covr _||_ dstn | frsv
dstn _||_ frsv | age
frsv _||_ rich | covr, dstn
frsv _||_ rich | age, covr
If you want the basis set… just add an argument
impliedConditionalIndependencies(
mod_dag,
type = "basis.set"
)covr _||_ age, dstn | frsv
frsv _||_ dstn | age
rich _||_ age, frsv | covr, dstn
and that is what you’ll need to test.
But, hey, NEAT - that is the same as the new parameters we have for the saturated model. It’s almost as if, we can use those new parameters, fix each one to 0, then one at the time let them be free, and get the p-value each time.
First, let’s start with - how do we take a model and pin it’s values at a certain value? For that, MakeADFun() has an argument map where you can supply a list with names of parameters. If a parameter in the map is a factor with NA - factor(NA) - its value is fixed to what it is in the parameters list. Interestingly, if you have entries in map with the SAME factor level (that is not NA), they will be set to a common value. So, nice way to do some constraints even if you have different parameter names.
OK, so, let’s make a new basis set parameter list and an accompanying map.
basis_params <- list(
# rich _||_ age, frsv | covr, dstn
firesev_rich = 0,
age_rich = 0,
# covr _||_ age, dstn | frsv
age_cover = 0,
distance_cover = 0,
# frsv _||_ dstn | age
distance_firesev = 0
)
keeley_params_basis <- c(
keeley_params,
basis_params
)
fix0_map <- lapply(basis_params,
\(x){factor(NA)})Now, to show you this works, let’s fit the following. We’ll use keeley_mod_saturated from above, but use our new parameters for a basis set and we will fix all parameters to 0. This should mean we get a fit model back that is identical to our initial keeley_fit from the start of all of this.
obj <- MakeADFun(
cmb(keeley_mod_saturated, keeley),
parameters = keeley_params_basis,
map = fix0_map,
silent = TRUE)
# optimize
opt <- nlminb(obj$par, obj$fn, obj$gr)
# compare models NLLs
opt$objective[1] 878.5167
keeley_opt$objective[1] 878.5167
Check their sdreport() as well - you’ll see they are the same.
So this is cool. We can now use lapply() or purrr::map() to iterate over the parameter names in basis_params and get the p value for each one in order to construct a test of Fischer’s C. First, we’ll need a function to extract a p-value for a parameter.
get_p_param <- function(obj, a_param){
sdreport(obj) |>
summary(p.value = TRUE) |>
as_tibble(rownames = "parameter") |>
janitor::clean_names() |>
filter(parameter == a_param) |>
select(parameter, pr_z_2) |>
rename(p = pr_z_2)
}
get_p_param(obj, "age_firesev")# A tibble: 1 × 2
parameter p
<chr> <dbl>
1 age_firesev 0.00000135
Now we need a function that, given a parameter and a map list where that parameter is fixed will free it up.
get_free_mod <- function(mod, param, paramlist, fix0_map, data) {
new_map <- fix0_map[names(fix0_map) != param]
obj <- MakeADFun(
cmb(mod, data),
parameters = paramlist,
map = new_map,
silent = TRUE
)
# optimize
opt <- nlminb(obj$par, obj$fn, obj$gr)
obj
}
# let's test it out!
test_obj <- get_free_mod(
keeley_mod_saturated,
param = "distance_firesev",
paramlist = keeley_params_basis,
fix0_map = fix0_map,
data = keeley
)
get_p_param(test_obj, "distance_firesev")# A tibble: 1 × 2
parameter p
<chr> <dbl>
1 distance_firesev 0.0876
Oh, hey! That works! And……look, there’s our p-value! So, one last step to make this all work - wrap it in an lapply!
make_basis_fun <- function(param){
fit_obj <- get_free_mod(
keeley_mod_saturated,
param = param,
paramlist = keeley_params_basis,
fix0_map = fix0_map,
data = keeley
)
get_p_param(fit_obj, param)
}
# make it sew
basis_frame <- lapply(names(basis_params),
make_basis_fun) |>
Reduce(rbind, x = _)
basis_frame# A tibble: 5 × 2
parameter p
<chr> <dbl>
1 firesev_rich 0.0429
2 age_rich 0.250
3 age_cover 0.0669
4 distance_cover 0.176
5 distance_firesev 0.0876
Welp - what’s nice here is that we can see that one conditional independence claim is not satisfied - and it’s an interesting one! We can also now calculate Fisher’s C and evaluate it.
c_stat <- -2 * sum(log(basis_frame$p))
df <- 2 * nrow(basis_frame)
p <- 1 - pchisq(c_stat, df)
data.frame(C = c_stat, df = df, p = p) C df p
1 22.82381 10 0.01141593
Yup - that failure hoses the model. Interestingly, this is slightly different from a similar model in piecewiseSEM, but, it’s likely a rounding bit in the p values or an algorithmic thing.
Model Comparison in General
From the above, I hope you can see how you can easily generate AICs from alternate models and do comparisons there. As our objective is the negative log likelihood, our AIC is just 2 * (nll + k). So, let’s compare the first model we fit to the saturated model.
AIC_mod <- 2 * keeley_opt$objective +
2* length(keeley_opt$par)
AIC_saturated <- 2 * keeley_opt_saturated$objective +
2 *length(keeley_opt_saturated$par)
tibble(
model = c("Our model", "Saturated model"),
aic = c(AIC_mod, AIC_saturated)
) |>
mutate(delta_aic = min(aic) - aic)# A tibble: 2 × 3
model aic delta_aic
<chr> <dbl> <dbl>
1 Our model 1783. -1.63
2 Saturated model 1781. 0
Not that different! Which accords with most of our results above - save that we’re not testing for fit explicitly. Still, this gives another view into how these models compare, and one that is useful for optimizing for out of sample prediction.
Where do we go from here?
I hope you’ve enjoyed. Obviously, as we’re dealing with SEMs using equation-level estimation, the complexity is pretty daunting. However, there are some real advantages. In the next post, I’ll talk simulation from these models, which is pretty sweet. I’ve explored a bit if some of the above can be automated, and, well, while it can, it’s often with some fairly abstruse coding that is easy to use once written, but often obscures what you are trying to do with your models from you. I still think at some point an semRTMB package might be a good idea that translates lavaan-style models to RTMB and automates some of the above, but…. that might be a minute until I have time to try making that. But I’m sure it’s possible!