-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy path11-irt.Rmd
1477 lines (1192 loc) · 55.7 KB
/
11-irt.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Item Response Theory
Item response theory (IRT) builds models for item (stimuli that the measures collected) based on two broad classes of models
1. Models for dichotomous (binary, 0/1) items and
2. Models for polytomous (multi-category) items.
## IRT Models for Dichotomous Data
First, for conventional dichotomous observed variables, an IRT model can be generally specified as follows.
Let $x_{ij}$ be the observed value from respondent $i$ on observable (item) $j$.
When $x$ is binary, the observed value can be $0$ or $1$.
Some common IRT models for binary observed variables can be expressed as a version of
\[p(x_{ij} = 1 \mid \theta_i, d_j, a_j, c_j) = c_j + (1-c_j)F(a_j \theta_i + d_j),\]
where,
* $\theta_i$ is the magnitude of the latent variable that individual $i$ possesses. In educational measurement, $\theta_i$ commonly represents proficiency so that a higher $\theta_i$ means that individual has more of the trait,
* $d_j$ is the item location or difficulty parameter. $d_j$ is commonly transformed to be $d_j = -a_jb_j$ so that the location parameter is easier to interpret in relation to the latent trait $\theta_i$,
* $a_j$ is the item slope or discrimination parameter,
* $c_j$ is the item lower asymptote or guessing parameter,
* $F(.)$ is the link function to be specified that determines the form of the transformation between latent trait and the item response probability. The link is common chosen to be either the logistic link or the normal-ogive link.
Common IRT models are the
* 1-PL, or one-parameter logistic model, which only uses one measurement parameter $d_j$ per item,
* 2-PL, or two-parameter logistic model, which uses two measurement model parameters $a_j$ and $d_j$ per item,
* 3-PL, or three-parameter logistic model, which uses all three parameters as shown above.
* other models are also possible for binary item response formats but are omitted here.
The above describes the functional form used to model why individual may have a greater or lesser likelihood of endorsing an item (have a $1$ as a measure).
We use the above model as the basis for defining the conditional probability of any response given the values of the parameters.
The conditional probability is then commonly used as part of a *marginal maximum likelihood (MML)* approach to finding parameters values for the measurement model which maximize the likelihood.
However, given that the values of the latent variable $\theta_i$ are also unknown, the distribution of $\theta_i$ is marginalized out of the likelihood function.
However, in the Bayesian formulation, we can side-step some of these issues by the use of prior distributions.
Starting with the general form of the likelihood function
\[p(\mathbf{x}\mid \boldsymbol{\theta}, \boldsymbol{\omega}) = \prod_{i=1}^np(\mathbf{x}_i\mid \theta_i, \boldsymbol{\omega}) = \prod_{i=1}^n\prod_{j=1}^Jp(x_{ij}\mid \theta_i, \boldsymbol{\omega}_j),\]
where
\[x_{ij}\mid \theta_i, \boldsymbol{\omega}_j \sim \mathrm{Bernoulli}[p(x_{ij}\mid \theta_i, \boldsymbol{\omega}_j)].\]
Developing a joint prior distribution for $p(\boldsymbol{\theta}, \boldsymbol{\omega})$ is not straightforward given the high dimensional aspect of the components.
But, a common assumption is that the distribution for the latent variables ($\boldsymbol{\theta}$) is independent of the distribution for the measurement model parameters ($\boldsymbol{\omega}$).
That is, we can separate the problem into independent priors
\[p(\boldsymbol{\theta}, \boldsymbol{\omega}) = p(\boldsymbol{\theta})p(\boldsymbol{\omega}).\]
For the latent variables, the prior distributuion is generally build by assuming that all individuals are also independent.
The independence of observations leads to a joint prior that is a product of priors with a common distribution,
\[p(\boldsymbol{\theta}) = \prod_{i=1}^np(\theta_i\mid \boldsymbol{\theta}_p),\]
where $\boldsymbol{\theta}_p$ are the hyperparameters governing the common prior for the latent variable distribution.
A common choice is that $\theta_i \sim \mathrm{Normal}(\mu_{\theta} = 0, \sigma^2_{\theta}=1)$ because the distribution is arbitrary.
For the measurement model parameters, a bit more complex specification is generally needed.
One *simple* approach would be to invoke an exchangeability assumption among items and among item parameters.
This would essentially make all priors independent and simplify the specification to product of univariate priors over all measurement model parameters
\[p(\boldsymbol{\omega}) = \prod_{j=1}^Jp(\boldsymbol{\omega}_j)=\prod_{j=1}^Jp(d_j)p(a_j)p(c_j).\]
For for location parameter ($d_j$), a common prior distribution is an unbounded normal distribution.
Because, the location can take on any value within the range of the latent variable which is also technically unbounded so we let
\[d_j \sim \mathrm{Normal}(\mu_{d},\sigma^2_d).\]
The choice of hyperparameters can be guided by prior research or set to a common relative diffuse value for all items such as $\mu_{d}=0,\sigma^2_d=10$.
The discrimination parameter governs the strength of the relationship between the latent variable and the probability of endorsing the item.
This is similar in flavor to a factor loading in CFA.
An issue with specifying a prior for the discrimination parameter is the indeterminacy with respect the the orientation of the latent variable.
In CFA, we resolved the orientation indeterminacy issue by fixing one factor loading to 1.
In IRT, we can do so by constraining the possible values of the discrimination parameters to be strictly positive.
This forces each item to have the meaning of higher values on the latent variable directly (or at least proportionally) increase the probability of endorsing the item.
We achieve this by using a prior such as
\[a_j \sim \mathrm{Normal}^{+}(\mu_a,\sigma^2_a).\]
The term $\mathrm{Normal}^{+}(.)$ means that the normal distribution is truncated at 0 so that only positive values are possible.
Lastly, the guessing parameter $c_j$ takes on values between $[0,1]$.
A common choice for parameters bounded between 0 and 1 is a Beta prior, that is
\[c_j \sim \mathrm{Beta}(\alpha_c, \beta_c).\]
The hyperparameters $\alpha_c$ and $\beta_c$ determine the shape of the beta prior and affect the likelihood and magnitude of guessing parameters.
## 3-PL LSAT Example
In the Law School Admission Test (LSAT) example (p. 263-271), the data are from 1000 examinees responding to five items which is just a subset of the LSAT.
We hypothesize that only one underlying latent variable is measured by these items.
But that guessing is also plausible.
The full 3-PL model we will use can be described in an equation as
\[p(\boldsymbol{\theta}, \boldsymbol{d}, \boldsymbol{a}, \boldsymbol{c} \mid \mathbf{x}) \propto \prod_{i=1}^n\prod_{j=1}^Jp(\theta_i\mid\theta_i, d_j, a_j, c_j)p(\theta_i)p(d_j)p(a_j)p(c_j),\]
where
\begin{align*}
x_{ij}\mid\theta_i\mid\theta_i, d_j, a_j, c_j &\sim \mathrm{Bernoulli}[p(\theta_i\mid\theta_i, d_j, a_j, c_j)],\ \mathrm{for}\ i=1, \cdots, 100,\ j = 1, \cdots, 5;\\
p(\theta_i\mid\theta_i, d_j, a_j, c_j) &= c_j + (1-c_j)\Phi(a_j\theta_j + d_j),\ \mathrm{for}\ i=1, \cdots, 100,\ j = 1, \cdots, 5;\\
\theta_i &\sim \mathrm{Normal}(0,1),\ \mathrm{for}\ i = 1, \cdots, 1000;\\
d_j &\sim \mathrm{Normal}(0, 2),\ \mathrm{for}\ j=1, \cdots, 5;\\
a_j &\sim \mathrm{Normal}^{+}(1, 2),\ \mathrm{for}\ j=1, \cdots, 5;\\
c_j &\sim \mathrm{Beta}(5, 17),\ \mathrm{for}\ j=1, \cdots, 5.
\end{align*}
The above model can illustrated in a DAG as shown below.
```{r chp11-dag-1, echo=FALSE,fig.align='center',fig.cap='DAG for 3-PL IRT model for LSAT Example', out.width="75%"}
knitr::include_graphics(paste0(w.d,'/dag/chp11-irt1.png'),
auto_pdf = TRUE)
```
The path diagram for an IRT is essentially identical to the path diagram for a CFA model.
This fact highlights an important feature of IRT/CFA in that the major conceptual difference between these approaches to is how we define the link between the latent variable the observed items.
```{r chp11-pathdiag-1, echo=FALSE,fig.align='center',fig.cap='Path diagram for 3-PL IRT model', out.width="90%"}
knitr::include_graphics(paste0(w.d,'/path-diagram/chp11-irt1.png'),
auto_pdf = TRUE)
```
For completeness, I have included the model specification diagram that more concretely connects the DAG and path diagram to the assumed distributions and priors.
```{r chp11-spec-1, echo=FALSE,fig.align='center',fig.cap='Model specification diagram for the 3-PL IRT model', out.width="90%"}
knitr::include_graphics(paste0(w.d,'/model-spec/chp11-irt1.png'),
auto_pdf = TRUE)
```
## LSAT Example - JAGS
```{r chp11-lsat-jags, warnings=T, message=T, error=T, cache=TRUE}
jags.model.lsat <- function(){
#########################################
# Specify the item response measurement model for the observables
#########################################
for (i in 1:n){
for(j in 1:J){
P[i,j] <- c[j]+(1-c[j])*phi(a[j]*theta[i]+d[j]) # 3P-NO expression
x[i,j] ~ dbern(P[i,j]) # distribution for each observable
}
}
##########################################
# Specify the (prior) distribution for the latent variables
##########################################
for (i in 1:n){
theta[i] ~ dnorm(0, 1) # distribution for the latent variables
}
##########################################
# Specify the prior distribution for the measurement model parameters
##########################################
for(j in 1:J){
d[j] ~ dnorm(0, .5) # Locations for observables
a[j] ~ dnorm(1, .5); I(0,) # Discriminations for observables
c[j] ~ dbeta(5,17) # Lower asymptotes for observables
}
} # closes the model
# initial values
start_values <- list(
list("d"=c(1.00, 1.00, 1.00, 1.00, 1.00),
"a"=c(1.00, 1.00, 1.00, 1.00, 1.00),
"c"=c(0.20, 0.20, 0.20, 0.20, 0.20)),
list("d"=c(-3.00, -3.00, -3.00, -3.00, -3.00),
"a"=c(3.00, 3.00, 3.00, 3.00, 3.00),
"c"=c(0.50, 0.50, 0.50, 0.50, 0.50)),
list("d"=c(3.00, 3.00, 3.00, 3.00, 3.00),
"a"=c(0.1, 0.1, 0.1, 0.1, 0.1),
"c"=c(0.05, 0.05, 0.05, 0.05, 0.05))
)
# vector of all parameters to save
param_save <- c("a", "c", "d", "theta")
# dataset
dat <- read.table("data/LSAT.dat", header=T)
mydata <- list(
n = nrow(dat), J = ncol(dat),
x = as.matrix(dat)
)
# fit model
fit <- jags(
model.file=jags.model.lsat,
data=mydata,
inits=start_values,
parameters.to.save = param_save,
n.iter=2000,
n.burnin = 1000,
n.chains = 3,
progress.bar = "none")
#print(fit)
round(fit$BUGSoutput$summary[ !rownames(fit$BUGSoutput$summary) %like% "theta", ], 3)
# extract posteriors for all chains
jags.mcmc <- as.mcmc(fit)
# the below two plots are too big to be useful given the 1000 observations.
#R2jags::traceplot(jags.mcmc)
# gelman-rubin-brook
#gelman.plot(jags.mcmc)
# convert to single data.frame for density plot
a <- colnames(as.data.frame(jags.mcmc[[1]]))
plot.data <- data.frame(as.matrix(jags.mcmc, chains=T, iters = T))
colnames(plot.data) <- c("chain", "iter", a)
bayesplot::mcmc_acf(plot.data,pars = c(paste0("d[", 1:5, "]")))
bayesplot::mcmc_trace(plot.data,pars = c(paste0("d[", 1:5, "]")))
ggmcmc::ggs_grb(ggs(jags.mcmc), family="d")
mcmc_areas(plot.data, pars = c(paste0("d[",1:5,"]")), prob = 0.8)
bayesplot::mcmc_acf(plot.data,pars = c(paste0("a[", 1:5, "]")))
bayesplot::mcmc_trace(plot.data,pars = c(paste0("a[", 1:5, "]")))
ggmcmc::ggs_grb(ggs(jags.mcmc), family="a")
mcmc_areas( plot.data,pars = c(paste0("a[", 1:5, "]")), prob = 0.8)
bayesplot::mcmc_acf(plot.data,pars = c(paste0("c[", 1:5, "]")))
bayesplot::mcmc_trace(plot.data,pars = c(paste0("c[", 1:5, "]")))
ggmcmc::ggs_grb(ggs(jags.mcmc), family="c")
mcmc_areas(plot.data, pars = c(paste0("c[", 1:5, "]")), prob = 0.8)
```
### Posterior Predicted Distributions
Here, we want to compare the observed and expected posterior predicted distributions.
Statistical functions of interest are the (1) standardized model-based covariance (SMBC) and (2) the standardized generalized discrepancy measure (SGDDM).
For (1), the SMBC is
\[SMBC_{jj^\prime}=\frac{\frac{1}{n}\sum_{i=1}^n(x_{ij} - E(x_{ij} \mid \theta_i,\boldsymbol{\omega}_j))(x_{ij^\prime} - E(x_{ij^\prime} \mid \theta_i,\boldsymbol{\omega}_j^\prime))}{\sqrt{\frac{1}{n}\sum_{i=1}^n(x_{ij} - E(x_{ij} \mid \theta_i,\boldsymbol{\omega}_j))^2}\sqrt{\frac{1}{n}\sum_{i=1}^n(x_{ij^\prime} - E(x_{ij^\prime} \mid \theta_i,\boldsymbol{\omega}_j^\prime))}}\]
In R, the functions below can be used to compute these qualtities.
```{r chp11-ppd-functions, warnings=T, message=T, error=T, cache=TRUE}
calculate.SGDDM <- function(data.matrix, expected.value.matrix){
J.local = ncol(data.matrix)
SMBC.matrix <- calculate.SMBC.matrix(data.matrix, expected.value.matrix)
SGDDM = sum(abs((lower.tri(SMBC.matrix, diag=FALSE))*SMBC.matrix))/((J.local*(J.local-1))/2)
SGDDM
} # closes calculate.SGDDM
calculate.SMBC.matrix <- function(data.matrix, expected.value.matrix){
N.local <- nrow(data.matrix)
MBC.matrix <- (t(data.matrix-expected.value.matrix) %*% (data.matrix-expected.value.matrix))/N.local
MBStddevs.matrix <- diag(sqrt(diag(MBC.matrix)))
#SMBC.matrix <- solve(MBStddevs.matrix) %*% MBC.matrix %*% solve(MBStddevs.matrix)
J.local <- ncol(data.matrix)
SMBC.matrix <- matrix(NA, nrow=J.local, ncol=J.local)
for(j in 1:J.local){
for(jj in 1:J.local){
SMBC.matrix[j,jj] <- MBC.matrix[j,jj]/(MBStddevs.matrix[j,j]*MBStddevs.matrix[jj,jj])
}
}
SMBC.matrix
} # closes calculate.MBC.matrix
```
Next, we will use the functions above among other basic data wrangling to construct a full posterior predictive distribution analysis to probe our resulting posterior.
```{r chp11-lsat-jags-ppd, warnings=T, message=T, error=T, cache=TRUE}
# Data wrangle the results/posterior draws for use
datv1 <- plot.data %>%
pivot_longer(
cols = `a[1]`:`a[5]`,
values_to = "a",
names_to = "item"
) %>%
mutate(item = substr(item, 3,3)) %>%
select(chain, iter, item, a)
datv2 <- plot.data %>%
pivot_longer(
cols = `c[1]`:`c[5]`,
values_to = "c",
names_to = "item"
) %>%
mutate(item = substr(item, 3,3)) %>%
select(chain, iter, item, c)
datv3 <- plot.data %>%
pivot_longer(
cols = `d[1]`:`d[5]`,
values_to = "d",
names_to = "item"
) %>%
mutate(item = substr(item, 3,3)) %>%
select(chain, iter, item, d)
datv4 <- plot.data %>%
pivot_longer(
cols = `theta[1]`:`theta[999]`,
values_to = "theta",
names_to = "person"
) %>%
select(chain, iter, person, theta)
dat_long <- full_join(datv1, datv2)
dat_long <- full_join(dat_long, datv3)
dat_long <- full_join(dat_long, datv4)
dat1 <- dat
dat1$person <- paste0("theta[",1:nrow(dat), "]")
datvl <- dat1 %>%
pivot_longer(
cols=contains("item"),
names_to = "item",
values_to = "x"
) %>%
mutate(
item = substr(item, 6, 100)
)
dat_long <- left_join(dat_long, datvl)
# compute expected prob
ilogit <- function(x){exp(x)/(1+exp(x))}
dat_long <- dat_long %>%
as_tibble()%>%
mutate(
x.exp = c + (1-c)*ilogit(a*(theta - d)),
x.dif = x - x.exp
)
dat_long$x.ppd <- apply(
dat_long, 1,
FUN=function(x){
rbern(1, as.numeric(x[10]))
}
)
itermin <- min(dat_long$iter) # used for subseting
# figure 11.4
d <- dat_long %>%
group_by(chain, iter, person) %>%
summarise(raw.score = sum(x),
raw.score.ppd = sum(x.ppd))
di <- d %>%
filter(chain==1, iter==1001) %>%
group_by(raw.score) %>%
summarise(count = n())
dii <- d %>%
group_by(chain, iter, raw.score.ppd)%>%
summarise(raw.score = n())
# overall fit of observed scores
ggplot()+
geom_boxplot(data=dii, aes(y=raw.score, x= raw.score.ppd, group=raw.score.ppd))+
geom_point(data=di, aes(x=raw.score, y=count), color="red", size=2)+
labs(x="Raw Score", y="Number of Examinees")+
scale_x_continuous(breaks=0:5)+
theme_classic()
# by item
d <- dat_long %>%
group_by(chain, iter, person) %>%
mutate(raw.score = sum(x),
raw.score.ppd = sum(x.ppd))
di <- d %>%
filter(chain==1, iter==1001) %>%
group_by(raw.score, item) %>%
summarise(p.correct = mean(x))
dii <- d %>%
group_by(chain, iter, raw.score.ppd, item)%>%
summarise(p.correct = mean(x.ppd))
ggplot()+
geom_boxplot(data=dii,
aes(y= p.correct,
x= raw.score.ppd,
group=raw.score.ppd))+
geom_point(data=di,
aes(x=raw.score, y=p.correct),
color="red", size=2)+
facet_wrap(.~item)+
labs(x="Raw Score", y="Number of Examinees")+
theme_classic()
# computing standardized model summary statistics
# objects for results
J <- 5
n.chain <- 3
n.iters <- length(unique(dat_long$iter))
n.iters <- length(unique(long_dat$iter))
n.iters.PPMC <- n.iters*n.chain
realized.SMBC.array <- array(NA, c(n.iters.PPMC, J, J))
postpred.SMBC.array <- array(NA, c(n.iters.PPMC, J, J))
realized.SGDDM.vector <- array(NA, c(n.iters.PPMC))
postpred.SGDDM.vector <- array(NA, c(n.iters.PPMC))
ii <- i <- c <- 1
# iteration condiitons
iter.cond <- unique(dat_long$iter)
Xobs <- as.matrix(dat[,-6])
for(i in 1:length(iter.cond)){
for(c in 1:3){
cc <- iter.cond[i]
Xexp <- dat_long[dat_long$chain==c & dat_long$iter==cc , ] %>%
pivot_wider(
id_cols = person,
names_from = "item",
values_from = "x.exp",
names_prefix = "item"
) %>%
ungroup()%>%
select(item1:item5)%>%
as.matrix()
Xppd <- dat_long[dat_long$chain==c & dat_long$iter==cc , ] %>%
pivot_wider(
id_cols = person,
names_from = "item",
values_from = "x.ppd",
names_prefix = "item"
) %>%
ungroup()%>%
select(item1:item5)%>%
as.matrix()
# compute realized values
realized.SMBC.array[ii, ,] <- calculate.SMBC.matrix(Xobs, Xexp)
realized.SGDDM.vector[ii] <- calculate.SGDDM(Xobs, Xexp)
# compute PPD values
postpred.SMBC.array[ii, ,] <- calculate.SMBC.matrix(Xppd, Xexp)
postpred.SGDDM.vector[ii] <- calculate.SGDDM(Xppd, Xexp)
ii <- ii + 1
}
}
plot.dat.ppd <- data.frame(
real = realized.SGDDM.vector,
ppd = postpred.SGDDM.vector
)
ggplot(plot.dat.ppd, aes(x=real, y=ppd))+
geom_point()+
geom_abline(intercept = 0, slope=1)+
lims(x=c(0,0.5), y=c(0, 0.5))
# transform smbc into plotable format
ddim <- dim(postpred.SMBC.array)
plot.dat.ppd <- as.data.frame(matrix(0, nrow=ddim[1]*ddim[2]*ddim[3], ncol=4))
colnames(plot.dat.ppd) <- c("itemj", "itemjj", "real", "ppd")
ii <- i <- j <- jj <- 1
for(i in 1:ddim[1]){
for(j in 1:ddim[2]){
for(jj in 1:ddim[3]){
plot.dat.ppd[ii, 1] <- j
plot.dat.ppd[ii, 2] <- jj
plot.dat.ppd[ii, 3] <- realized.SMBC.array[i, j, jj]
plot.dat.ppd[ii, 4] <- postpred.SMBC.array[i, j, jj]
ii <- ii + 1
}
}
}
plot.dat.ppd <- plot.dat.ppd %>%
filter(itemj < itemjj) %>%
mutate(
cov = paste0("cov(", itemj, ", ", itemjj,")")
)
ggplot(plot.dat.ppd, aes(x=real, y=ppd))+
geom_point(alpha=0.25)+
geom_density2d(adjust=2)+
geom_abline(intercept = 0, slope=1)+
facet_wrap(.~cov)+
lims(x=c(-1,1), y=c(-1,1))+
theme_classic()
```
<!-- ## LSAT Example - OpenBUGS -->
<!-- ```{r chp11-lsat-openbugs, warnings=T, message=T, error=T, cache=TRUE} -->
<!-- # model code -->
<!-- model.file <- paste0(w.d,"/code/IRT-for-Dichotomous-Observables/WinBUGS/3PNO.bug") -->
<!-- cat(model.file) -->
<!-- # get data file -->
<!-- data.file <- paste0(w.d,"/code/IRT-for-Dichotomous-Observables/WinBUGS/data.txt") -->
<!-- # initial values -->
<!-- start_values <- list( -->
<!-- list("d"=c(1.00, 1.00, 1.00, 1.00, 1.00), -->
<!-- "a"=c(1.00, 1.00, 1.00, 1.00, 1.00), -->
<!-- "c"=c(0.20, 0.20, 0.20, 0.20, 0.20)), -->
<!-- list("d"=c(-3.00, -3.00, -3.00, -3.00, -3.00), -->
<!-- "a"=c(3.00, 3.00, 3.00, 3.00, 3.00), -->
<!-- "c"=c(0.50, 0.50, 0.50, 0.50, 0.50)), -->
<!-- list("d"=c(3.00, 3.00, 3.00, 3.00, 3.00), -->
<!-- "a"=c(0.1, 0.1, 0.1, 0.1, 0.1), -->
<!-- "c"=c(0.05, 0.05, 0.05, 0.05, 0.05)) -->
<!-- ) -->
<!-- # vector of all parameters to save -->
<!-- param_save <- c("a", "c", "d", "theta") -->
<!-- # fit model -->
<!-- fit <- openbugs( -->
<!-- data= data.file, -->
<!-- model.file = model.file, # R grabs the file and runs it in openBUGS -->
<!-- parameters.to.save = param_save, -->
<!-- #inits=start_values, -->
<!-- n.chains = 1, -->
<!-- n.iter = 2000, -->
<!-- n.burnin = 1000 -->
<!-- ) -->
<!-- print(fit) -->
<!-- ``` -->
## LSAT Example - Stan
```{r chp11-lsat-stan, warnings=T, message=T, error=T}
model_irt_lsat <- '
data {
int N;
int J;
int x[N,J];
}
parameters {
real<lower=0> a[J]; //discrimination
real d[J]; //location
real<lower=0, upper=1> c[J]; //guessing
real theta[N]; //person parameters
}
model {
matrix[N,J] pi;
// item response probabilities
for(n in 1:N){
for(j in 1:J){
pi[n,j] = c[j]+(1-c[j])*Phi(a[j]*theta[n]+d[j]);
x[n,j] ~ bernoulli(pi[n,j]);
}
}
//measurement model priors
for(j in 1:J){
a[j] ~ normal(1,2)T[0,];
d[j] ~ normal(0,2);
c[j] ~ beta(5, 17);
}
theta ~ normal(0,1);
}
'
# initial values
start_values <- list(
list("d"=c(1.00, 1.00, 1.00, 1.00, 1.00),
"a"=c(1.00, 1.00, 1.00, 1.00, 1.00),
"c"=c(0.20, 0.20, 0.20, 0.20, 0.20)),
list("d"=c(-3.00, -3.00, -3.00, -3.00, -3.00),
"a"=c(3.00, 3.00, 3.00, 3.00, 3.00),
"c"=c(0.50, 0.50, 0.50, 0.50, 0.50)),
list("d"=c(3.00, 3.00, 3.00, 3.00, 3.00),
"a"=c(0.1, 0.1, 0.1, 0.1, 0.1),
"c"=c(0.05, 0.05, 0.05, 0.05, 0.05))
)
# dataset
dat <- read.table("data/LSAT.dat", header=T)
mydata <- list(
N = nrow(dat),
J = ncol(dat),
x = as.matrix(dat)
)
# Next, need to fit the model
# I have explicitly outlined some common parameters
fit <- stan(
model_code = model_irt_lsat, # model code to be compiled
data = mydata, # my data
init = start_values, # starting values
chains = 3, # number of Markov chains
warmup = 2000, # number of warm up iterations per chain
iter = 4300, # total number of iterations per chain
cores = 1, # number of cores (could use one per chain)
refresh = 0 # no progress shown
)
```
```{r chp11-lsat-stan-plots, warnings=T, message=T, error=T}
# first get a basic breakdown of the posteriors
print(fit,pars =c("d", "a", "c", "theta[1000]"))
# plot the posterior in a
# 95% probability interval
# and 80% to contrast the dispersion
plot(fit,pars =c("d", "a", "c", "theta[1000]"))
# traceplots
rstan::traceplot(fit,pars =c("d", "a", "c", "theta[1000]"), inc_warmup = TRUE)
# Gelman-Rubin-Brooks Convergence Criterion
ggs_grb(ggs(fit, family = c("d"))) +
theme_bw() + theme(panel.grid = element_blank())
ggs_grb(ggs(fit, family = "a")) +
theme_bw() + theme(panel.grid = element_blank())
ggs_grb(ggs(fit, family = "c")) +
theme_bw() + theme(panel.grid = element_blank())
ggs_grb(ggs(fit, family = "theta[1000]")) +
theme_bw() + theme(panel.grid = element_blank())
# autocorrelation
ggs_autocorrelation(ggs(fit, family="d")) +
theme_bw() + theme(panel.grid = element_blank())
ggs_autocorrelation(ggs(fit, family="a")) +
theme_bw() + theme(panel.grid = element_blank())
ggs_autocorrelation(ggs(fit, family="c")) +
theme_bw() + theme(panel.grid = element_blank())
ggs_autocorrelation(ggs(fit, family="theta[1000]")) +
theme_bw() + theme(panel.grid = element_blank())
# plot the posterior density
plot.data <- as.matrix(fit)
mcmc_areas(plot.data, pars = paste0("d[",1:5,"]"),prob = 0.8)
mcmc_areas(plot.data, pars = paste0("a[",1:5,"]"),prob = 0.8)
mcmc_areas(plot.data, pars = paste0("c[",1:5,"]"),prob = 0.8)
mcmc_areas(plot.data, pars = paste0("theta[1000]"),prob = 0.8)
```
## IRT Models for Polytomous Data
A commonly used IRT model for polytomous items is the graded response model (GRM).
Below is one way of describing the model.
Let $x_{ij}$ be the observed response to item $j$ from examinee $i$ that may take on values 1, 2, ..., $K_j$, where $K_j$ is the number of possible responses/outcomes for item $j$.
In many applications, the number of response options is constant across items, though this need not be the case.
The GRM using conditional probability statements about the probability of a response being at or above a specific category and obtaining the probability for each category as a difference of two such conditional probabilities.
That is
\[P(x_{ij} = k \mid \theta_i, \boldsymbol{d}_j,a_j) = P(x_{ij} \geq k \mid \theta_i, d_{jk},a_j) - P(x_{ij} \geq k+1 \mid \theta_i, d_{j(k+1)},a_j),\]
where $\boldsymbol{d}_j$ is the collection of location/threshold parameters for item $j$.
The GRM takes on a structure similar to the 2-PL for any one category
\[P(x_{ij} \geq k \mid \theta_i, d_{jk},a_j)=F(a_j\theta_i + d_{jk}).\]
The conditional probability of observed responses may be modeled similarly as we have used for dichotomous responses but with a few important differences.
The conditional distribution of the data is
\[p(\boldsymbol{x}\mid \boldsymbol{\theta},\boldsymbol{\omega}) = \prod_{i=1}^np(\boldsymbol{x}_i\mid \theta_i, \boldsymbol{\omega}) = \prod_{i=1}^n\prod_{j=1}^Jp(x_{ij}\mid \theta_i, \boldsymbol{\omega}_j),\]
where each $x_{ij}$ is specified as a categorical random variable (or multinomial).
A categorical random variable is a generalization of the Bernoulli distribution which is defined be the collection of category response probabilities
\[x_{ij} \sim \mathrm{Categorical}(\boldsymbol{P}(x_{ij}\mid\theta_i, \boldsymbol{\omega}_j)).\]
The above helps form the likelihood of the observed data.
Next, the prior distribution is described because what the structure should be is not necessarily obvious.
First, the prior for the latent ability follows the same logic from the dichotomous model.
We employ an exchangeability assumption to specify independent priors for each respondent with a normally distribution prior.
Next, the measurement model parameters' priors are described.
We again can assume exchangeability and arrive at a common but independent prior across items, and assume that the priors for the location and discrimination parameters are independent.
These assumptions may not be tenable in theory, but they are practically useful.
The priors for discrimination stay the same as the dichotomous model.
The priors for the location parameters are a bit more involved.
For the location parameters, the first location parameter $d_{j1}$ specifies the probability of responding a 1 or greater which is a certainty if they gave a response.
Therefore, the probability would be 1.
We set $d_{j1} = -\inf$ and then set a normal prior for $d_{j2}\sim \mathrm{Normal}(\mu_{d2},\sigma^2_{d2})$.
The priors for the remaining location parameters ($d_{3}-d_{k}$) can be specified as truncated normal distributions.
That is, the location of the next threshold is constrained to be larger than the previous threshold and is formally
\[d_{jk} \sim \mathrm{Normal}^{>d_{j(k-1)}}(\mu_{d_k},\sigma^2_{d_k}),\ \mathrm{for}\ k=3, ...,K_j.\]
The posterior distribution for the GRM can be parameterized as follows.
The model as described below is very general and can accommodate varying number of thresholds per item but is constrained to only 1 latent factor.
\[p(\boldsymbol{\theta}, \boldsymbol{d}, \boldsymbol{a}\mid \mathbf{x}) \propto \prod_{i=1}^n\prod_{j=1}^Jp(\theta_i\mid\theta_i, \boldsymbol{d}_j, a_j)p(\theta_i)p(a_j)\prod_{k=2}^{K_j}p(d_{jk}),\]
where
\begin{align*}
x_{ij}\mid\theta_i\mid\theta_i, \boldsymbol{d}_j, a_j) &\sim \mathrm{Categorical}(\boldsymbol{P}(x_{ij}\mid\theta_i, \boldsymbol{\omega}_j)),\ \mathrm{for}\ i=1, \cdots, n,\ j = 1, \cdots, J;\\
\mathbf{P}(x_{ij}\mid\theta_i, \boldsymbol{d}_j, a_j) &= \left(P(x_{ij}=1\mid\theta_i, \boldsymbol{d}_j, a_j), \cdots, P(x_{ij}=K_j\mid\theta_i, \boldsymbol{d}_j, a_j)\right),\ \mathrm{for}\ i=1, \cdots, n,\ j = 1, \cdots, J;\\
P(x_{ij}=k\mid\theta_i, \boldsymbol{d}_j, a_j) &= P(x_{ij}\geq k\mid\theta_i,d_{jk}, a_j) - P(x_{ij}\geq k+1\mid\theta_i, d_{j(k+1)}, a_j),\ \mathrm{for}\ i=1, \cdots, n,\ j = 1, \cdots, J,\ k = 1,\cdots,K_j-1;\\
P(x_{ij}=K_j\mid\theta_i, \boldsymbol{d}_j, a_j) &= P(x_{ij}\geq K_j\mid\theta_i,d_{jK_j}, a_j),\ \mathrm{for}\ i=1, \cdots, n,\ j = 1, \cdots, J;\\
P(x_{ij}\geq k\mid\theta_i, d_{jk}, a_j) &= F(a_j\theta_j + d_{jk}),\ \mathrm{for}\ i=1, \cdots, n,\ j = 1, \cdots, J,\ k=2,\cdots,K_j;\\
P(x_{ij}\geq 1\mid\theta_i, d_{j1}, a_j) &= 1,\ \mathrm{for}\ i=1, \cdots, n,\ j = 1, \cdots, J;\\
\theta_i \mid \mu_{\theta}, \sigma^2_{\theta} &\sim \mathrm{Normal}(\mu_{\theta}, \sigma^2_{\theta}),\ \mathrm{for}\ i = 1, \cdots, n;\\
a_j \mid \mu_{a}, \sigma^2_{a} &\sim \mathrm{Normal}^{+}(\mu_{a}, \sigma^2_{a}),\ \mathrm{for}\ j=1, \cdots, J;\\
d_{j2}\mid\mu_{j2}, \sigma^2_{j2} &\sim \mathrm{Normal}(\mu_{j2}, \sigma^2_{j2} ),\ \mathrm{for}\ j=1, \cdots, J;\ \mathrm{and}\\
d_{jk}\mid\mu_{d_{jk}},\sigma^2_{d_{jk}} &\sim \mathrm{Normal}^{>d_{j(k-1)}}(\mu_{d_{jk}},\sigma^2_{d_{jk}}),\ \mathrm{for}\ j=1, \cdots, J,\ k=3, ...,K_j.
\end{align*}
## GRM Peer Interactions Example
The book uses an example of Peer Interactions from 500 responses to seven items. All the responses are coded from 1 to 5 on an agreement Likert-type scale.
A DAG for the GRM corresponding to these data is shown below.
```{r chp11-dag-2, echo=FALSE,fig.align='center',fig.cap='DAG for the for Peer Interactions GRM analysis', out.width="90%"}
knitr::include_graphics(paste0(w.d,'/dag/chp11-grm.png'),
auto_pdf = TRUE)
```
The path diagram version is substantially simpler and identical to the path diagram for the 3-PL and factor analysis diagrams.
Highlighting the similarity in *substantive* modeling of polytomous items to dichotomous items.
```{r chp11-pathdiag-2, echo=FALSE,fig.align='center',fig.cap='Path diagram for the Peer Interactions GRM analysis', out.width="90%"}
knitr::include_graphics(paste0(w.d,'/path-diagram/chp11-grm.png'),
auto_pdf = TRUE)
```
For completeness, I have included the model specification diagram that more concretely connects the DAG and path diagram to the assumed distributions and priors.
```{r chp11-spec-2, echo=FALSE,fig.align='center', out.width="90%",fig.cap='Model specification diagram for the Peer Interactions GRM analysis'}
knitr::include_graphics(paste0(w.d,'/model-spec/chp11-grm.png'),
auto_pdf = TRUE)
```
### Example Specific Model Specification
In fitting the GRM to the Peer Interactions data, we can be more precise about the prior and likelihood structure.
Below is a breakdown of the model specific to this example.
Everything is structurally identical to the previous page but specific values are chosen for the hyperparameters.
\[p(\boldsymbol{\theta}, \boldsymbol{d}, \boldsymbol{a}\mid \mathbf{x}) \propto \prod_{i=1}^n\prod_{j=1}^Jp(\theta_i\mid\theta_i, \boldsymbol{d}_j, a_j)p(\theta_i)p(a_j)\prod_{k=2}^{K_j}p(d_{jk}),\]
where
\begin{align*}
x_{ij}\mid\theta_i\mid\theta_i, \boldsymbol{d}_j, a_j) &\sim \mathrm{Categorical}(\boldsymbol{P}(x_{ij}\mid\theta_i, \boldsymbol{\omega}_j)),\ \mathrm{for}\ i=1, \cdots, 500,\ j = 1, \cdots, 7;\\
\mathbf{P}(x_{ij}\mid\theta_i, \boldsymbol{d}_j, a_j) &= \left(P(x_{ij}=1\mid\theta_i, \boldsymbol{d}_j, a_j), \cdots, P(x_{ij}=5\mid\theta_i, \boldsymbol{d}_j, a_j)\right),\ \mathrm{for}\ i=1, \cdots, 500,\ j = 1, \cdots, 7;\\
P(x_{ij}=k\mid\theta_i, \boldsymbol{d}_j, a_j) &= P(x_{ij}\geq k\mid\theta_i,d_{jk}, a_j) - P(x_{ij}\geq k+1\mid\theta_i, d_{j(k+1)}, a_j),\ \mathrm{for}\ i=1, \cdots, 500,\ j = 1, \cdots, 7,\ k = 1,\cdots,4;\\
P(x_{ij}=5\mid\theta_i, \boldsymbol{d}_j, a_j) &= P(x_{ij}\geq 5\mid\theta_i,d_{j5}, a_j),\ \mathrm{for}\ i=1, \cdots, 500,\ j = 1, \cdots, 7;\\
P(x_{ij}\geq k\mid\theta_i, d_{jk}, a_j) &= F(a_j\theta_j + d_{jk}) = \frac{\exp\left(a_j\theta_i +d_{jk}\right)}{1+\exp\left(a_j\theta_i +d_{jk}\right)},\ \mathrm{for}\ i=1, \cdots, 500,\ j = 1, \cdots, 7,\ k=2,\cdots,5;\\
P(x_{ij}\geq 1\mid\theta_i, d_{j1}, a_j) &= 1,\ \mathrm{for}\ i=1, \cdots, 500,\ j = 1, \cdots, 7;\\
\theta_i \mid \mu_{\theta}, \sigma^2_{\theta} &\sim \mathrm{Normal}(0, 1),\ \mathrm{for}\ i = 1, \cdots, 500;\\
a_j \mid \mu_{a}, \sigma^2_{a} &\sim \mathrm{Normal}^{+}(0,2),\ \mathrm{for}\ j=1, \cdots, 7;\\
d_{j2}\mid\mu_{d_{j2}}, \sigma^2_{d_{j2}} &\sim \mathrm{Normal}(2,2),\ \mathrm{for}\ j=1, \cdots, 7;\\
d_{j3}\mid\mu_{d_{j3}},\sigma^2_{d_{j3}} &\sim \mathrm{Normal}^{>d_{j2}}(1, 2),\ \mathrm{for}\ j=1, \cdots, 7;\\
d_{j4}\mid\mu_{d_{j4}},\sigma^2_{d_{j4}} &\sim \mathrm{Normal}^{>d_{j3}}(-1, 2),\ \mathrm{for}\ j=1, \cdots, 7; \mathrm{and}\\
d_{j5}\mid\mu_{d_{j5}},\sigma^2_{d_{j5}} &\sim \mathrm{Normal}^{>d_{j4}}(-2, 2),\ \mathrm{for}\ j=1, \cdots, 7.
\end{align*}
## PI Example - JAGS
In the below implementation, I had to change ` d[j,3] ~ dnorm(1, .5)I(d[j,4],d[j,2])` to ` d[j,3] ~ dnorm(1, .5);I(,d[j,2])` because (1) R is dumb and doesn't realize that ` I` is a JAGS function; and (2) JAGS does not allow for a ` directed cycle`.
The directed cycle in the DAG is when the range of values for ` d[j,3]` is fixed to be within ` I(d[j,4],d[j,2])` and is not permissible. We need to simply constrain the thresholds to be decreasing or smaller than the previous threshold.
I'm not sure of the underlying technical reason for this error, but I found that adding the semi-colon fixes the issue when defining the model as an R function.
```{r chp11-peer-int-jags, warnings=T, message=T, error=T, cache=TRUE}
jags.model.peer.int <- function(){
#######################################
# Specify the item response measurement model for the observables
#######################################
for (i in 1:n){
for(j in 1:J){
###################################
# Specify the probabilities of a value being greater than or equal to each category
###################################
for(k in 2:(K[j])){
# P(greater than or equal to category k > 1)
logit(P.gte[i,j,k]) <- a[j]*theta[i]+d[j,k]
}
# P(greater than or equal to category 1)
P.gte[i,j,1] <- 1
###################################
# Specify the probabilities of a value being equal to each category
###################################
for(k in 1:(K[j]-1)){
# P(greater equal to category k < K)
P[i,j,k] <- P.gte[i,j,k]-P.gte[i,j,k+1]
}
# P(greater equal to category K)
P[i,j,K[j]] <- P.gte[i,j,K[j]]
###################################
# Specify the distribution for each observable
###################################
x[i,j] ~ dcat(P[i,j,1:K[j]])
}
}
#######################################
# Specify the (prior) distribution for the latent variables
#######################################
for (i in 1:n){
theta[i] ~ dnorm(0, 1) # distribution for the latent variables
}
#######################################
# Specify the prior distribution for the measurement model parameters
#######################################
for(j in 1:J){
d[j,2] ~ dnorm(2, .5) # Locations for k = 2
d[j,3] ~ dnorm(1, .5);I(,d[j,2]) # Locations for k = 3
d[j,4] ~ dnorm(-1, .5);I(,d[j,3]) # Locations for k = 4
d[j,5] ~ dnorm(-2, .5);I(,d[j,4]) # Locations for k = 5
a[j] ~ dnorm(1, .5); I(0,) # Discriminations for observables
}
} # closes the model
# initial values
start_values <- list(
list(
d= matrix(c(NA, 3.00E+00, 1.00E+00, 0.00E+00, -1.00E+00,
NA, 3.00E+00, 1.00E+00, 0.00E+00, -1.00E+00,
NA, 3.00E+00, 1.00E+00, 0.00E+00, -1.00E+00,
NA, 3.00E+00, 1.00E+00, 0.00E+00, -1.00E+00,
NA, 3.00E+00, 1.00E+00, 0.00E+00, -1.00E+00,
NA, 3.00E+00, 1.00E+00, 0.00E+00, -1.00E+00,
NA, 3.00E+00, 1.00E+00, 0.00E+00, -1.00E+00),
ncol=5, nrow=7, byrow=T),
a=c(1.00E-01, 1.00E-01, 1.00E-01, 1.00E-01, 1.00E-01, 1.00E-01, 1.00E-01)),
list(
d= matrix(c(NA, 2.00E+00, 0.00E+00, -1.00E+00, -2.00E+00,
NA, 2.00E+00, 0.00E+00, -1.00E+00, -2.00E+00,
NA, 2.00E+00, 0.00E+00, -1.00E+00, -2.00E+00,
NA, 2.00E+00, 0.00E+00, -1.00E+00, -2.00E+00,
NA, 2.00E+00, 0.00E+00, -1.00E+00, -2.00E+00,
NA, 2.00E+00, 0.00E+00, -1.00E+00, -2.00E+00,
NA, 2.00E+00, 0.00E+00, -1.00E+00, -2.00E+00),
ncol=5, nrow=7, byrow=T),
a=c(3.00E+00, 3.00E+00, 3.00E+00, 3.00E+00, 3.00E+00, 3.00E+00, 3.00E+00)),
list(
d= matrix(c(NA, 1.00E+00, -1.00E+00, -2.00E+00, -3.00E+00,
NA, 1.00E+00, -1.00E+00, -2.00E+00, -3.00E+00,
NA, 1.00E+00, -1.00E+00, -2.00E+00, -3.00E+00,
NA, 1.00E+00, -1.00E+00, -2.00E+00, -3.00E+00,
NA, 1.00E+00, -1.00E+00, -2.00E+00, -3.00E+00,
NA, 1.00E+00, -1.00E+00, -2.00E+00, -3.00E+00,
NA, 1.00E+00, -1.00E+00, -2.00E+00, -3.00E+00),
ncol=5, nrow=7, byrow=T),
a=c(1.00E+00, 1.00E+00, 1.00E+00, 1.00E+00, 1.00E+00, 1.00E+00, 1.00E+00))
)
# vector of all parameters to save
param_save <- c("a", "d", "theta")
# dataset
dat <- read.table("data/PI.dat", header=T)
mydata <- list(
n = nrow(dat), J = ncol(dat),
K = rep(5, ncol(dat)),
x = as.matrix(dat)
)
# fit model
fit <- jags(
model.file=jags.model.peer.int,
data=mydata,
inits=start_values,
parameters.to.save = param_save,
n.iter=4000,
n.burnin = 2000,
n.chains = 3,
progress.bar = "none")
print(fit)
round(fit$BUGSoutput$summary[ !rownames(fit$BUGSoutput$summary) %like% "theta", ], 3)
# extract posteriors for all chains
jags.mcmc <- as.mcmc(fit)
# convert to single data.frame for density plot
a <- colnames(as.data.frame(jags.mcmc[[1]]))
plot.data <- data.frame(as.matrix(jags.mcmc, chains=T, iters = T))
colnames(plot.data) <- c("chain", "iter", a)
plot_title <- ggtitle("Posterior distributions","with medians and 80% intervals")
bayesplot::mcmc_areas(plot.data, regex_pars = "d", prob = 0.8) + plot_title + lims(x=c(-10, 10))
bayesplot::mcmc_areas(
plot.data,
pars = c(paste0("a[", 1:7, "]")),
prob = 0.8) +
plot_title
bayesplot::mcmc_acf(plot.data,pars = c(paste0("a[", 1:7, "]")))
bayesplot::mcmc_trace(plot.data,pars = c(paste0("a[", 1:7, "]")))
ggmcmc::ggs_grb(ggs(jags.mcmc), family="d")
ggmcmc::ggs_grb(ggs(jags.mcmc), family="a")
ggmcmc::ggs_autocorrelation(ggs(jags.mcmc), family="d")
```
<!-- ## PI Example - OpenBUGS -->
<!-- I ran into issues using the BUGs code provided in text using JAGS so I figured I would replicate the model using OpenBUGS directly to test whether the model can be run as is without any modifications. -->
<!-- ```{r chp11-peer-int-openbugs, warnings=T, message=T, error=T, cache=TRUE} -->
<!-- # model code -->
<!-- model.file <- paste0(w.d,"/code/IRT-for-Polytomous-Observables/IRT for Polytomous Observables/WinBUGS/L-GRM (Normal with Bounds, Truncated-Normal).bug") -->
<!-- cat(model.file) -->
<!-- # get data file -->
<!-- data.file <- paste0(w.d,"/code/IRT-for-Polytomous-Observables/IRT for Polytomous Observables/WinBUGS/data.txt") -->
<!-- # initial values -->
<!-- start_values <- list( -->
<!-- list( -->
<!-- d= matrix(c(NA, 3.00E+00, 1.00E+00, 0.00E+00, -1.00E+00, -->
<!-- NA, 3.00E+00, 1.00E+00, 0.00E+00, -1.00E+00, -->
<!-- NA, 3.00E+00, 1.00E+00, 0.00E+00, -1.00E+00, -->
<!-- NA, 3.00E+00, 1.00E+00, 0.00E+00, -1.00E+00, -->
<!-- NA, 3.00E+00, 1.00E+00, 0.00E+00, -1.00E+00, -->
<!-- NA, 3.00E+00, 1.00E+00, 0.00E+00, -1.00E+00, -->
<!-- NA, 3.00E+00, 1.00E+00, 0.00E+00, -1.00E+00), -->
<!-- ncol=5, nrow=7, byrow=T), -->
<!-- a=c(1.00E-01, 1.00E-01, 1.00E-01, 1.00E-01, 1.00E-01, 1.00E-01, 1.00E-01)), -->
<!-- list( -->
<!-- d= matrix(c(NA, 2.00E+00, 0.00E+00, -1.00E+00, -2.00E+00, -->
<!-- NA, 2.00E+00, 0.00E+00, -1.00E+00, -2.00E+00, -->
<!-- NA, 2.00E+00, 0.00E+00, -1.00E+00, -2.00E+00, -->
<!-- NA, 2.00E+00, 0.00E+00, -1.00E+00, -2.00E+00, -->
<!-- NA, 2.00E+00, 0.00E+00, -1.00E+00, -2.00E+00, -->
<!-- NA, 2.00E+00, 0.00E+00, -1.00E+00, -2.00E+00, -->
<!-- NA, 2.00E+00, 0.00E+00, -1.00E+00, -2.00E+00), -->
<!-- ncol=5, nrow=7, byrow=T), -->
<!-- a=c(3.00E+00, 3.00E+00, 3.00E+00, 3.00E+00, 3.00E+00, 3.00E+00, 3.00E+00)), -->
<!-- list( -->
<!-- d= matrix(c(NA, 1.00E+00, -1.00E+00, -2.00E+00, -3.00E+00, -->
<!-- NA, 1.00E+00, -1.00E+00, -2.00E+00, -3.00E+00, -->
<!-- NA, 1.00E+00, -1.00E+00, -2.00E+00, -3.00E+00, -->
<!-- NA, 1.00E+00, -1.00E+00, -2.00E+00, -3.00E+00, -->
<!-- NA, 1.00E+00, -1.00E+00, -2.00E+00, -3.00E+00, -->
<!-- NA, 1.00E+00, -1.00E+00, -2.00E+00, -3.00E+00, -->
<!-- NA, 1.00E+00, -1.00E+00, -2.00E+00, -3.00E+00), -->
<!-- ncol=5, nrow=7, byrow=T), -->
<!-- a=c(1.00E+00, 1.00E+00, 1.00E+00, 1.00E+00, 1.00E+00, 1.00E+00, 1.00E+00)) -->
<!-- ) -->
<!-- # vector of all parameters to save -->
<!-- param_save <- c("a", "d", "theta") -->
<!-- # fit model -->
<!-- fit <- openbugs( -->
<!-- data= data.file, -->
<!-- model.file = model.file, # R grabs the file and runs it in openBUGS -->
<!-- parameters.to.save = param_save, -->
<!-- inits=start_values, -->
<!-- n.chains = 3, -->
<!-- n.iter = 2000, -->
<!-- n.burnin = 1000, -->
<!-- n.thin = 1 -->
<!-- ) -->
<!-- print(fit) -->
<!-- ``` -->
## PI Example - Stan
```{r chp11-peer-int-stan, warnings=T, message=T, error=T, cache=TRUE}
model_irt_peer_int <- '
data {
int N;
int J;
int K;
int x[N,J];
}
parameters {
real<lower=0> a[J]; //discrimination
ordered[K-1] d[J]; //location/thresholds
real theta[N]; //person parameters