-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathptII_quan_Bayes_HMC.r
2031 lines (1630 loc) · 52.2 KB
/
ptII_quan_Bayes_HMC.r
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
### (C) 2005-2023 by Leo Guertler
### R-code supplement
### to the book
###
### "Subjektive Ansichten und objektive Betrachtungen"
###
### written by Gürtler & Huber (2023)
###
### All R-code is published under the GPL v3 license:
###
### https://www.gnu.org/licenses/gpl-3.0.en.html
###
### except for 'borrowed' code - see links and references.
### For this R-code the original license of the respective
### authors is valid.
###
### R-code published on
###
### https://osdn.net/projects/mixedmethod-rcode
### https://github.com/abcnorio/mixedmethod-rcode
# file:
# ptII_quan_Bayes_HMC_helpfuncs.r
# location:
# chap. 6 [6.13.2.3.1]
# Hamilton Monte Carlo im R
# load necessary libs
library(rhmc)
library(numDeriv)
library(bayesplot)
library(coda)
library(magrittr)
library(hmclearn)
library(mvtnorm)
library(rethinking)
library(car)
library(unikn)
library(mixtools)
library(RColorBrewer)
library(gear)
# load helper functions
source("ptII_quan_Bayes_HMC_helpfuncs.r")
source("ptII_quan_Bayes_HMC_rethinking-upd_helpfuncs.r")
# look at source code
# Hamiltonian Dynamics
rhmc:::hamiltonian_dynamics
# Hamiltonian Monte Carlo
rhmc:::hmc
# Numerical Gradient
rhmc:::num_grad
?hmc
# mu
mu <- 10
# sigma
sigma <- 5
# create some function with (negative) log posterior
hmcfun <- function(x) -dnorm(x, mu, sigma, log=TRUE)
# compare gradient functions
#library(numDeriv)
hmcfun(100)
?grad
numDeriv:::grad(hmcfun, 100)
rhmc:::num_grad(hmcfun, 100)
all.equal(numDeriv:::grad(hmcfun, 100), rhmc:::num_grad(hmcfun, 100))
# do actual HMC mcmc
# number of chains
nchains <- 10
# iterations per chain
itera <- 1000
# initival value (prior value!)
initv <- 9
# leapfrog parameter (number of steps)
L <- 8
# leapfrog parameter (size of each step)
eps <- 0.3
# leapfrog parameter (mass vector)
mass <- 0.1
hmc.res.arr <- lapply(1:nchains, function(x) rhmc:::hmc(hmcfun, initv+(0.5-runif(1)), itera, L, eps, mass))
# have a look at results
str(hmc.res.arr)
# plot one chain
chain <- drop(hmc.res.arr[[1]]$chain)
U <- drop(hmc.res.arr[[1]]$U)
plot(chain, type="l")
plot(U[1:30],type="l")
# take only posterior values
hmc.res.arr.red <- lapply(hmc.res.arr, function(x) x[1])
str(hmc.res.arr.red)
# define dimensions for array
dimis <- dim(as.matrix(hmc.res.arr.red[[1]][[1]]))
# create array
res.arr <- array(dim=c(dimis[2],nchains,dimis[1]),
dimnames=list(iter=1:dimis[2],
chain=paste("chain",1:nchains,sep=""),
var=c("theta"))
)
# fill i values
for(i in 1:nchains) res.arr[,i,] <- t(as.matrix(hmc.res.arr.red[[i]][[1]]))
#library(bayesplot)
# plot posteriors and chains
color_scheme_set("mix-blue-pink")
bayesplot:::mcmc_trace(res.arr, pars=c("theta"))
bayesplot:::mcmc_hist_by_chain(res.arr, pars=c("theta"))
color_scheme_set("green")
bayesplot:::mcmc_hist(res.arr, pars=c("theta"))
color_scheme_set("purple")
bayesplot:::mcmc_dens(res.arr, pars=c("theta"))
color_scheme_set("blue")
bayesplot:::mcmc_dens_overlay(res.arr, pars=c("theta"))
color_scheme_set("teal")
bayesplot:::mcmc_violin(res.arr, pars=c("theta"), probs=c(0.1, 0.5, 0.9))
# descriptive statistics
# per chain
str(unlist(hmc.res.arr.red[[1]]))
hm.res.red.desc <- do.call("rbind", lapply(hmc.res.arr.red, function(x) summary(unlist(x))))
hm.res.red.desc
hm.res.red.sd <- do.call("rbind", lapply(hmc.res.arr.red, function(x) sd(unlist(x))))
hm.res.red.desc <- data.frame(hm.res.red.desc,sd=hm.res.red.sd,var=hm.res.red.sd^2)
hm.res.red.desc
# over all chains
apply(hm.res.red.desc,2,mean)
# q<uantiles
hm.res.red.quan <- do.call("rbind", lapply(hmc.res.arr.red, function(x) quantile(unlist(x))))
apply(hm.res.red.quan,2,mean)
# all chains
summary(res.arr)
sd(res.arr)
var(res.arr)
# summarize through array
theta.chains <- (res.arr[,,1])
str(theta.chains)
# descriptive statistics
t(apply(theta.chains, 2, function(x) c(summary(x),sd=sd(x),var=var(x))))
burnin.rem <- FALSE
burnin <- 100
dim(theta.chains)
if(burnin.rem) theta.chains <- theta.chains[-c(1:burnin),]
c(mean=mean(theta.chains),
sd=esdes <- sd(theta.chains),
var=esdes^2,
SE=sqrt((esdes^2)/dim(theta.chains)[1])
)
quantile(theta.chains, probs=c(0,0.025,0.25,0.5,0.75,0.975,1))
# quantiles
# convert to mcmc object and mcmc list to use coda library
#library(coda)
hmc.res.arr.red.mcmc <- as.mcmc.list(lapply(hmc.res.arr.red, function(x) mcmc(t(x$chain))))
summary(hmc.res.arr.red.mcmc)
theta <- c(5.0, 0.5, 2.0, 1.5)
names(theta) <- c("mu1","sd1","mu2","sd2")
theta
n <- 100
sims <- bivariate_normal(theta, n)
xs <- as.matrix(sims)
head(xs)
dim(xs)
log_likelihood <- function(xs, theta)
{
sum(apply(xs, 1, function(x) dnorm(x[1], mean=theta[1], sd=theta[2], log=T) +
dnorm(x[2], mean=theta[3], sd=theta[4], log=T))
)
}
log_likelihood(xs, theta)
# library(magrittr)
# for: "%>%"
log_likelihood <- function(xs, theta) {
apply(xs, 1, function(x) dnorm(x[1], mean = theta[1], sd = theta[2], log = T) +
dnorm(x[2], mean = theta[3], sd = theta[4], log = T)) %>% sum()
}
log_likelihood(xs, theta)
#The prior distributions are chosen to be:
#p(μj)p(Σjj)=N(0,3),=Gamma(3,3),j=1,2.
log_prior <- function(theta)
{
dnorm(theta[1], log=T) +
dnorm(theta[3], log=T) +
dgamma(theta[2], shape=3, rate=3, log=T) +
dgamma(theta[4], shape=3, rate=3, log=T)
}
log_prior(theta)
log_posterior <- function(xs, theta)
{
log_likelihood(xs, theta) + log_prior(theta)
}
log_posterior(xs,theta)
#library(hmclearn)
# Linear regression example
set.seed(521)
X <- cbind(1, matrix(rnorm(300), ncol=3))
betavals <- c(0.5, -1, 2, -3)
y <- X%*%betavals + rnorm(100, sd=.2)
head(X)
head(y)
theta.init <- c(rep(0, 4), 1)
theta.init
f1_hmc <- hmclearn:::hmc(N = 500,
theta.init = theta.init,
epsilon = 0.01,
L = 10,
logPOSTERIOR = linear_posterior,
glogPOSTERIOR = g_linear_posterior,
varnames = c(paste0("beta", 0:3), "log_sigma_sq"),
param=list(y=y, X=X), parallel=FALSE, chains=1)
summary(f1_hmc, burnin=100)
str(f1_hmc)
linear_posterior(theta.init,y,X) #res = 1 value
g_linear_posterior(theta.init,y,X) #res = 5 values = 5 parameters (=length(theta.init))
#############################################################
# Kevin Shoemaker MH & MCMC
# working example HMC
#library(mvtnorm)
seed <- 9988776
set.seed(seed)
# iterations of HMC MCMC
nsamp <- 500
# correlation of the two normal dists
rho <- 0.6
# initial values for all parameters of interest
xinit <- 0
yinit <- 0
# matrix for storing the random samples
Qmat <- matrix(ncol=2, nrow=nsamp)
# initialize the markov chain
# Q stores temporarily as a list for each loop the relevant values
# first entry = initial values
# initial
current_q <- c(xinit, yinit)
# sigma matrix - stays constant
#sigmamat <- matrix(c(4,2,2,3), ncol=2)
sigmamat <- matrix(c(1,rho,rho,1),ncol=2)
# probability density of the distribution at the starting values
# actually not really needed???
# otherwise start with n>1
#prev <- dmvnorm(x=Q$q, mean=c(0,0), sigma=sigmamat, log=TRUE)
# HMC_2D_sample
# sampler
# define vectors, matrices, etc. for stored post values
# accept
a <- rep(NA, nsamp)
# diff H1-H0
dH <- rep(NA, nsamp)
# posterior values c(x,y)
post <- matrix(NA, nrow=nsamp, ncol=2)
# adapt to terminology from Neale & CO
# not needed as it is required for each trial...
#current_q <- Q$q
L <- 8
epsilon <- 0.03
step <- 0.03
# sd of rnorm to choose parameters
draw.param.sd <- 1#0.5 #1
# crawl through iterations
#for (i in 1:nsamp)
i <- 1
while(i <= nsamp)
{
print(i)
q <- current_q
### start of HMC2
#q = current_q
#p = rnorm(length(q), 0, 1)
# make a jump. Note the symmetrical proposal distribution
# draw both from rnorm
p <- rnorm(length(q),0,draw.param.sd)
current_p <- p
q
p
# assess whether the new jump is good!
# draw from target distribution (= U)
# gradient from target distribution(= U_gradient)
#newprob.grad <- numDeriv:::grad(f=dmvnorm, x=c(newx,newy), sigma=sigmamat, log=TRUE)
#Q <- HMC2(U, U_gradient, epsilon = step, L = L, current_q = Q$q)
# HMC2
#function (U, grad_U, epsilon, L, current_q, ...)
#{
#...
#}
#p = p - epsilon * grad_U(q, ...)/2
p = p - epsilon * numDeriv:::grad(f=mvtnorm:::dmvnorm, x=q, sigma=sigmamat, log=TRUE) / 2
#qtraj <- matrix(NA, nrow = L + 1, ncol = length(q))
#ptraj <- qtraj
#qtraj[1, ] <- current_q
#ptraj[1, ] <- p
# leapfrog integrator
for (ii in 1:L)
{
q = q + epsilon * p
if (ii != L) {
#p = p - epsilon * grad_U(q, ...)
p = p - epsilon * numDeriv:::grad(f=mvtnorm:::dmvnorm, x=q, sigma=sigmamat, log=TRUE)
#ptraj[i + 1, ] <- p
}
#qtraj[i + 1, ] <- q
}
#p = p - epsilon * grad_U(q, ...)/2
p = p - epsilon * numDeriv:::grad(f=mvtnorm:::dmvnorm, x=q, sigma=sigmamat, log=TRUE) / 2
#ptraj[L + 1, ] <- p
p = -p
#current_U = U(current_q, ...)
current_U = -mvtnorm:::dmvnorm(x=current_q, sigma=sigmamat, log=TRUE)
current_K = sum(current_p^2)/2
proposed_U = -mvtnorm:::dmvnorm(x=q, sigma=sigmamat, log=TRUE)
proposed_K = sum(p^2)/2
H0 <- current_U + current_K
H1 <- proposed_U + proposed_K
new_q <- NA
accept <- NA
if(runif(1) < exp(current_U - proposed_U + current_K - proposed_K))
{
new_q <- q
accept <- 1
} else
{
new_q <- current_q
accept <- 0
}
#return(list(q = new_q, traj = qtraj, ptraj = ptraj, accept = accept,
# dH = H1 - H0))
#return(list(q = new_q, accept = accept, dh = H1 - H0))
new_q
accept
dH.temp <- H1-H0
### end of HMC2
# actual test routing with the outcome of the HMC proposal routine
r <- min(abs(dH.temp), 1)
dH[i] <- dH.temp
a[i] <- accept
if (a[i] == 1)
{
current_q <- post[i, ] <- new_q
i <- i + 1
}
}
head(post)
head(a)
plot(post)
hist(post, prob=TRUE)
lines(density(post), col="darkred", lwd=2)
#############################################################
#library(rethinking)
seed <- 9988776
seed <- 996 #with stepsize 0.03 bad example!
set.seed(seed)
rho <- 0.8
sigmamat <- matrix(c(1,rho,rho,1),ncol=2)
sigmamat
#sigmamat <- matrix(c(4,2,2,3), ncol=2)
#sigmamat
grad_U <- function(q, ...) -numDeriv:::grad(f=mvtnorm:::dmvnorm, x=q, sigma=sigmamat, log=TRUE)
U <- function(q, ...) -mvtnorm:::dmvnorm(x=q, sigma=sigmamat, log=TRUE)
L <- 11 #10
#WRONG
step <- 0.03 #0.03
step <- 0.1
# pretty exact
#L <- 10 #10
#step <- 0.03 #0.03
Q <- list()
Q$q <- c(0,0)
U(Q$q)
grad_U(Q$q)
Q
nsamp <- 3e4 #1e4
nsamp <- 3e3
nsamp <- 3e3
nsamp <- 1e3+1
post.qadH <- matrix(NA, nrow=nsamp, ncol=2+1+1)
colnames(post.qadH) <- c("q1","q2","a","dH")
dim(post.qadH)
post.qadH[1,c("q1","q2")] <- unlist(Q)
head(post.qadH)
# just to see development
for (i in 2:nsamp)
{
print(i)
Q <- HMC2.plus(U, grad_U, epsilon=step, L=L, current_q=post.qadH[i-1,c("q1","q2")])
Q
post.qadH[i,"dH"] <- Q$dH
post.qadH[i,"a"] <- Q$accept
if(Q$accept == 1)
{
post.qadH[i,c("q1","q2")] <- unlist(Q$q) # accept = 1 -> update q1, q2
} else
{
post.qadH[i,] <- post.qadH[i-1,c("q1","q2")] # we don't change values of q1, q2 here
}
}
# remove first line (not required, initial values or nothing)
post.qadH <- post.qadH[-c(1),]
# last Q
Q
head(post.qadH)
tail(post.qadH)
dim(post.qadH)
apply(post.qadH,2,mean, na.rm=TRUE)
cov(post.qadH[,c("q1","q1")], use="complete.obs")
length(is.na(post.qadH[,"a"]))/dim(post.qadH)[1]
post <- post.qadH[,c(1:2)]
## example McElreath rethinking HMC_2D_sample
#res <- HMC_2D_sample( n=1000 , U=U_funnel , U_gradient=U_funnel_gradient ,
# step=0.2 , L=10 , ylab="v" , adj_lvls=1/12 )
#sum(!is.na(res)+0) / length(res)
dim(post)
head(post)
sum(!is.na(post)+0) / length(post)
method <- "dmvnorm"
#post <- post[-c(1:500),]
# plot bivariate posterior with ellipses
dim(post)
radius <- sqrt(qchisq(.5,2))
plot(post, main=paste("Bivariate normal distribution [method=",method,"]",sep=""),
pre.plot=grid(), type="p", bty="n",
xlab="v1", ylab="v2", col="olivedrab")
Xbar <- apply(post,2,mean, na.rm=TRUE)
Xbar
S <- cov(post, use="complete.obs")
S
apply(post,2,sd, na.rm=TRUE)
#library(car)
ellipse(center=Xbar, shape=S, radius=radius, col="blue")
ellipse(center=c(0,0), shape=sigmamat, radius=radius, col="darkred", lty=2)
# compare with simulated from multivariate normal distribution
rmv.sim <- mvtnorm:::rmvnorm(n=1000, mean=c(0,0), sigma=sigmamat)
str(rmv.sim)
Xbar.sim <- apply(rmv.sim, 2, mean)
Xbar.sim
SD.sim <- apply(rmv.sim, 2, sd)
SD.sim
cov.sim <- cov(rmv.sim)
cov.sim
points(rmv.sim, col="red")
ellipse(center=Xbar.sim, shape=cov.sim, radius=radius, col="black")
# single run
#HMC2(U, grad_U, epsilon=0.03, L=8, current_q=c(0,0), sigmamat)
# plot MCMC
# diagnostics MCMC
# investigate acceptance rate
# 3d plot bivariate normal distribution
# investigate Q
# investigate leapfrogs
# investigate dH
# simulate and draw
post <- HMC_2D_sample(n=5, U=U, U_gradient=grad_U, step=0.1, L=11, start=c(0,0))
post
HMC_2D_sample(n=15, U=U, U_gradient=grad_U, step=0.1, L=11, start=c(0,0))
HMC_2D_sample(n=25, U=U, U_gradient=grad_U, step=0.1, L=11, start=c(0,0))
HMC_2D_sample(n=99, U=U, U_gradient=grad_U, step=0.1, L=11, start=c(0,0))
HMC_2D_sample(n=100, U=U, U_gradient=grad_U, step=0.1, L=11, start=c(0,0))
HMC_2D_sample(n=150, U=U, U_gradient=grad_U, step=0.1, L=11, start=c(0,0))
HMC_2D_sample(n=1000, U=U, U_gradient=grad_U, step=0.1, L=11, start=c(0,0))
############################
# HMC
# with Neal's code (s.a.) and modifications/ comments
# good to lean the basic principle
# U is a function that returns the potential energy given q
# grad_U returns the respective partial derivatives
# epsilon stepsize
# L number of leapfrog steps
# current_q current position
# kinetic energy is assumed to be sum(p^2/2) (mass == 1)
HMC <- function (U, grad_U, epsilon, L, current_q, ...)
{
q <- current_q
# independent standard normal variates
p <- rnorm(length(q), 0, 1)
# Make a half step for momentum at the beginning
current_p <- p
# Alternate full steps for position and momentum
p <- p - epsilon * grad_U(q, ...) / 2
for (ii in 1:L) {
# Make a full step for the position
q <- q + epsilon * p
# Make a full step for the momentum, except at end of trajectory
if (ii != L) p <- p - epsilon * grad_U(q, ...)
}
# Make a half step for momentum at the end
p <- p - epsilon * grad_U(q, ...) / 2
# Negate momentum at end of trajectory to make the proposal symmetric
p <- -p
# Evaluate potential and kinetic energies at start and end of trajectory
current_U <- U(current_q, ...)
current_K <- sum(current_p^2) / 2
proposed_U <- U(q, ...)
proposed_K <- sum(p^2) / 2
# Accept or reject the state at end of trajectory, returning either
# the position at the end of the trajectory or the initial position
if (runif(1) < exp(current_U-proposed_U+current_K-proposed_K)) {
return (q) # accept
} else {
return (current_q) # reject
}
}
###
#library(mvtnorm)
rho <- 0.8
sigmamat <- matrix(c(1,rho,rho,1),ncol=2)
sigmamat
#sigmamat <- matrix(c(4,2,2,3), ncol=2)
#sigmamat
grad_U <- function(q, ...) -numDeriv:::grad(f=dmvnorm, x=q, sigma=sigmamat, log=TRUE)
U <- function(q, ...) -dmvnorm(x=q, sigma=sigmamat, log=TRUE)
L <- 11 #10
step <- 0.03 #0.03
Q <- list()
Q$q <- c(0,0)
postQ <- matrix(NA, nrow=nsamp, ncol=2)
postQ[1, ] <- c(0,0)
HMC(U, grad_U, epsilon=step, L=L, current_q=Q$q)
seed <- 9988776
set.seed(seed)
nsamp <- 3e4
nsamp <- 3e3
for (i in 1:nsamp)
{
cat("i = ",i," | q = ",q,"\t",sep="")
Q$q <- postQ[i, ] <- HMC(U, grad_U, epsilon=step, L=L, current_q=Q$q, sigmamat=sigmamat)
}
apply(postQ,2,mean)
apply(postQ,2,sd)
cov(postQ)
hist(postQ)
plot(postQ)
############### BOOK CODE
# the following oode contains loops that require a lot of computation time
# doing it once should mean to save the result afterward for further analysis and plots
# reload the results afterwards with load
?save
?load
# a lot of those models just show differences in the parameter configurations, but require
# due to the slow speed of the sampler a lot of time for calculations
# NOTE:
# another problem that may arise is that some functions/ parts of the script fail because other
# packages ie. libraries are loaded and use a (slightly) different syntax. As a consequence
# one should restart the R session which removes all loaded or attached packages and restart
# just from the point on where one left it - then one has to load all missing packages required
# for the code at this point
# It's impossible to always resolve that completely.
# example:
# bivariate probability density function
# correlation
rho <- 0.8
# sigmas
sigma1 <- 1
sigma2 <- 1
# Sigma matrix
sigmamat <- matrix(c(sigma1,rho*sigma1*sigma2,rho*sigma1*sigma2,sigma2),ncol=2)
sigmamat
#sigmamat <- matrix(c(4,2,2,3), ncol=2)
#sigmamat
# mu
mu <- c(1,1)
# point where to evaluate function
x <- c(0.5,0.4)
start_time <- Sys.time()
ND.pdf(x,mu,sigmamat)
end_time <- Sys.time()
end_time - start_time
start_time <- Sys.time()
mvtnorm:::dmvnorm(x,mean=mu,sigma=sigmamat)
end_time <- Sys.time()
end_time - start_time
# check gradient
numDeriv:::grad(f=mvtnorm:::dmvnorm, x=x, mean=mu, sigma=sigmamat)
numDeriv:::grad(f=ND.pdf, x=x ,mu=mu, sigmamat=sigmamat)
# does not work
rhmc:::num_grad(f=ND.pdf, x=x, mu=mu, sigmamat=sigmamat)
# we use this (tweaked version)
num_grad2(f=ND.pdf, x=x, mu=mu, sigmamat=sigmamat)
### HMC with HMC2()
#library(rethinking)
seed <- 9988776
seed <- 996 # with stepsize 0.03 bad example!
# we define two functions for the HMC sampling
# negative log likelihood for U
U <- function(q, ...) -mvtnorm:::dmvnorm(x=q, sigma=sigmamat, log=TRUE)
# gradient of U by making use of grad() from numDeriv
grad_U <- function(q, ...) -numDeriv:::grad(f=mvtnorm:::dmvnorm, x=q, sigma=sigmamat, log=TRUE)
# number of leapfrogs
L <- 11 #10
# step size epsilon
#WRONG step <- 0.03
step <- 0.1
# define a temporary list to store the Q results from HMC2()
Q <- list()
# initial value to start MCMC
Q$q <- c(0,0)
# try out functions whether they work
U(Q$q)
grad_U(Q$q)
Q
# MCMC repetitions ie. sample size
nsamp <- 3e4
nsamp <- 1e4
nsamp <- 1e3
# number of MCMC chains
nchains <- 5
#
coln <- length(Q$q)+1+1
Qres <- matrix(NA, nrow=nsamp, ncol=coln)
colnames(Qres) <- c("q1","q2","a","dH")
Qres[1,c(1:2)] <- Q$q
head(Qres)
# start random number generator initial value
set.seed(seed)
OUTmcmc <- list()
for(z in 1:nchains)
{
print(z)
Q <- list()
Q$q <- c(0,0)
for (i in 1:nsamp)
{
# print(i)
Q <- HMC2(U, grad_U, epsilon=step, L=L, current_q=Q$q)
Qres[i,"dH"] <- Q$dH
Qres[i,"a"] <- Q$accept
if(Q$a == 1) Qres[i,c(1:2)] <- Q$q
}
OUTmcmc[[z]] <- Qres
}
# summary
lapply(OUTmcmc, summary)
OUTmcmc.fn <- lapply(OUTmcmc,function(x) apply(x,2,fivenum))
OUTmcmc.fn
##########
# start random number generator initial value
seeds <- c(9988776, 996, 345, 321, 12399)
# epsilon
step <- 0.1
# number of leapfrogs
L <- 11
#mu <- c(0,0)
# initial value for q
Qinitv <- c(0,0)
# number of samples per MCMC chain
nsamp <- 1e3
# number of MCMC chains
nchains <- 5
posty <- bivarnormdist.HMC.sim(U=U, grad_U=grad_U, epsilon=step, L=11,
nchains=nchains, Qinitv=Qinitv,
nsamp=nsamp,
seeds=seeds #c(9988776, 996, 345, 321, 12399)
)
str(posty)
OUTmcmc <- posty
# compare with BAD starting values
step <- 0.03
L <- 11
step
L
Qinitv
nsamp <- 3e4
nsamp
seeds <- c(9988776, 996, 345, 321, 12399)
seeds
nchains <- 5
posty2 <- bivarnormdist.HMC.sim(U=U, grad_U=grad_U, epsilon=step, L=L,
nchains=5, Qinitv=Qinitv,
nsamp=nsamp,
seeds=seeds
)
#posty2.BP <- posty2
str(posty2)
head(posty2[[1]])
OUTmcmc <- posty2
# compare with GOOD starting values
step <- 0.1
L <- 11
step
L
Qinitv
nsamp <- 3e4
nsamp
seeds <- c(9988776, 996, 345, 321, 12399)
seeds
nchains <- 5
posty3 <- bivarnormdist.HMC.sim(U=U, grad_U=grad_U, epsilon=step, L=L,
nchains=nchains, Qinitv=Qinitv,
nsamp=nsamp,
seeds=seeds
)
post3.BP <- posty3
str(posty3)
head(posty3[[1]])
save(posty3, file="posty3_steps01.RDAta")
OUTmcmc <- posty3
# variability GOOD ONE
step <- 0.1
L <- 11
step
L
Qinitv
nsamp <- 1e3
nsamp
seeds <- c(9988776, 996, 345, 321, 12399,
395, 350, 840, 382, 573,
242, 891, 385, 680, 606,
770, 913, 795, 670, 736
)
length(seeds)
seeds
nchains <- 20
nchains
posty4 <- bivarnormdist.HMC.sim(U=U, grad_U=grad_U, epsilon=step, L=L,
nchains=nchains, Qinitv=Qinitv,
nsamp=nsamp,
seeds=seeds
)
post4.BP <- posty4
str(posty4)
head(posty4[[1]])
save(posty4, file="posty4_steps01_nsamps-1e3_nchains-20.RDAta")
OUTmcmc <- posty4
# variability BAD ONE
step <- 0.03
L <- 11
step
L
Qinitv
nsamp <- 1e3
nsamp
seeds <- c(9988776, 996, 345, 321, 12399,
395, 350, 840, 382, 573,
242, 891, 385, 680, 606,
770, 913, 795, 670, 736
)
length(seeds)
seeds
nchains <- 20
nchains
posty5 <- bivarnormdist.HMC.sim(U=U, grad_U=grad_U, epsilon=step, L=L,
nchains=nchains, Qinitv=Qinitv,
nsamp=nsamp,
seeds=seeds
)
post5.BP <- posty5
str(posty5)
head(posty5[[1]])
save(posty5, file="posty5_steps003_nsamps-1e3_nchains-20.RDAta")
OUTmcmc <- posty5
# variability BAD ONE
step <- 0.1
L <- 11
step
L
Qinitv
nsamp <- 3e3
nsamp
seeds <- c(9988776, 996, 345, 321, 12399,
395, 350, 840, 382, 573,
242, 891, 385, 680, 606,
770, 913, 795, 670, 736
)
length(seeds)
seeds
nchains <- 20
nchains
posty6 <- bivarnormdist.HMC.sim(U=U, grad_U=grad_U, epsilon=step, L=L,
nchains=nchains, Qinitv=c(1,1),
nsamp=nsamp,
seeds=seeds, sigma=sigmamat
)
post6.BP <- posty6
str(posty6)
head(posty6[[1]])
save(posty6, file="posty6_steps003_nsamps-3e3_nchains-20_Qinitv-1-1.RDAta")
OUTmcmc <- posty6
############
#posty2 nsamp 3e4 chains 5 step 0.03 L 11
#posty3 nsamp 3e4 chains 5 step 0.1 L 11
#posty4 nsamp 1e3 chains 20 step 0.03 L 11
#posty5 nsamp 1e3 chains 20 step 0.1 L 11
#k = 2; n=3; m = 4
#array(NA, c(n,m,k))
# inspect results
str(OUTmcmc)
# bayesplot package requires chains to be of the same length
# so we delete all NA rows and delete from all chains
# the same rows which therefor is a random delete
# there may be a better way like sampling till the iterations
# are fully complete with full valid observations
# and delete then NAs so it comes out for all chains to have
# the same number of rows (iterations) if cols (= vars)
NA.IDs <- lapply(OUTmcmc, function(x) which(is.na(x), arr.ind=TRUE))
NA.IDs
#unlist(lapply(NA.IDs, length))
NA.rowIDs <- unique(unlist(lapply(NA.IDs, function(x) x[,1])))
NA.rowIDs
NA.rowIDs.l <- length(NA.rowIDs)
NA.rowIDs.l
NA.rowIDs.diffs <- NA.rowIDs[2:NA.rowIDs.l]-NA.rowIDs[1:(NA.rowIDs.l-1)]
#library(unikn)
hist(NA.rowIDs.diffs, col=usecol(pal_bordeaux, n=6), main="Samples between NAs (= non-acceptance)", prob=TRUE, xlab="samples", ylab="prob")
lines(density(NA.rowIDs.diffs), col="blue", lwd=2)
c(summary(NA.rowIDs.diffs), sd=sd(NA.rowIDs.diffs))
# rate a
NA.rowIDs.l/nsamp
OUTmcmc.nonas <- list()
if(length(NA.rowIDs) > 0)
{
for(i in 1:nchains)
{
#OUTmcmc.nonas[[i]] <- OUTmcmc[[i]][-NA.IDs[[i]][,1],c("q1","q2")]
OUTmcmc.nonas[[i]] <- OUTmcmc[[i]][-NA.rowIDs,c("q1","q2")]
}
} else OUTmcmc.nonas <- OUTmcmc
lapply(OUTmcmc.nonas, function(x) which(is.na(x), arr.ind=TRUE))
head(OUTmcmc.nonas[[1]])
str(OUTmcmc.nonas)