Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

12.3 Summary

This section summarises the key steps and syntax for specifying, fitting, inspecting, and visualising CFA and SEM models using semopy.


Specifying a Model

In SEM, models are defined using a string-based syntax that separates the measurement model (relationships between observed and latent variables) from the structural model (relationships between latent variables).

desc = '''# Measurement model
          latent_factor1 =~ x1 + x2 + x3
          latent_factor2 =~ x4 + x5 + x6

          # Structural model
          latent_factor2 ~ latent_factor1'''

This example specifies two latent variables, each measured by three observed variables, and a structural regression in which latent_factor1 predicts latent_factor2.


Higher-order Factors

Latent variables can themselves be indicators of a higher-order latent variable:

desc = '''# First-order measurement model
          latent_factor1 =~ x1 + x2 + x3
          latent_factor2 =~ x4 + x5 + x6

          # Higher-order factor
          general_factor =~ latent_factor1 + latent_factor2'''

Variances and Covariances

Variances and covariances are specified using the ~~ operator:

desc = '''latent_factor1 =~ x1 + x2 + x3
          latent_factor2 =~ x4 + x5 + x6

          # Allow latent factors to covary
          latent_factor1 ~~ latent_factor2
          '''

Covariances can be fixed to zero to impose independence assumptions:

latent_factor1 ~~ 0*latent_factor2

Overview of Operators


Fitting a Model

model = semopy.Model(desc)
model_fit = model.fit(data)

Extracting Model Estimates

estimates = model.inspect(std_est=True)
print(estimates)

Extracting Fit Measures

stats = semopy.calc_stats(model)
print(stats.T)

Visualising the Model

semopy.semplot(model, plot_covs=True, std_ests=True, filename='data/plot.pdf')