An R
and python
package for structural equation modeling using Torch
. This package is meant for researchers who know their way around SEM, Torch, and lavaan.
Structural equation modeling is implemented as a fully functional torch.nn
module. A short example optimization loop would be:
import tensorsem as ts
model = ts.StructuralEquationModel(opt = opts) # opts are of class SemOptions
optim = torch.optim.Adam(model.parameters()) # init the optimizer
for epoch in range(1000):
optim.zero_grad() # reset the gradients of the parameters
Sigma = model() # compute the model-implied covariance matrix
loss = ts.mvn_negloglik(dat, Sigma) # compute the negative log-likelihood, dat tensor should exist
loss.backward() # compute the gradients and store them in the parameter tensors
optim.step() # take a step in the negative gradient direction using adam
To install the latest version of tensorsem
, run the following:
- Install the
R
interface package from this repository:remotes::install_github("vankesteren/tensorsem")
- Install
pytorch
on your system. Use thepytorch
website to do this. For example, for a windows pip cpu version, use:pip install torch==1.5.0+cpu torchvision==0.6.0+cpu -f https://download.pytorch.org/whl/torch_stable.html
- Install the
tensorsem
python
package from this repository.pip install https://github.com/vankesteren/tensorsem/archive/master.zip
- (Optional) Install
pandas
andmatplotlib
for plotting and parameter storingpip install matplotlib pandas
See the example directory for a full usage example, estimating the Holzinger-Swineford model using maximum likelihood, unweighted least squares, and diagonally weighted least squares.