Latent Variables
How do you model something you cannot observe, and how do you know the model is not a fiction?
In 1921 Sewall Wright drew arrows between variables and showed how correlations follow from them; in 1969 Karl Jöreskog joined his paths to Spearman's factors, and the structural equation model became psychology's way to state a theory about unobservables. The part derives the tracing rule, builds and identifies the factor model, fits Holzinger and Swineford's nine tests by maximum likelihood (checked against lavaan), judges fit and shows fixed cut-offs passing a wrong model, undoes attenuation, tests invariance across two schools, finds a significant indirect effect that is not there, shows that equivalent diagrams fit identically, that a cross-lagged panel confuses stable people with change, and that a factor and a network can imply the same covariances, and ends with eight questions for reading an SEM paper.
What you need. Part 3's reliability, Part 32's factor analysis and Part 43's workflow; matrices, the normal likelihood and least squares.
- Hook
- Wright's guinea pigs; the 1939 test battery
- Ideas, models and mathematics
- path analysis, confirmatory factor analysis, structural equation models, identification, fit, invariance, mediation and its limits, equivalent models, networks against factors
- Psyche gains
psyche.sem- On you
- draw the model that fits as well
What you will be able to do
Psych 101 and the major
- Read a path diagram: latent and observed variables, loadings, errors, and what an arrow claims.
- Explain why a good fit does not show that the arrows point the right way.
Graduate
- Derive model-implied correlations by the tracing rule and as Σ = ΛΦΛᵀ + Θ; count parameters to check identification, and fit a confirmatory factor model by maximum likelihood.
- Compute χ², RMSEA, CFI and SRMR, and test configural, metric and scalar invariance.
- Simulate a confounded mediator and show the product-of-coefficients estimate is biased.
Research
- Say what causal discovery can orient from conditional independences, and what its assumptions demand of psychological data.
Practice
- Audit a survey or people-analytics model by asking which equivalent diagram fits as well, and whether the score is comparable across groups.
Contents
Each chapter has a home level. Choose a track to see what to read and watch: Psych 101 and the major 10 min · Graduate 26 min · Research 27 min · Practice 11 min.
- 0One matrix, three diagramsPsych 101 and the major2 min
- 1On you: draw a model, and four numbersPsych 101 and the major1 min
- 2Wright's pathsGraduate1 min
- 3The factor model, confirmedGraduate1 min
- 4Estimation by maximum likelihoodGraduate1 min
- 5Does it fit?Graduate2 min
- 6Measurement and structureGraduate2 min
- 7Measurement invarianceGraduate1 min
- 8MediationGraduate2 min
- 9Equivalent modelsPsych 101 and the major1 min
- 10Latent variables over timeGraduate2 min
- 11Factors or networks?Graduate2 min
- 12Reading an SEM paperPsych 101 and the major2 min
- 13The LedgerGraduate
- 14In practice: surveys, tests and people analyticsPractice1 min
- 15Frontier: causal discovery, Bayes and dynamic fitResearch2 min
- Recap, problems, and the road aheadAll tracks3 min
Also on this page: Lecture · Key results · Try it · Lab · Problems · Notes and sources · Build the film.
Lecture
The text of each chapter is the film's narration, as it is spoken, so you can read along or revise without the film. The pictures are in the film.
One matrix, three diagramsPsych 101 and the major2 min
Here is a correlation matrix for three variables. A thousand simulated people, generated by a chain: X causes M, and M causes Y. Now fit three diagrams: the chain, the chain reversed, and a fork, with M as the common cause of both. They fit these data exactly equally well, to the second decimal place. The data can't say which diagram is true. Only the design of the study can.
The idea has two roots. In 1921 the geneticist Sewall Wright drew arrows between variables, and showed how their correlations follow from the arrows. He called it path analysis. Spearman had already explained correlations by an unseen common factor, in Part 32. In 1969 Karl Jöreskog joined the two: factors measured by indicators, arrows between the factors, all estimated by maximum likelihood. The structural equation model became psychology's standard way to state a theory about things it can't observe. Its standard abuse is to forget the diagrams that fit equally well.
So this part asks how to model something you can't observe, and how to know the model isn't a fiction. Paths, factors, and the model that joins them. Estimation, fit, and the cut-offs people use to judge it. Invariance, mediation, and models that fit equally. And time, networks, and how to read a paper that uses all this.
This is Part 44 of Psychology, Built: latent variables, and the start of the graduate toolkit. We'll derive Wright's tracing rules. We'll build the factor model, identify it, and estimate it by maximum likelihood. We'll judge fit: the chi-square test, RMSEA, CFI, and cut-offs that depend on the model. We'll correct a regression for unreliability, and test whether a measure means the same thing in two groups. We'll see why mediation stays correlational. And we'll meet equivalent models, growth over time, and factors against networks.
What it does: Three diagrams that fit equally; Wright's arrows and Spearman's factors; the question; objectives
1On you: draw a model, and four numbersPsych 101 and the major1 min
First, three stories. Stress disturbs sleep, which lowers mood. Or low mood disturbs sleep, which raises stress. Or poor sleep raises both stress and low mood. Draw each one as a diagram. All three imply the same correlation matrix, and fit any data equally well. One diagram on the same three variables does differ: stress and mood both disturbing sleep. That one implies stress and mood are uncorrelated, and it can be rejected. On the course site, you can try to draw a model that fits as well as the true one.
Now four numbers to write down before the part answers them. One: nine ability tests, three factors, three hundred and one children. Does the model pass the chi-square test of exact fit? Two: two traits correlate zero point five, and each is measured by three items with loadings of zero point six. What do the sum scores correlate? Three: a randomized treatment, a measured mediator, and no real indirect effect. Can the analysis still find one? And four: how many different diagrams can fit a correlation matrix exactly as well as the true one? Pause here, and write them down.
What it does: Three stories as diagrams; four predictions
2Wright's pathsGraduate1 min
Wright's rule turns arrows into correlations. Take standardized variables, arrows for direct effects, and no loops. A correlation is the sum, over every path that links two variables, of the product of the coefficients along it. A path may go backward along the arrows and then forward, but never forward then backward, and through no variable twice. Here, the correlation of A and D is a c plus b d. And B and C correlate a times b, though neither causes the other, through their common cause A.
In matrix form, Wright's rule is one line. Each variable equals the arrows into it plus a disturbance. B holds the arrows, and psi holds the covariances of what the arrows leave unexplained. The implied covariance is the inverse of I minus B, times psi, times its transpose. Expand the inverse as I plus B plus B squared and so on, and each power sums the paths of one length. That's Wright's rule. Psyche computes it for any model without loops, and the tests check it against the tracing rule.
What it does: The tracing rule; in matrix form
3The factor model, confirmedGraduate1 min
Now the factor model. In 1939 Karl Holzinger and Frances Swineford gave nine tests to three hundred and one children in two schools: three visual, three verbal, and three of speed. A confirmatory model says each test measures one factor and nothing else, and the factors may correlate. The missing arrows are the claim. The implied covariance matrix is lambda phi lambda transpose, plus theta: loadings, factor covariances, and each test's own error variance.
Before estimating, count. A factor has no units of its own, so fix one loading per factor to one, or its variance to one, to give it a scale. The knowns are the nine variances and thirty-six covariances: forty-five in all. The unknowns are six free loadings, three factor variances, three factor covariances, and nine error variances: twenty-one. That leaves twenty-four degrees of freedom: twenty-four testable constraints. A factor needs at least three indicators to be identified on its own. A model with more unknowns than knowns can't be estimated at all, and one with exactly as many fits perfectly, and tests nothing.
What it does: Nine tests, three factors; identification by counting
4Estimation by maximum likelihoodGraduate1 min
Estimation means choosing the unknowns that bring the model closest to the data. If the data are multivariate normal, minimizing this discrepancy is maximizing the likelihood. It's zero exactly when the model reproduces the observed covariances. Psyche minimizes it numerically over the twenty-one unknowns, from rough starting values, in about half a second. And n times the minimum is, if the model is exactly right, a chi-square on the model's degrees of freedom.
Here is the model, fitted to Holzinger and Swineford's children. The standardized loadings run from about zero point four to zero point nine. The factors correlate: visual with verbal and with speed, both a little under zero point five, and verbal with speed about zero point three. The chi-square is eighty-five on twenty-four degrees of freedom. And every number matches lavaan, the reference package in R, to three decimal places. The tests check it.
What it does: The discrepancy function; Holzinger and Swineford, fitted
5Does it fit?Graduate2 min
First, the chi-square test of exact fit. If the model were exactly right, the statistic would come from this curve, centred near twenty-four. The data give eighty-five. The model is rejected, decisively. A single general factor does far worse. But no model of real people is exactly right, and with enough people the test rejects every one. It answers a question nobody really asked.
So people use approximate fit. RMSEA measures misfit per degree of freedom and per person. CFI asks how much better the model is than a model with no correlations at all. TLI asks the same, with a penalty for complexity. And SRMR is the average residual correlation. In 1999 Li-tze Hu and Peter Bentler proposed cut-offs, from simulations of a few model types: CFI at least zero point nine five, RMSEA at most zero point oh six. By them this model fails. And the cut-offs became rules in thousands of papers.
But a cut-off only means something for a particular model. Psyche draws two hundred samples of three hundred and one children from the fitted model, and two hundred from the same model with one cross-loading left out. When the model is right, almost all the RMSEAs fall low. When it's wrong, they spread higher, but most still fall below the conventional cut-off, and nearly every CFI passes too. The fixed cut-offs pass a model that's wrong. In 2023 Daniel McNeish and Melissa Wolf proposed dynamic cut-offs: simulate from your own model to set them. A fixed zero point oh six can be far too strict, or far too lenient.
What it does: The chi-square test; approximate fit; cut-offs that depend on the model
6Measurement and structureGraduate2 min
A full structural equation model has two layers. The measurement model: each latent variable and its indicators, with their errors. The structural model: arrows between the latent variables themselves, a regression among things never observed. Because the errors are modelled, the structural arrows are free of measurement error. It's Part 3's correction for attenuation, done inside the model.
Here is the correction at work. Psyche makes two traits that correlate zero point five, each measured by three items with loadings of zero point six, in five hundred people. The sum scores have a reliability of about zero point six, and correlate only about zero point three. The two-factor model recovers about zero point five: the relation between the traits, not the tests. The correction is only as good as the measurement model. If the items measure something else as well, it corrects the wrong thing.
The loadings also say how reliable a scale is. The share of a sum score that is true score is the squared sum of the loadings, over that plus the error variances. It's McDonald's omega. For Holzinger and Swineford's three factors, omega and Part 3's alpha agree. But they agree only when the loadings are alike. With loadings of zero point nine, eight, three and two, alpha is about zero point six and omega about zero point six seven. Alpha understates. Alpha assumed equal loadings. The factor model tests that assumption instead of making it.
What it does: Two layers; attenuation, undone; reliability from the loadings
7Measurement invarianceGraduate1 min
Before comparing two groups on a test, ask whether the test means the same thing in both. Configural invariance: the same diagram in each group, the same tests loading on the same factors. Metric invariance: the same loadings, so a unit of the factor moves each test by the same amount. That's needed to compare correlations and regressions. Scalar invariance: the same intercepts too, so people with the same factor score expect the same test score. That's needed to compare means. William Meredith formalized the ladder in 1993. Without the third rung, a difference in mean scores can be a difference in the test, not in the people. Parts 32 and 38 owed this chapter.
Holzinger and Swineford's children came from two schools. Fit the three-factor model in both at once. Holding the loadings equal costs little: an acceptable change in chi-square. Holding the intercepts equal costs about forty: rejected. Some tests are easier in one school for children of the same ability. If scalar invariance is assumed anyway, Grant-White looks more than half a point higher on the verbal factor. It's a comparison the data don't license as it stands. These numbers match lavaan exactly.
What it does: Three rungs; two schools
8MediationGraduate2 min
A treatment works. Through what? X is the treatment, M a proposed mechanism, Y the outcome. Regress M on X for the path a. Regress Y on M and X for the path b, and the direct effect. The indirect effect is a times b, with a bootstrap interval. Reuben Baron and David Kenny wrote the recipe in 1986, and it's been cited tens of thousands of times. Here's the trap. X can be randomized, but M is not. The regression of Y on M is an observational one, with every confound that brings.
Watch the trap close. Psyche runs an experiment. X is randomized, and X raises M. But M does nothing at all to Y. An unmeasured trait, U, raises both M and Y. The recipe finds an indirect effect of about zero point one seven, with an interval well clear of zero. A mechanism, significant, and false. Randomizing X protects the total effect, not its split into paths.
So what would show a mechanism? Manipulate M: a second experiment that moves the mechanism directly, and watches Y. Or design in parallel: the treatment with and without the mechanism blocked. At least, a sensitivity analysis: how strong would a confound of M and Y have to be to erase the indirect effect? Or say less: consistent with mediation, never explained by, from one randomized X. John Bullock, Donald Green and Shang Ha made the case in 2010, under the title: yes, but what's the mechanism? Don't expect an easy answer. This chapter's Ledger row is a mediator that failed when it was manipulated.
What it does: The recipe; a mechanism that is not there; what would show a mechanism
9Equivalent modelsPsych 101 and the major1 min
Psyche makes three variables, with X causing M and M causing Y. Now fit four diagrams. The true chain. The chain reversed: Y causes M, M causes X. A fork: M causes both. The first three fit identically, to every decimal. They imply the same thing, that X and Y are independent given M. The data can't choose among them, ever. Only the collider differs. It says X and Y are independent, and the data reject it.
This is general. In 1993 Robert MacCallum and colleagues showed that most published models had equivalent models, often many, with arrows reversed or replaced by correlations. In a survey of fifty-three published applications, almost none acknowledged them. A good fit says the model belongs to a family the data can't tell apart. The arrows come from design, time order and theory, not from the fit. It's Part 2's lesson again. A direction is something an experiment tests, not something a correlation matrix announces.
What it does: Four diagrams, one matrix; what fit cannot tell you
10Latent variables over timeGraduate2 min
Measure the same people four times. A growth-curve model gives each person two latent variables: where they start, and how fast they change. The loadings are fixed, not estimated: one, one, one, one for the start, and zero, one, two, three for the slope. The variance of the slope says whether people differ in how they change. Its correlation with the start says whether the high fall back or pull ahead. It's the same model as the mixed model behind Part 31's growth curves for children, written as a diagram.
Now two traits, measured at three waves. Say, loneliness and low mood. The cross-lagged panel model lets each predict itself next time. And each predict the other, controlling for the past. If loneliness at one wave predicts low mood at the next, it is read as a driver. Thousands of papers read it that way.
Here is the catch. Psyche makes two thousand people, measured four times. They differ stably in the two traits, and the stable parts correlate. But within any one person, neither trait does anything to the other. The cross-lagged panel finds an effect anyway, about eleven standard errors from zero, because the past score is a noisy stand-in for the stable trait. Within each person, the effect is nothing. Ellen Hamaker, Rebecca Kuiper and Raoul Grasman made the point in 2015. A random-intercept model separates the stable person from the wave-to-wave change, and a claim about one trait driving another is a claim about change.
What it does: Growth curves; the cross-lagged panel; between people or within?
11Factors or networks?Graduate2 min
Two pictures of a disorder. In the first, a hidden cause, the disorder, produces each symptom, the way a diagnostic category assumes. In the second, Part 39's symptom network, there's no hidden cause. The symptoms cause each other. Denny Borsboom and Angélique Cramer argued for the second in 2013: poor sleep causes fatigue, fatigue causes poor focus, poor focus causes worry. No hidden depression needed.
Can data decide between the pictures? Psyche writes down a single factor, with loadings of zero point eight, seven, six and five. The correlations follow. Now compute the partial correlations. They're a network: every pair joined, the strongest edges where the loadings are largest. The network reproduces the correlations exactly. Any covariance matrix has a network that fits it perfectly. Joost Kruis and Gunter Maris proved the stronger result in 2016. For yes-or-no symptoms, the network, a latent-variable model and a common-cause model are the same distribution. Part 39 stated it; this is the simplest case, computed. The fit can't decide.
So what could decide? Intervention. Treat sleep alone. In a network, fatigue and focus should improve too; under a common cause, they shouldn't. Time. With data within each person over weeks, as in Part 47, does sleep today predict fatigue tomorrow in the same person? And stability. A network estimated from a few hundred people can change from sample to sample, so bootstrap its edges before reading them. And the answer may be both: a common cause and direct links together. The question is how much of each.
What it does: Two pictures of a disorder; the same covariances; what could decide
12Reading an SEM paperPsych 101 and the major2 min
Here is an abstract, invented for practice, in a shape you'll meet often. Four hundred and twelve employees, surveyed once. Workload leads to burnout, which leads to turnover intention. The model fit well, and burnout fully mediated the effect. Surveyed once: leads to is a direction that one wave of data can't show. Fit well: by fixed cut-offs, which pass wrong models, and the reversed chain fits identically. Fully mediated: the mediator wasn't manipulated, and here nothing was. What it does show: the three measures are related the way a chain would imply. So would other diagrams.
Eight questions for any paper with a path diagram. Is the diagram drawn, with every fixed and free parameter, and the degrees of freedom? Which equivalent models fit as well, and why were they set aside? Were the data collected over time, or in an experiment, for the arrows that need it? Is the chi-square reported, and fit judged for this model, not by fixed cut-offs? Was the model changed after looking at the fit, and does the paper say so? Was invariance tested before groups were compared? Are the measures reliable, and is measurement modelled? And are the data and code open, so another analyst can fit a different diagram?
What it does: An invented abstract; eight questions
13The LedgerGraduate
What the three have in common. Each is a claim about a model, not about a single study's data. The mediator failed when it was moved by hand. The cut-offs failed outside the simulations they came from. The theorem holds because it is a theorem. A model is a claim too. It goes in the Ledger, and it can fail.
What it does: Three rows; what they have in common
14In practice: surveys, tests and people analyticsPractice1 min
Where these models earn their keep. Test validation: a new questionnaire's factor structure confirmed in a fresh sample, with its reliability from the loadings. Surveys across countries: invariance tested before an engagement or wellbeing score is ranked across countries, languages or groups. People analytics: engagement, burnout and intention to leave as latent variables, with measurement error modelled rather than ignored. And marketing: models of customer satisfaction, trust and loyalty, and of attitudes in advertising.
In every one of these settings, one question does the most work. What other diagram fits these data equally well, and what would tell them apart? A dashboard that says engagement drives retention has drawn one arrow of several that fit. A score compared across teams or countries needs scalar invariance first. And the cheapest answer is often an experiment: change one thing for some teams, and watch.
What it does: Where the models work; the question to ask
15Frontier: causal discovery, Bayes and dynamic fitResearch2 min
Can the arrows be found, rather than assumed? Take chapter nine's four diagrams. For the chain, its reverse and the fork, the data reveal the edges but not their direction. Only the collider is oriented, because X and Y are independent until M is known. Algorithms such as Peter Spirtes, Clark Glymour and Richard Scheines's PC test conditional independences, and return the family of diagrams that fits, orienting only what the data force. They assume every common cause is measured, and that no independence is a coincidence. Psychological data, with latent traits behind everything, rarely oblige. An open question: how much can discovery add when the variables are themselves noisy measures?
Two more frontiers. Bayesian structural equation models put priors on small cross-loadings, keeping them near zero instead of exactly zero, as Bengt Muthén and Tihomir Asparouhov proposed in 2012. It helps small samples, and the priors must be reported and varied. Dynamic fit simulates from this model, with a misspecification of a stated size, and sets the cut-off from the simulation, as Daniel McNeish and Melissa Wolf proposed. It makes chapter five's lesson routine. And open: which misspecifications matter for the question being asked, and how big is too big?
What it does: What discovery can orient; small samples and fit for this model
Recap, problems, and the road aheadAll tracks3 min
First, your four numbers. The three-factor model fails the exact-fit test, with a chi-square of eighty-five on twenty-four degrees of freedom. The sum scores correlate about zero point three, when the traits correlate zero point five. Mediation can be found when there is none: zero point one seven, with an interval clear of zero. And two other diagrams fit exactly as well as the true one here; in published models, often many more. A model can be rejected and useful, corrected and still wrong, significant and false, and never the only one.
Part forty-four in twelve lines. A correlation is a sum over the paths that join two variables. A factor model is a diagram, written as a matrix equation. Identification fixes a scale and counts parameters against moments. Maximum likelihood fits the diagram to the covariances. The chi-square test rejects every model in time, and fixed cut-offs pass wrong ones. Modelled measurement undoes attenuation. Compare means only with scalar invariance. A randomized treatment doesn't randomize the mediator. Equivalent models fit identically, so arrows come from design. The cross-lagged panel confuses stable people with change. Factors and networks can imply the same data. And eight questions for reading a path diagram.
Kant's wager. The first objection, that mathematics can't apply to the mind, met Wright's rules, maximum likelihood, fit and invariance, all computed and checked against a reference implementation. The second, that the mind can't be experimented on: the arrows of a model are claims an experiment must test, and the fit can't. Amber. And the third, about introspection: the indicators are mostly questionnaires. The model handles their random error, not their bias. Amber.
Where this comes back. A latent trait behind each single item is next, in Part 45. Within-person models over time are Part 47. Models of behaviour, fitted and compared, are Part 48. And the weight of evidence across studies is Part 50.
Seven problems, with full solutions in this part's README. One traces paths. One counts parameters and degrees of freedom. One computes an RMSEA. One corrects for attenuation. One tests invariance. One finds equivalent models. And the last, with the star, asks you to redraw an abstract two ways and design the study that would tell them apart. Pause here if you'd like to try them.
The books and papers behind this part are listed here and in the README. Rex Kline's textbook is the standard course; Kenneth Bollen's is the mathematics; and Julia Rohrer's short paper on correlation and causation is the best first read on what a diagram can and can't claim.
The graduate toolkit has begun. This part modelled what no one observes, and showed what the fit can and can't say. Next, the single encounter of one person with one question. How can two people who took different questions be put on the same scale? Part 45: item response theory.
Where it goes next. Item response theory is Part 45; within-person models over time Part 47; models of behaviour Part 48; the weight of evidence Part 50.
Key results
The part's results in one place, for revision.
Try it
Lab 44 · Latent Variables
Fit the three-factor model to Holzinger and Swineford's tests, judge its fit, test whether the two schools can be compared, then see three ways a well-fitting model can still mislead: attenuation, a confounded mediator, and diagrams that fit identically.
python -m videos.psychology.labs 44
needs numpy, scipy, matplotlib · download lab44.py ·
source on GitHubtracing rule: X -> M (0.5) -> Y (0.6) gives r(X, Y) 0.30
three factors: chi2 / df; CFI; TLI; RMSEA; SRMR 85.31 / 24; 0.931; 0.896; 0.092; 0.065
one factor: chi2 / df; CFI; RMSEA 312.3 / 27; 0.677; 0.187
invariance: chi2 (df) configural; metric; scalar 115.85 (48); 124.04 (54); 164.10 (60)
loadings equal: delta chi2 on 6 df, p; intercepts equal: delta chi2, p 8.19, 0.22; 40.06, 4.4e-07
attenuation: sum scores correlate; the factors (truth 0.5) 0.32; 0.49
a confounded mediator with no effect: indirect a*b and 95% interval 0.169 [0.099, 0.250] (truth 0.0)
equivalent models: largest gap between chain, reverse and fork; collider differs 0.0e+00; 0.30
The three-factor model is rejected by χ² but describes the tests well; the schools share loadings but not intercepts, so their means cannot be compared as they stand; and fit cannot rescue a confounded mediator or choose among equivalent diagrams.
The code (92 lines; it asserts its own result)
"""Lab 44: latent variables: tracing rules, a confirmatory factor model fitted by maximum likelihood to Holzinger and
Swineford's nine tests, fit indices, invariance across two schools, attenuation, a confounded mediator, and
equivalent models."""
import numpy as np
from videos.coursekit import labs
from explainer.psychology import opendata
from explainer.psychology.psyche import sem as E
TITLE = "Latent Variables"
GOAL = ("Fit the three-factor model to Holzinger and Swineford's tests, judge its fit, test whether the two schools "
"can be compared, then see three ways a well-fitting model can still mislead: attenuation, a confounded "
"mediator, and diagrams that fit identically.")
TASKS = [
"Free the loading of x9 on the visual factor. How much does χ² fall, for one degree of freedom, and what happens "
"to the RMSEA?",
"Raise the confounding in the mediation simulator to 0 and to 1.0. How does the indirect effect's interval move?",
"Make the traits in the attenuation simulation correlate 0.8 with loadings 0.4. How far are the sum scores off?",
]
P3 = np.zeros((9, 3), int)
P3[0:3, 0] = 1
P3[3:6, 1] = 1
P3[6:9, 2] = 1
def run(seed=0):
out = labs.Lab()
out.row("tracing rule: X -> M (0.5) -> Y (0.6) gives r(X, Y)", f"{0.5 * 0.6:.2f}")
h = opendata.holzinger_1939()
X = h["X"]
n = len(X)
S = np.cov(X.T, bias=True)
r3 = E.fit_cfa(S, n, P3)
r1 = E.fit_cfa(S, n, np.ones((9, 1), int))
out.row("three factors: chi2 / df; CFI; TLI; RMSEA; SRMR",
f"{r3['T']:.2f} / {r3['df']}; {r3['cfi']:.3f}; {r3['tli']:.3f}; {r3['rmsea']:.3f}; {r3['srmr']:.3f}")
assert abs(r3["T"] - 85.306) < 0.05 and r3["df"] == 24
out.row("one factor: chi2 / df; CFI; RMSEA", f"{r1['T']:.1f} / {r1['df']}; {r1['cfi']:.3f}; {r1['rmsea']:.3f}")
sch = np.array(h["school"])
gs = [X[sch == "Pasteur"], X[sch == "Grant-White"]]
inv = {lev: E.fit_multigroup(gs, P3, lev) for lev in ("configural", "metric", "scalar")}
out.row("invariance: chi2 (df) configural; metric; scalar",
"; ".join(f"{inv[k]['T']:.2f} ({inv[k]['df']})" for k in ("configural", "metric", "scalar")))
from scipy import stats
dm = inv["metric"]["T"] - inv["configural"]["T"]
ds = inv["scalar"]["T"] - inv["metric"]["T"]
out.row("loadings equal: delta chi2 on 6 df, p; intercepts equal: delta chi2, p",
f"{dm:.2f}, {stats.chi2.sf(dm, 6):.2f}; {ds:.2f}, {stats.chi2.sf(ds, 6):.1e}")
rng = np.random.default_rng(seed + 44)
m = 500
F = rng.multivariate_normal([0, 0], [[1, 0.5], [0.5, 1]], m)
Xs = np.column_stack([0.6 * F[:, j // 3] + 0.8 * rng.normal(0, 1, m) for j in range(6)])
P2 = np.zeros((6, 2), int)
P2[:3, 0] = 1
P2[3:, 1] = 1
r2 = E.fit_cfa(np.cov(Xs.T, bias=True), m, P2)
d = np.sqrt(np.diag(r2["Phi"]))
out.row("attenuation: sum scores correlate; the factors (truth 0.5)",
f"{np.corrcoef(Xs[:, :3].sum(1), Xs[:, 3:].sum(1))[0, 1]:.2f}; {r2['Phi'][0, 1] / (d[0] * d[1]):.2f}")
med = E.mediation(seed=seed + 44, boots=500)
out.row("a confounded mediator with no effect: indirect a*b and 95% interval",
f"{med['indirect']:.3f} [{med['lo']:.3f}, {med['hi']:.3f}] (truth {med['true']:.1f})")
eq = E.markov_equivalent()
out.row("equivalent models: largest gap between chain, reverse and fork; collider differs",
f"{max(np.abs(eq[k] - eq['chain']).max() for k in ('reverse', 'fork')):.1e}; "
f"{np.abs(eq['collider'] - eq['chain']).max():.2f}")
out.note = ("The three-factor model is rejected by χ² but describes the tests well; the schools share loadings "
"but not intercepts, so their means cannot be compared as they stand; and fit cannot rescue a "
"confounded mediator or choose among equivalent diagrams.")
fig, ax = labs.figure(2, size=(11, 4.0))
std = r3["L"] * np.sqrt(np.diag(r3["Phi"]))[None, :] / np.sqrt(np.diag(r3["Sigma"]))[:, None]
ax[0].bar(range(1, 10), std.sum(1), color=[labs.BLUE] * 3 + [labs.GREEN] * 3 + [labs.RED] * 3)
ax[0].set(title="standardized loadings, three factors", xlabel="test", ylabel="loading")
levs = ("configural", "metric", "scalar")
ax[1].bar(levs, [inv[k]["T"] for k in levs], color=[labs.BLUE, labs.GREEN, labs.RED])
ax[1].set(title="invariance across two schools", ylabel="chi-square")
out.fig = fig
return out
if __name__ == "__main__":
print(run())
Now change it
- Free the loading of x9 on the visual factor. How much does χ² fall, for one degree of freedom, and what happens to the RMSEA?
- Raise the confounding in the mediation simulator to 0 and to 1.0. How does the indirect effect's interval move?
- Make the traits in the attenuation simulation correlate 0.8 with loadings 0.4. How far are the sum scores off?
Problems, with solutions
Try each problem before opening its solution.
-
Tracing. X causes M with standardized path 0.5, and M causes Y with path 0.6. Use Wright's tracing rules to find the correlation of X and Y.
Solution
The only path from X to Y runs through M, so r(X, Y) = 0.5 × 0.6 = 0.30.
-
Counting. Nine tests, three factors, each test loading on one factor, a marker loading fixed for each factor. Count the free parameters and the degrees of freedom.
Solution
Free parameters: 9 loadings less 3 markers = 6, plus 3 factor variances and 3 covariances, plus 9 residual variances: 21. Moments: 9 × 10/2 = 45. Degrees of freedom: 45 - 21 = 24.
-
RMSEA. \(\chi^2 = 85.3\) on 24 df with \(n = 301\). Compute the RMSEA.
Solution
√((85.3 - 24)/(24 × 301)) = √(61.3/7224) = √0.00849 = 0.092.
-
Attenuation. Two sum scores each have reliability 0.63 and correlate 0.32. Correct the correlation for attenuation.
Solution
0.32/√(0.63 × 0.63) = 0.32/0.63 = 0.51, close to the true 0.5.
-
Intercepts. Metric invariance gives \(\chi^2 = 124.0\) on 54 df; scalar, 164.1 on 60. Test the intercepts at 5%.
Solution
Δχ² = 164.1 - 124.0 = 40.1 on 60 - 54 = 6 df; the 5% critical value is 12.6 (p ≈ 4 × 10⁻⁷). Scalar invariance is rejected, so the schools' means are not comparable as they stand.
-
Equivalence. Three variables, edges X–M and M–Y. Of the four ways to direct the two edges, which fit identically, and why?
Solution
X → M → Y, Y → M → X and X ← M → Y all imply that X and Y are independent given M and nothing else, so they fit identically, always. X → M ← Y implies that X and Y are independent, a different constraint.
-
★ The abstract. For chapter 12's invented abstract, draw two diagrams that fit equally well, and design a study that would tell them apart.
Solution
Burnout → workload perceptions → turnover intention, or turnover intention → burnout → workload perceptions, fit as well as the authors' chain. A study that tells them apart: randomize a reduction in workload (for instance, staffing) across teams, measure burnout and intention monthly, and preregister that burnout should fall before intention does; a second arm that targets burnout without changing workload tests the mediator directly.
Notes and sources
Sources
- S. Wright, Correlation and causation, Journal of Agricultural Research 20 (1921) 557-585; K. G. Jöreskog, A general approach to confirmatory maximum likelihood factor analysis, Psychometrika 34 (1969) 183-202; K. A. Bollen, Structural Equations with Latent Variables (Wiley, 1989); R. B. Kline, Principles and Practice of Structural Equation Modeling (Guilford).
- K. J. Holzinger and F. F. Swineford, A Study in Factor Analysis: The Stability of a Bi-Factor Solution (University of Chicago, 1939); Y. Rosseel, lavaan: an R package for structural equation modeling, Journal of Statistical Software 48 (2012).
- L. Hu and P. M. Bentler, Cutoff criteria for fit indexes in covariance structure analysis, Structural Equation Modeling 6 (1999) 1-55; H. W. Marsh, K.-T. Hau and Z. Wen (2004); D. McNeish and M. G. Wolf, Dynamic fit index cutoffs for confirmatory factor analysis models, Psychological Methods 28 (2023).
- W. Meredith, Measurement invariance, factor analysis and factorial invariance, Psychometrika 58 (1993) 525-543.
- R. M. Baron and D. A. Kenny, The moderator-mediator variable distinction, Journal of Personality and Social Psychology 51 (1986) 1173-1182; J. G. Bullock, D. P. Green and S. E. Ha, Yes, but what's the mechanism? (don't expect an easy answer), Journal of Personality and Social Psychology 98 (2010) 550-558.
- M. T. Gailliot et al. (2007); F. Lange and F. Eggert (2014); M. A. Vadillo, N. Gold and M. Osman (2016).
- R. C. MacCallum, D. T. Wegener, B. N. Uchino and L. R. Fabrigar, The problem of equivalent models in applications of covariance structure analysis, Psychological Bulletin 114 (1993) 185-199.
- E. L. Hamaker, R. M. Kuiper and R. P. P. P. Grasman, A critique of the cross-lagged panel model, Psychological Methods 20 (2015) 102-116.
- D. Borsboom and A. O. J. Cramer, Network analysis: an integrative approach to the structure of psychopathology, Annual Review of Clinical Psychology 9 (2013) 91-121; J. Kruis and G. Maris (2016); M. Marsman et al. (2018).
- P. Spirtes, C. Glymour and R. Scheines, Causation, Prediction, and Search (2nd edition, MIT Press, 2000); B. Muthén and T. Asparouhov, Bayesian structural equation modeling, Psychological Methods 17 (2012) 313-335; J. M. Rohrer, Thinking clearly about correlations and causation, Advances in Methods and Practices in Psychological Science 1 (2018) 27-42.
About this partfrom its README
In 1921 the geneticist Sewall Wright drew arrows between variables and showed how their correlations follow from the arrows. Spearman had already explained correlations by an unseen common factor. In 1969 Karl Jöreskog joined the two, and the structural equation model became psychology's standard way to state a theory about things nobody observes. Its standard abuse is to forget that very different diagrams fit the same data.
The viewer meets one correlation matrix and three diagrams that fit it equally well, draws a model for three stories, and predicts four numbers. Then Wright's tracing rule, derived and written as a matrix; the confirmatory factor model, identified by counting; maximum likelihood, fitted to Holzinger and Swineford's nine tests and checked against lavaan; fit, from the chi-square test to the indices and the fixed cut-offs that pass a wrong model (computed); the full model, which undoes Part 3's attenuation and gives reliability from the loadings; measurement invariance across the two schools; mediation, and a significant indirect effect that is not there (computed); equivalent models; growth curves and the cross-lagged panel's confusion of stable people with change (computed); factors against networks (computed); and eight questions for reading a paper with a path diagram. This part starts Act XI, the graduate toolkit.
What is computed and built
explainer/psychology/psyche/sem.py: model-implied covariances for path and factor models, the maximum-likelihood discrepancy, confirmatory factor analysis with marker-variable scaling and the χ², RMSEA, CFI, TLI and SRMR, multi-group models with configural, metric and scalar constraints and latent means, Markov-equivalent diagrams, the network implied by a factor model, and a mediation simulator with a bootstrap. Checked against lavaan on Holzinger and Swineford's data; tested intests/psychology/test_sem.py.- The Ledger gains three rows.
- The course's interactive: three variables and a correlation matrix; the reader draws diagrams and sees which fit as well as the true one.
Chapter notes
| # | Chapter | What it does |
|---|---|---|
| 0 | One matrix, three diagrams | Three diagrams that fit equally; Wright's arrows and Spearman's factors; the question; objectives |
| 1 | On you: draw a model, and four numbers | Three stories as diagrams; four predictions |
| 2 | Wright's paths | The tracing rule; in matrix form |
| 3 | The factor model, confirmed | Nine tests, three factors; identification by counting |
| 4 | Estimation by maximum likelihood | The discrepancy function; Holzinger and Swineford, fitted |
| 5 | Does it fit? | The chi-square test; approximate fit; cut-offs that depend on the model |
| 6 | Measurement and structure | Two layers; attenuation, undone; reliability from the loadings |
| 7 | Measurement invariance | Three rungs; two schools |
| 8 | Mediation | The recipe; a mechanism that is not there; what would show a mechanism |
| 9 | Equivalent models | Four diagrams, one matrix; what fit cannot tell you |
| 10 | Latent variables over time | Growth curves; the cross-lagged panel; between people or within? |
| 11 | Factors or networks? | Two pictures of a disorder; the same covariances; what could decide |
| 12 | Reading an SEM paper | An invented abstract; eight questions |
| 13 | The Ledger | Three rows; what they have in common |
| 14 | In practice: surveys, tests and people analytics | Where the models work; the question to ask |
| 15 | Frontier: causal discovery, Bayes and dynamic fit | What discovery can orient; small samples and fit for this model |
| Recap, problems, and the road ahead | Your numbers; twelve lines; Kant's three objections; payoffs; problems; references; Part 45 |
NotesWhere the numbers come from
| What | Source |
|---|---|
| The hook and chapter 9: 1,000 simulated people from the chain X → M → Y (paths 0.5 and 0.6); correlations 0.51, 0.56 and 0.28; the chain, its reverse and the fork each give χ² = 0.32 on 1 df; the collider gives 79.3 | Psyche (sem.markov_equivalent, the item's own regression), item equivalent |
| Holzinger and Swineford's nine tests for 301 children: the three-factor model gives χ² = 85.31 on 24 df, CFI 0.931, TLI 0.896, RMSEA 0.092, SRMR 0.065 (baseline 918.85 on 36); standardized loadings 0.42 to 0.86; factor correlations 0.46, 0.47 and 0.28; one factor: χ² = 312 on 27 df, CFI 0.677, RMSEA 0.187 | opendata.holzinger_1939 (fetched from CRAN and SHA-256 checked); Psyche (sem.fit_cfa), item hs; every value matches lavaan's |
| Fixed cut-offs: 200 samples of 301 from the fitted model, and 200 from a model in which x9 also loads 0.4 on the visual factor, each fitted by the three-factor model: the wrong model passes RMSEA at most 0.06 in 91% of samples and CFI at least 0.95 in all of them | Psyche (sem.fit_cfa), item cutoffs |
| Attenuation: two traits correlated 0.5, three items each with loadings 0.6, 500 simulated people: alpha 0.63, sum scores correlate 0.32, the two-factor model recovers 0.49 | Psyche (sem.fit_cfa), item attenuation |
| Reliability from the loadings: omega 0.63, 0.89 and 0.69 for the three factors' sums, alpha 0.63, 0.88 and 0.69; four standardized loadings 0.9, 0.8, 0.3 and 0.2: alpha 0.60, omega 0.67 | Psyche (sem.fit_cfa), item omega |
| Invariance across the two schools (Pasteur 156, Grant-White 145): configural χ² = 115.85 on 48 df, metric 124.04 on 54, scalar 164.10 on 60; Grant-White's verbal mean 0.58 higher if scalar invariance is assumed | Psyche (sem.fit_multigroup), item invariance; every value matches lavaan's |
| Mediation: 500 simulated people, X randomized, a = 0.5, no effect of M on Y, an unmeasured U (0.6) behind M and Y: indirect effect 0.17, bootstrap 95% interval 0.10 to 0.25 (1,000 resamples) | Psyche (sem.mediation), item mediation |
| The cross-lagged panel: 2,000 simulated people, 4 waves, stable traits correlated 0.6, within-person autoregression 0.3, no cross effects: the pooled cross-lagged regression gives 0.117 (SE 0.010); on the within-person deviations, -0.015 (SE 0.012) | the item's own regressions in compute.py, item panel |
| Factors and networks: one factor with loadings 0.8, 0.7, 0.6 and 0.5; the network of partial correlations (0.10 to 0.40) reproduces the correlations to 3e-16 | Psyche (sem.factor_as_network), item network |
| Every published number on screen | the studies listed under Sources, quoted as reported |
The diagrams in chapters 6, 10 and 11 (two layers, a growth model, a cross-lagged panel, two pictures of a disorder) are schematic, and the abstract in chapter 12 is invented for practice and labelled so on screen.
Notes
| Finding | Original | Status |
|---|---|---|
| Self-control draws on blood glucose: depletion lowers it, and a sugary drink restores self-control. | Gailliot and colleagues 2007 | failed |
| A latent-factor model and a network model of direct interactions can imply exactly the same distribution of observed responses. | Kruis and Maris 2016 | replicated |
| Fixed cut-offs for fit indices, such as CFI of at least 0.95 and RMSEA of at most 0.06, separate good models from bad ones in general. | Hu and Bentler 1999 | failed |
Shown without a row, with the reason recorded in explainer/psychology/ledger.py: Wright and Jöreskog; Holzinger and
Swineford; Baron and Kenny; Bullock, Green and Ha; MacCallum and colleagues; Meredith; Hamaker, Kuiper and Grasman;
Borsboom and Cramer; Spirtes, Glymour and Scheines; Muthén and Asparouhov, and McNeish and Wolf.
Notes
The web-search budget for this session was spent on earlier parts, so the facts in this part come from the standard literature and were not re-checked online today; each is listed here to be checked against its source: Wright's 1921 paper and its guinea-pig examples; McDonald's omega (McDonald, Test Theory, 1999); Jöreskog's 1969 paper; Holzinger and Swineford's 1939 monograph and the two schools; Hu and Bentler's cut-offs (CFI 0.95, RMSEA 0.06, SRMR 0.08) and their simulation conditions; McNeish and Wolf's dynamic cut-offs (2023); Meredith (1993); Baron and Kenny's citation count ("tens of thousands"); Bullock, Green and Ha's title and argument; Gailliot et al. (2007), Lange and Eggert (2014) and Vadillo, Gold and Osman (2016); MacCallum et al.'s survey (53 published applications, and how few acknowledged equivalent models); Hamaker, Kuiper and Grasman (2015); Borsboom and Cramer (2013); Kruis and Maris (2016) and Marsman et al. (2018); Spirtes, Glymour and Scheines's PC algorithm; Muthén and Asparouhov (2012); Rohrer (2018); and every page range in Sources.
Companion material in this repository
The syllabus's plan for this partfrom SYLLABUS.md, the plan of record
- Hook: one correlation matrix, three diagrams that fit it equally (returned to at the end).
- Path analysis: Wright's tracing rules derived; a correlation as a sum over paths.
- From exploratory to confirmatory factor analysis: the model Σ = ΛΦΛᵀ + Θ; identification (scaling, the three-indicator rule, counting parameters).
- Estimation: the maximum-likelihood discrepancy function, derived and minimized with the series' autodiff; Holzinger and Swineford's 1939 scores fitted.
- Fit: the χ² test and why it "always rejects"; RMSEA, CFI, SRMR; where the conventional cut-offs came from and why fixed cut-offs mislead (dynamic cut-offs).
- The full model: measurement plus structure; latent regressions corrected for unreliability (Part 3's attenuation, done properly).
- Measurement invariance: configural, metric, scalar. What must hold before two groups' means can be compared (owed since Parts 32 and 38).
- Mediation: Baron and Kenny (1986), the product of coefficients, bootstrapped intervals; and why a mediation analysis of an experiment is still a correlational claim about the mediator (sequential ignorability; link to Statistics, Built Part 36).
- Equivalent models: the diagrams of chapter 1; rules for generating them; why fit cannot choose.
- Longitudinal models: latent growth curves; the cross-lagged panel model and its repair (to Part 47).
- Factors against networks: a one-factor model and a fully connected network can imply the same covariances. What would distinguish them (interventions, time).
- Reporting standards, and a checklist for reading an SEM paper.
Psyche: psyche.sem: path models, CFA and SEM by ML on the series' autodiff, checked against a reference
implementation on the Holzinger–Swineford data; fit indices; invariance tests; equivalent-model generation;
everything run on Pool data with a known generating model.
On you: three data-generating stories and one matrix: draw a model that fits as well as the "true" one.
Ledger: famous mediation claims whose mediators failed when manipulated; statistical equivalence of factor and
network models (replicated as mathematics).
In practice: survey analytics, test validation, people analytics, marketing mix and attitude models; the
question to ask: what alternative diagram fits equally?
Frontier: causal discovery from psychological data and its assumptions; Bayesian SEM and small-sample
behaviour; dynamic fit.
Reading: Wright 1921; Jöreskog 1969; Bollen 1989; Kline, Principles and Practice of Structural Equation
Modeling; Hu & Bentler 1999, with McNeish & Wolf 2023; MacCallum et al. 1993; Meredith 1993; Bullock, Green & Ha
2010; Rohrer 2018; Statistics, Built Parts 31 and 36.
Build the film
python -m videos.psychology.psych44.compute # the part's numbers, into .cache/psych44
python tools/build.py psych44 # render and assemble the film
EXPLAINER_TTS=silent python tools/qa_scene.py psych44 Hook # one chapter, silent, with a contact sheet
Scenes: videos/psychology/psych44. Setup: see the course page. Source of these notes: the README and the scenes' narration.
Build it
python -m videos.psychology.psych44.compute # every number (about a minute; fetches the data once)
python tools/qa_scene.py psych44 Fit # one chapter, silent, at 480p, with a contact sheet
EXPLAINER_TTS=silent python tools/build.py psych44 -q l # the whole part, silent preview
python tools/build.py psych44 # 1080p30 with narration
python tools/qa_scene.py psych44 Mediation --lang zh # the Chinese edition of one chapter
python tools/make.py psych44 # both editions, with the checks a long build needs
python -m videos.psychology.labs 44 # the lab: paths, a CFA by hand, fit, invariance, mediation
python tools/check_ledger.py psych44 # every study shown has its Ledger row, or a reason
python -m pytest tests/psychology # Psyche's sem module, the Ledger, the Archive
The Chinese edition is zh_lines.py (the narration, line by line) and the series table
videos/psychology/psychology_text_zh.json (the text on screen); the terms are in
PSYCHOLOGY_ZH_GUIDE.md.