knitr::opts_chunk$set( echo = TRUE, collapse = TRUE, warning = FALSE, fig.width=5, fig.height=5, fig.align = "center", dev = "png", fig.pos = 'H' )
R package gllvm fits Generalized linear latent variable models (GLLVM) for multivariate data^[Niku, J., F.K.C. Hui, S. Taskinen, and D.I. Warton. 2019. Gllvm - Fast Analysis of Multivariate Abundance Data with Generalized Linear Latent Variable Models in R. 10. Methods in Ecology and Evolution: 2173–82].
Developed by J. Niku, W.Brooks, R. Herliansyah, F.K.C. Hui, S. Taskinen, D.I. Warton, B. van der Veen.
The package available in
Package installation:
# From CRAN install.packages(gllvm) # OR # From GitHub using devtools package's function install_github devtools::install_github("JenniNiku/gllvm")
Problems?
gllvm package depends on R packages TMB and mvabund, try to install these first.
GLLVMs are computationally intensive to fit due the integral in log-likelihood.
gllvm package overcomes computational problems by applying closed form approximations to log-likelihood and using automatic differentiation in C++ to accelerate computation times (TMB^[Kasper Kristensen, Anders Nielsen, Casper W. Berg, Hans Skaug, Bradley M. Bell (2016). TMB: Automatic Differentiation and Laplace Approximation. Journal of Statistical Software, 70(5), 1-21]).
Estimation is performed using either variational approximation (VA^[Hui, F. K. C., Warton, D., Ormerod, J., Haapaniemi, V., and Taskinen, S. (2017). Variational approximations for generalized linear latent variable models. Journal of Computational and Graphical Statistics. Journal of Computational and Graphical Statistics, 26:35-43]), extended variational approximation method (EVA^[Korhonen, P., Hui, F. K. C., Niku, J., and Taskinen, S. (2021). Fast, universal estimation of latent variable models using extended variational approximations, arXiv:2107.02627 .]) or Laplace approximation (LA^[Niku, J., Warton, D. I., Hui, F. K. C., and Taskinen, S. (2017). Generalized linear latent variable models for multivariate count and biomass data in ecology. Journal of Agricultural, Biological, and Environmental Statistics, 22:498-522.]) method implemented via R package TMB.
VA method is faster and more accurate than LA, but not applicable for all distributions and link functions.
Using gllvm we can fit
GLLVM without latent variables fits basic multivariate GLMs
Additional tools: residuals, information criteria, confidence intervals, visualization.
| Response | Distribution | Method | Link | | ----------- |:------------:|:------- |:------- | |Counts | Poisson | VA/LA |log | | | NB | VA/LA |log | | | ZIP | VA/LA |log | | | ZINB | VA/LA |log | |Binary | Bernoulli | VA/LA |probit | | | | LA |logit | |Ordinal | Ordinal | VA |probit | |Normal | Gaussian | VA/LA |identity| |Positive continuous| Gamma | VA/LA |log| |Non-negative continuous| Exponential | VA/LA |log| |Biomass | Tweedie | LA/EVA |log | |Percent cover| beta | LA/EVA |probit/logit |
Main function of the gllvm package is gllvm()
, which can be used to fit GLLVMs for multivariate data with the most important arguments listed in the following:
gllvm(y = NULL, X = NULL, TR = NULL, family, num.lv = 2, formula = NULL, method = "VA", row.eff = FALSE, n.init=1, starting.val ="res", ...)
library(gllvm)
soil.dry
: Soil dry massbare.sand
: cover of bare sandfallen.leaves
: cover of fallen leaves/twigsmoss
: cover of mossherb.layer
: cover of herb layerreflection
: reflection of the soil surface with a cloudless skyFit GLLVM with environmental variables $g(E(y_{ij})) = \beta_{0j} + \boldsymbol{x}i'\boldsymbol{\beta}{j} + \boldsymbol{u}_i'\boldsymbol{\theta}_j$ using gllvm:
library(gllvm) data("spider") fitx <- gllvm(y = spider$abund, X=spider$x, family = "negative.binomial", num.lv = 2) fitx
X=spider$x fitx1 <- gllvm(spider$abund, X, family = "negative.binomial", num.lv = 1) fitx2 <- gllvm(spider$abund, X, family = "negative.binomial", num.lv = 2) fitx3 <- gllvm(spider$abund, X, family = "negative.binomial", num.lv = 3) AIC(fitx1) AIC(fitx2) AIC(fitx3)
plot()
: par(mfrow = c(1,2)) plot(fitx1, which = 1:2)
E1. Load spider data from mvabund package and take a look at the dataset.
library(gllvm) #Package **mvabund** is loaded with **gllvm** so just load with a function `data()`. data("spider") # more info: # ?spider
Show the answers.
Package mvabund is loaded with gllvm so just load with a function data()
.
# response matrix: spider$abund # Environmental variables spider$x # Plot data using boxplot: boxplot(spider$abund)
E2. Fit GLLVM with two latent variables to spider data with a suitable distribution. Data consists of counts of spider species.
# Take a look at the function documentation for help: ?gllvm
Show the answers.
2. Response variables in spider data are counts, so Poisson, negative binomial and zero inflated Poisson are possible. However, ZIP is implemented only with Laplace method, so it need to be noticed, that if models are fitted with different methods they can not be compared with information criteria. Let's try just with a Poisson and NB. NOTE THAT the results may not be exactly the same as below, as the initial values for each model fit are slightly different, so the results may
# Fit a GLLVM to data fitp <- gllvm(y=spider$abund, family = poisson(), num.lv = 2) fitp fitnb <- gllvm(y=spider$abund, family = "negative.binomial", num.lv = 2) fitnb
Based on AIC, NB distribution suits better. How about residual analysis: NOTE THAT The package uses randomized quantile residuals so each time you plot the residuals, they look a little different.
# Fit a GLLVM to data par(mfrow = c(1,2)) plot(fitp, which = 1:2) plot(fitnb, which = 1:2)
You could do these comparisons with Laplace method as well, using the code below, and it would give the same conclusion that NB distribution suits best:
fitLAp <- gllvm(y=spider$abund, family = poisson(), method = "LA", num.lv = 2) fitLAnb <- gllvm(y=spider$abund, family = "negative.binomial", method = "LA", num.lv = 2) fitLAzip <- gllvm(y=spider$abund, family = "ZIP", method = "LA", num.lv = 2) AIC(fitLAp) AIC(fitLAnb) AIC(fitLAzip)
GLLVM with two latent variables can be used as a model-based approach to unconstrained ordination, as considered at the first day of the workshop.
E3. Fit GLLVM with environmental variables soil.dry
and reflection
to the data with suitable number of latent variables.
Show the answers.
We can extract the two columns from the environmental variable matrix or define the model using formula.
# `soil.dry` and `reflection` are in columns 1 and 6 X <- spider$x[,c(1,6)] fitx1 <- gllvm(spider$abund, X, family = "negative.binomial", num.lv = 1) fitx2 <- gllvm(spider$abund, X, family = "negative.binomial", num.lv = 2) fitx3 <- gllvm(spider$abund, X, family = "negative.binomial", num.lv = 3) AIC(fitx1) AIC(fitx2) AIC(fitx3) # Or alternatively using formula: fitx1 <- gllvm(spider$abund, spider$x, formula = ~soil.dry + reflection, family = "negative.binomial", num.lv = 1) fitx1
Model with one latent variable gave the lowest AIC value.
E4. Explore the model fit. Find the coefficients for environmental covariates.
Show the answers.
Estimated parameters can be obtained with coef()
function. Confidence intervals for parameters are obtained with confint()
.
coef(fitx1) # Coefficients for covariates are named as `Xcoef` # Confidence intervals for these coefficients: confint(fitx1, parm = "Xcoef") # The first 12 intervals are for soil.dry and next 12 for reflection
Problems? See hints:
I have problems in model fitting. My model converges to infinity or local maxima:
GLLVMs are complex models where starting values have a big role. Choosing a different starting value method (see argument starting.val
) or use multiple runs and pick up the one giving highest log-likelihood value using argument n.init
. More variation to the starting points can be added with jitter.var
.
My results does not look the same as in answers: The results may not be exactly the same as in the answers, as the initial values for each model fit are slightly different, so the results may also differ slightly.
getResidualCor
function can be used to estimate the correlation matrix of the linear predictor across species.
Let's consider first the correlation matrix based on a model without predictors: $g(E(y_{ij})) = \beta_{0j} + \boldsymbol{u}_i'\boldsymbol{\theta}_j$
fitnb <- gllvm(spider$abund, family = "negative.binomial", num.lv = 2)
The residual correlations can be visualized either using biplot, which shows the species ordination, or visualizing the actual correlation matrix using, eg., a corrplot
package.
The biplot can be produced using a function ordiplot()
with an argument biplot = TRUE
:
fitnb <- gllvm(spider$abund, family = "negative.binomial", num.lv = 2) ordiplot(fitnb, biplot = TRUE) abline(h = 0, v = 0, lty=2)
par(mfrow=c(1,1), mar=c(4,4,0.1,0.1)) ordiplot(fitnb, biplot = TRUE) abline(h = 0, v = 0, lty=2)
corrplot()
function:fitnb <- gllvm(spider$abund, family = "negative.binomial", num.lv = 2) cr <- getResidualCor(fitnb) library(corrplot); corrplot(cr, diag = FALSE, type = "lower", method = "square", tl.srt = 25)
ordiplot(fitnb, biplot = TRUE) abline(h = 0, v = 0, lty=2)
soil.dry
(soil dry mass) and reflection
(reflection of the soil surface with a cloudless sky), which shows different environmental gradients in ordination: rbPal <- c("#00FA9A", "#00EC9F", "#00DFA4", "#00D2A9", "#00C5AF", "#00B8B4", "#00ABB9", "#009DBF", "#0090C4", "#0083C9", "#0076CF", "#0069D4", "#005CD9", "#004EDF", "#0041E4", "#0034E9", "#0027EF", "#001AF4", "#000DF9", "#0000FF") X <- spider$x[,c(1,6)] par(mfrow = c(1,2), mar=c(4,4,2,2)) for(i in 1:ncol(X)){ Col <- rbPal[as.numeric(cut(X[,i], breaks = 20))] ordiplot(fitnb, symbols = T, s.colors = Col, main = colnames(X)[i], biplot = TRUE) abline(h=0,v=0, lty=2) }
coefplot()
plots point estimates of the species specific environmental coefficients $\boldsymbol{\beta}_{j}$ with confidence intervals.fitx1 <- gllvm(spider$abund, X, family = "negative.binomial", num.lv = 1) coefplot(fitx1, mfrow = c(1,2), cex.ylab = 0.8)
dry.soil
and reflection
were accounted, negative correlation between species do not seem to exist anymore, indicating that negative correlations were explained by different environmental conditions at sites and how species respond to them, rather than direct species interactions.crx <- getResidualCor(fitx1) corrplot(crx, diag = FALSE, type = "lower", method = "square", tl.srt = 25)
If species trait variables $\boldsymbol{t}j$, measuring eg. species behaviour or physical appearance, would be available, fourth corner models should be considered: $g(E(y{ij})) = \beta_{0j} + \boldsymbol{x}i'\boldsymbol{\beta}{j} + \boldsymbol{x}i'\boldsymbol{B}{I}\boldsymbol{t}_j + \boldsymbol{u}_i'\boldsymbol{\theta}_j$
Such models can also be fitted with gllvm()
function by including a matrix of traits with argument TR
.
Examples can be found in the gllvm package's vignettes.
Any scripts or data that you put into this service are public.
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.