-
Notifications
You must be signed in to change notification settings - Fork 1
/
source_sba.R
1608 lines (1400 loc) · 56.8 KB
/
source_sba.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
#---------------------------------------------------------------
# Source functions for semiparametric Bayesian regression
#---------------------------------------------------------------
#' Semiparametric Bayesian linear model
#'
#' Monte Carlo sampling for Bayesian linear regression with an
#' unknown (nonparametric) transformation. A g-prior is assumed
#' for the regression coefficients.
#'
#' @param y \code{n x 1} response vector
#' @param X \code{n x p} matrix of predictors
#' @param X_test \code{n_test x p} matrix of predictors for test data;
#' default is the observed covariates \code{X}
#' @param psi prior variance (g-prior)
#' @param laplace_approx logical; if TRUE, use a normal approximation
#' to the posterior in the definition of the transformation;
#' otherwise the prior is used
#' @param approx_g logical; if TRUE, apply large-sample
#' approximation for the transformation
#' @param nsave number of Monte Carlo simulations
#' @param ngrid number of grid points for inverse approximations
#' @param verbose logical; if TRUE, print time remaining
#' @return a list with the following elements:
#' \itemize{
#' \item \code{coefficients} the posterior mean of the regression coefficients
#' \item \code{fitted.values} the posterior predictive mean at the test points \code{X_test}
#' \item \code{post_theta}: \code{nsave x p} samples from the posterior distribution
#' of the regression coefficients
#' \item \code{post_ypred}: \code{nsave x n_test} samples
#' from the posterior predictive distribution at test points \code{X_test}
#' \item \code{post_g}: \code{nsave} posterior samples of the transformation
#' evaluated at the unique \code{y} values
#' \item \code{model}: the model fit (here, \code{sblm})
#' }
#' as well as the arguments passed in.
#'
#' @details This function provides fully Bayesian inference for a
#' transformed linear model using Monte Carlo (not MCMC) sampling.
#' The transformation is modeled as unknown and learned jointly
#' with the regression coefficients (unless \code{approx_g} = TRUE, which then uses
#' a point approximation). This model applies for real-valued data, positive data, and
#' compactly-supported data (the support is automatically deduced from the observed \code{y} values).
#' The results are typically unchanged whether \code{laplace_approx} is TRUE/FALSE;
#' setting it to TRUE may reduce sensitivity to the prior, while setting it to FALSE
#' may speed up computations for very large datasets.
#'
#' @examples
#' \donttest{
#' # Simulate some data:
#' dat = simulate_tlm(n = 100, p = 5, g_type = 'step')
#' y = dat$y; X = dat$X # training data
#' y_test = dat$y_test; X_test = dat$X_test # testing data
#'
#' hist(y, breaks = 25) # marginal distribution
#'
#' # Fit the semiparametric Bayesian linear model:
#' fit = sblm(y = y, X = X, X_test = X_test)
#' names(fit) # what is returned
#'
#' # Note: this is Monte Carlo sampling, so no need for MCMC diagnostics!
#'
#' # Evaluate posterior predictive means and intervals on the testing data:
#' plot_pptest(fit$post_ypred, y_test,
#' alpha_level = 0.10) # coverage should be about 90%
#'
#' # Check: correlation with true coefficients
#' cor(dat$beta_true[-1],
#' coef(fit)[-1]) # excluding the intercept
#'
#' # Summarize the transformation:
#' y0 = sort(unique(y)) # posterior draws of g are evaluated at the unique y observations
#' plot(y0, fit$post_g[1,], type='n', ylim = range(fit$post_g),
#' xlab = 'y', ylab = 'g(y)', main = "Posterior draws of the transformation")
#' temp = sapply(1:nrow(fit$post_g), function(s)
#' lines(y0, fit$post_g[s,], col='gray')) # posterior draws
#' lines(y0, colMeans(fit$post_g), lwd = 3) # posterior mean
#'
#' # Add the true transformation, rescaled for easier comparisons:
#' lines(y,
#' scale(dat$g_true)*sd(colMeans(fit$post_g)) + mean(colMeans(fit$post_g)), type='p', pch=2)
#' legend('bottomright', c('Truth'), pch = 2) # annotate the true transformation
#'
#' # Posterior predictive checks on testing data: empirical CDF
#' y0 = sort(unique(y_test))
#' plot(y0, y0, type='n', ylim = c(0,1),
#' xlab='y', ylab='F_y', main = 'Posterior predictive ECDF')
#' temp = sapply(1:nrow(fit$post_ypred), function(s)
#' lines(y0, ecdf(fit$post_ypred[s,])(y0), # ECDF of posterior predictive draws
#' col='gray', type ='s'))
#' lines(y0, ecdf(y_test)(y0), # ECDF of testing data
#' col='black', type = 's', lwd = 3)
#' }
#' @export
sblm = function(y, X, X_test = X,
psi = length(y),
laplace_approx = TRUE,
approx_g = FALSE,
nsave = 1000,
ngrid = 100,
verbose = TRUE){
# For testing:
# X_test = X; psi = length(y); laplace_approx = TRUE; approx_g = FALSE; nsave = 1000; verbose = TRUE; ngrid = 100
# Data dimensions:
n = length(y); p = ncol(X)
# Testing data points:
if(!is.matrix(X_test)) X_test = matrix(X_test, nrow = 1)
# And some checks on columns:
if(p >= n) stop('The g-prior requires p < n')
if(p != ncol(X_test)) stop('X_test and X must have the same number of columns')
#----------------------------------------------------------------------------
# Key matrix quantities:
XtX = crossprod(X)
XtXinv = chol2inv(chol(XtX))
xt_Sigma_x = sapply(1:n, function(i)
crossprod(X[i,], XtXinv)%*%X[i,])
#----------------------------------------------------------------------------
# Initialize the transformation:
# Define the CDF of y:
Fy = function(t) n/(n+1)*ecdf(y)(t)
# Evaluate at the unique y-values:
y0 = sort(unique(y))
Fy_eval = Fy(y0)
# Grid of values for the CDF of z (based on the prior)
z_grid = sort(unique(
sapply(range(psi*xt_Sigma_x), function(xtemp){
qnorm(seq(0.01, 0.99, length.out = ngrid),
mean = 0, # assuming prior mean zero
sd = sqrt(1 + xtemp))
})
))
# Define the moments of the CDF of z:
if(laplace_approx){
# Use a normal approximation for the posterior of theta
# Recurring terms:
Sigma_hat_unscaled = psi/(1+psi)*XtXinv # unscaled covariance (w/o sigma)
xt_Sigma_hat_unscaled_x = sapply(1:n, function(i)
crossprod(X[i,], Sigma_hat_unscaled)%*%X[i,])
# First pass: fix Fz() = qnorm(), initialize coefficients
z = qnorm(Fy(y))
theta_hat = Sigma_hat_unscaled%*%crossprod(X, z) # point estimate
# Alternative rank-based approaches (SLOW! but similar...)
# theta_hat = rank_approx(y, X) # alternative rank-based approach
# theta_hat= coef(Rfit::rfit(y ~ X))[-1] # faster, but less accurate
# that function also comes with a sd estimate
# Second pass: update g(), then update coefficients
# Moments of Z|X:
mu_z = X%*%theta_hat
sigma_z = sqrt(1 + xt_Sigma_hat_unscaled_x)
# CDF of z:
Fz_eval = Fz_fun(z = z_grid,
weights = rep(1/n, n),
mean_vec = mu_z,
sd_vec = sigma_z)
# Check: update the grid if needed
zcon = contract_grid(z = z_grid,
Fz = Fz_eval,
lower = 0.001, upper = 0.999)
z_grid = zcon$z; Fz_eval = zcon$Fz
# Transformation:
g = g_fun(y = y0,
Fy_eval = Fy_eval,
z = z_grid,
Fz_eval = Fz_eval)
# Updated coefficients:
z = g(y) # update latent data
theta_hat = Sigma_hat_unscaled%*%crossprod(X, z) # updated coefficients
# Moments of Z|X:
mu_z = X%*%theta_hat
#sigma_z = sqrt(1 + xt_Sigma_hat_unscaled_x) # no need to update
} else {
# Prior mean is zero:
mu_z = rep(0, n)
# Marginal SD based on prior:
sigma_z = sqrt(1 + psi*xt_Sigma_x)
}
# Define the CDF of z:
Fz_eval = Fz_fun(z = z_grid,
weights = rep(1/n, n),
mean_vec = mu_z,
sd_vec = sigma_z)
# Check: update the grid if needed
zcon = contract_grid(z = z_grid,
Fz = Fz_eval,
lower = 0.001, upper = 0.999)
z_grid = zcon$z; Fz_eval = zcon$Fz
# Compute the transformation:
g = g_fun(y = y0, Fy_eval = Fy_eval,
z = z_grid, Fz_eval = Fz_eval)
# Latent data:
z = g(y)
# Define the grid for approximations using equally-spaced + quantile points:
y_grid = sort(unique(c(
seq(min(y), max(y), length.out = ngrid/2),
quantile(y0, seq(0, 1, length.out = ngrid/2)))))
# Inverse transformation function:
g_inv = g_inv_approx(g = g, t_grid = y_grid)
#----------------------------------------------------------------------------
# Store MC output:
post_theta = array(NA, c(nsave, p))
post_ypred = array(NA, c(nsave, nrow(X_test)))
post_g = array(NA, c(nsave, length(y0)))
# Run the MC:
if(verbose) timer0 = proc.time()[3] # For timing the sampler
for(nsi in 1:nsave){
# NOTE: we could do this in blocks, perhaps more efficiently...
#----------------------------------------------------------------------------
# Block 1: sample the transformation
if(!approx_g){
# Bayesian bootstrap for the CDFs
# Dirichlet(1) weights for y:
weights_y = rgamma(n = n, shape = 1)
weights_y = weights_y/sum(weights_y)
# Dirichlet(1) weights for x:
weights_x = rgamma(n = n, shape = 1)
weights_x = weights_x/sum(weights_x)
# BB CDF of y:
Fy_eval = sapply(y0, function(t)
n/(n+1)*sum(weights_y[y <= t]))
# BB CDF of z:
Fz_eval = Fz_fun(z = z_grid,
weights = weights_x,
mean_vec = mu_z,
sd_vec = sigma_z)
# Compute the transformation:
g = g_fun(y = y0, Fy_eval = Fy_eval,
z = z_grid, Fz_eval = Fz_eval)
# Update z:
z = g(y)
# Update the inverse transformation function:
g_inv = g_inv_approx(g = g, t_grid = y_grid)
}
#----------------------------------------------------------------------------
# Block 2: sample the scale adjustment (SD)
SSR_psi = sum(z^2) - psi/(psi+1)*crossprod(z, X%*%XtXinv%*%crossprod(X, z))
sigma_epsilon = 1/sqrt(rgamma(n = 1,
shape = .001 + n/2,
rate = .001 + SSR_psi/2))
#----------------------------------------------------------------------------
# Block 3: sample the regression coefficients
ch_Q = chol(1/sigma_epsilon^2*(1+psi)/(psi)*XtX)
ell_theta = 1/sigma_epsilon^2*crossprod(X, z)
theta = backsolve(ch_Q,
forwardsolve(t(ch_Q), ell_theta) +
rnorm(p))
#----------------------------------------------------------------------------
# Store the MC:
# Posterior samples of the model parameters:
post_theta[nsi,] = theta
# Predictive samples of ytilde:
ztilde = X_test%*%theta + sigma_epsilon*rnorm(n = nrow(X_test))
post_ypred[nsi,] = g_inv(ztilde)
# Posterior samples of the transformation:
post_g[nsi,] = g(y0)
#----------------------------------------------------------------------------
if(verbose) computeTimeRemaining(nsi, timer0, nsave, nrep = ceiling(nsave/3))
}
if(verbose) print(paste('Total time: ', round((proc.time()[3] - timer0)), 'seconds'))
return(list(
coefficients = colMeans(post_theta),
fitted.values = colMeans(post_ypred),
post_theta = post_theta,
post_ypred = post_ypred,
post_g = post_g,
model = 'sblm', y = y, X = X, X_test = X_test, psi = psi, approx_g = approx_g, sigma_epsilon = sigma_epsilon))
}
#---------------------------------------------------------------
#' Semiparametric Bayesian spline model
#'
#' Monte Carlo sampling for Bayesian spline regression with an
#' unknown (nonparametric) transformation.
#'
#' @param y \code{n x 1} response vector
#' @param x \code{n x 1} vector of observation points; if NULL, assume equally-spaced on [0,1]
#' @param x_test \code{n_test x 1} vector of testing points; if NULL, assume equal to \code{x}
#' @param psi prior variance (inverse smoothing parameter); if NULL,
#' sample this parameter
#' @param laplace_approx logical; if TRUE, use a normal approximation
#' to the posterior in the definition of the transformation;
#' otherwise the prior is used
#' @param approx_g logical; if TRUE, apply large-sample
#' approximation for the transformation
#' @param nsave number of Monte Carlo simulations
#' @param ngrid number of grid points for inverse approximations
#' @param verbose logical; if TRUE, print time remaining
#' @return a list with the following elements:
#' \itemize{
#' \item \code{coefficients} the posterior mean of the regression coefficients
#' \item \code{fitted.values} the posterior predictive mean at the test points \code{x_test}
#' \item \code{post_theta}: \code{nsave x p} samples from the posterior distribution
#' of the regression coefficients
#' \item \code{post_ypred}: \code{nsave x n_test} samples
#' from the posterior predictive distribution at \code{x_test}
#' \item \code{post_g}: \code{nsave} posterior samples of the transformation
#' evaluated at the unique \code{y} values
#' \item \code{model}: the model fit (here, \code{sbsm})
#' }
#' as well as the arguments passed in.
#'
#' @details This function provides fully Bayesian inference for a
#' transformed spline regression model using Monte Carlo (not MCMC) sampling.
#' The transformation is modeled as unknown and learned jointly
#' with the regression function (unless \code{approx_g} = TRUE, which then uses
#' a point approximation). This model applies for real-valued data, positive data, and
#' compactly-supported data (the support is automatically deduced from the observed \code{y} values).
#' The results are typically unchanged whether \code{laplace_approx} is TRUE/FALSE;
#' setting it to TRUE may reduce sensitivity to the prior, while setting it to FALSE
#' may speed up computations for very large datasets.
#'
#' @examples
#' \donttest{
#' # Simulate some data:
#' n = 100 # sample size
#' x = sort(runif(n)) # observation points
#'
#' # Transform a noisy, periodic function:
#' y = g_inv_bc(
#' sin(2*pi*x) + sin(4*pi*x) + rnorm(n, sd = .5),
#' lambda = .5) # Signed square-root transformation
#'
#' # Fit the semiparametric Bayesian spline model:
#' fit = sbsm(y = y, x = x)
#' names(fit) # what is returned
#'
#' # Note: this is Monte Carlo sampling, so no need for MCMC diagnostics!
#'
#' # Plot the model predictions (point and interval estimates):
#' pi_y = t(apply(fit$post_ypred, 2, quantile, c(0.05, .95))) # 90% PI
#' plot(x, y, type='n', ylim = range(pi_y,y),
#' xlab = 'x', ylab = 'y', main = paste('Fitted values and prediction intervals'))
#' polygon(c(x, rev(x)),c(pi_y[,2], rev(pi_y[,1])),col='gray', border=NA)
#' lines(x, y, type='p')
#' lines(x, fitted(fit), lwd = 3)
#' }
#' @importFrom spikeSlabGAM sm
#' @export
sbsm = function(y, x = NULL,
x_test = NULL,
psi = NULL,
laplace_approx = TRUE,
approx_g = FALSE,
nsave = 1000,
ngrid = 100,
verbose = TRUE){
# For testing:
# psi = length(y); laplace_approx = TRUE; approx_g = FALSE; nsave = 1000; verbose = TRUE; x_test = sort(runif(100)); ngrid = 100
# Data dimensions:
n = length(y)
# Observation points:
if(is.null(x)) x = seq(0, 1, length=n)
if(is.null(x_test)) x_test = x
# Recale to [0,1]:
x = (x - min(x))/(max(x) - min(x))
x_test = (x_test - min(x_test))/(max(x_test) - min(x_test))
#----------------------------------------------------------------------------
# Orthogonalized P-spline and related quantities:
X = cbind(1/sqrt(n), poly(x, 1), sm(x))
X = X/sqrt(sum(diag(crossprod(X))))
diagXtX = colSums(X^2)
p = length(diagXtX)
# Recurring term:
xt_Sigma_x = rowSums(X^2) # sapply(1:n, function(i) sum(X[i,]^2/diagXtX))
# Smoothing parameter:
if(is.null(psi)){
# Flag to sample:
sample_psi = TRUE
# Initialize:
psi = n
} else sample_psi = FALSE
#----------------------------------------------------------------------------
# Initialize the transformation:
# Define the CDF of y:
Fy = function(t) n/(n+1)*ecdf(y)(t)
# Evaluate at the unique y-values:
y0 = sort(unique(y))
Fy_eval = Fy(y0)
# Grid of values for the CDF of z:
z_grid = sort(unique(
sapply(range(psi*xt_Sigma_x), function(xtemp){
qnorm(seq(0.01, 0.99, length.out = ngrid),
mean = 0, # assuming prior mean zero
sd = sqrt(1 + xtemp))
})
))
# Define the moments of the CDF of z:
if(laplace_approx){
# Use a normal approximation for the posterior of theta
# Recurring terms:
diag_Sigma_hat_unscaled = 1/(diagXtX + 1/psi)
xt_Sigma_hat_unscaled_x = colSums(t(X^2)*diag_Sigma_hat_unscaled)
#xt_Sigma_hat_unscaled_x = sapply(1:n, function(i)
# crossprod(X[i,], diag(diag_Sigma_hat_unscaled))%*%X[i,])
# First pass: fix Fz() = qnorm(), initialize coefficients
z = qnorm(Fy(y))
theta_hat = diag_Sigma_hat_unscaled*crossprod(X, z) # point estimate
# Second pass: update g(), then update coefficients
# Moments of Z|X:
mu_z = X%*%theta_hat
sigma_z = sqrt(1 + xt_Sigma_hat_unscaled_x)
# CDF of z:
Fz_eval = Fz_fun(z = z_grid,
weights = rep(1/n, n),
mean_vec = mu_z,
sd_vec = sigma_z)
# Check: update the grid if needed
zcon = contract_grid(z = z_grid,
Fz = Fz_eval,
lower = 0.001, upper = 0.999)
z_grid = zcon$z; Fz_eval = zcon$Fz
# Transformation:
g = g_fun(y = y0,
Fy_eval = Fy_eval,
z = z_grid,
Fz_eval = Fz_eval)
# Updated coefficients:
z = g(y) # update latent data
theta_hat = diag_Sigma_hat_unscaled*crossprod(X, z) # updated coefficients
# Moments of Z|X:
mu_z = X%*%theta_hat
#sigma_z = sqrt(1 + xt_Sigma_hat_unscaled_x)
} else {
# Prior mean is zero:
mu_z = rep(0, n)
# Marginal SD based on prior:
sigma_z = sqrt(1 + psi*xt_Sigma_x)
}
# Define the CDF of z:
Fz_eval = Fz_fun(z = z_grid,
weights = rep(1/n, n),
mean_vec = mu_z,
sd_vec = sigma_z)
# Check: update the grid if needed
zcon = contract_grid(z = z_grid,
Fz = Fz_eval,
lower = 0.001, upper = 0.999)
z_grid = zcon$z; Fz_eval = zcon$Fz
# Compute the transformation:
g = g_fun(y = y0, Fy_eval = Fy_eval,
z = z_grid, Fz_eval = Fz_eval)
# Latent data:
z = g(y)
# Define the grid for approximations using equally-spaced + quantile points:
y_grid = sort(unique(c(
seq(min(y), max(y), length.out = ngrid/2),
quantile(y0, seq(0, 1, length.out = ngrid/2)))))
# Inverse transformation function:
g_inv = g_inv_approx(g = g, t_grid = y_grid)
# For fully BNP, do not sample psi:
#----------------------------------------------------------------------------
# Store MC output:
post_theta = array(NA, c(nsave, p))
post_ypred = array(NA, c(nsave, length(x_test)))
post_g = array(NA, c(nsave, length(y0)))
post_psi = rep(NA, nsave)
# Run the MC:
if(verbose) timer0 = proc.time()[3] # For timing the sampler
for(nsi in 1:nsave){
#----------------------------------------------------------------------------
# Block 1: sample the transformation
if(!approx_g){
# Bayesian bootstrap for the CDFs
# Dirichlet(1) weights for y:
weights_y = rgamma(n = n, shape = 1)
weights_y = weights_y/sum(weights_y)
# Dirichlet(1) weights for x:
weights_x = rgamma(n = n, shape = 1)
weights_x = weights_x/sum(weights_x)
# BB CDF of y: (NOTE could be faster!)
Fy_eval = sapply(y0, function(t)
n/(n+1)*sum(weights_y[y <= t]))
# BB CDF of z:
Fz_eval = Fz_fun(z = z_grid,
weights = weights_x,
mean_vec = mu_z,
sd_vec = sigma_z)
# Compute the transformation:
g = g_fun(y = y0, Fy_eval = Fy_eval,
z = z_grid, Fz_eval = Fz_eval)
# Update z:
z = g(y)
# Update the inverse transformation function:
g_inv = g_inv_approx(g = g, t_grid = y_grid)
}
#----------------------------------------------------------------------------
# Block 2: sample the scale adjustment (SD)
# SSR_psi = sum(z^2) - crossprod(z, X%*%solve(crossprod(X) + diag(1/psi, p))%*%crossprod(X,z))
SSR_psi = sum(z^2) - crossprod(1/sqrt(diagXtX + 1/psi)*crossprod(X, z))
sigma_epsilon = 1/sqrt(rgamma(n = 1,
shape = .001 + n/2,
rate = .001 + SSR_psi/2))
#----------------------------------------------------------------------------
# Block 3: sample the regression coefficients
Q_theta = 1/sigma_epsilon^2*(diagXtX + 1/psi)
ell_theta = 1/sigma_epsilon^2*crossprod(X, z)
theta = rnorm(n = p,
mean = Q_theta^-1*ell_theta,
sd = sqrt(Q_theta^-1))
#----------------------------------------------------------------------------
# Block 4: sample the smoothing parameter
if(sample_psi){
psi = 1/rgamma(n = 1,
shape = 0.01 + p/2,
rate = 0.01 + sum(theta^2)/(2*sigma_epsilon^2))
}
#----------------------------------------------------------------------------
# Store the MC:
# Posterior samples of the model parameters:
post_theta[nsi,] = theta
# Predictive samples of ytilde:
# Note: it's easier/faster to just smooth for the testing points
# (the orthogonalized basis is a pain to recompute)
ztilde = stats::spline(x = x, y = X%*%theta, xout = x_test)$y +
sigma_epsilon*rnorm(n = length(x_test))
post_ypred[nsi,] = g_inv(ztilde)
# Posterior samples of the transformation:
post_g[nsi,] = g(y0)
post_psi[nsi] = psi
#----------------------------------------------------------------------------
if(verbose) computeTimeRemaining(nsi, timer0, nsave, nrep = ceiling(nsave/2))
}
if(verbose) print(paste('Total time: ', round((proc.time()[3] - timer0)), 'seconds'))
return(list(
coefficients = colMeans(post_theta),
fitted.values = colMeans(post_ypred),
post_theta = post_theta,
post_ypred = post_ypred,
post_g = post_g, post_psi = post_psi,
model = 'sbsm', y = y, X = X, psi = psi, approx_g = approx_g, sigma_epsilon = sigma_epsilon))
}
#---------------------------------------------------------------
#' Semiparametric Bayesian Gaussian processes
#'
#' Monte Carlo sampling for Bayesian Gaussian process regression with an
#' unknown (nonparametric) transformation.
#'
#' @param y \code{n x 1} response vector
#' @param locs \code{n x d} matrix of locations
#' @param X \code{n x p} design matrix; if unspecified, use intercept only
#' @param covfun_name string name of a covariance function; see ?GpGp
#' @param locs_test \code{n_test x d} matrix of locations
#' at which predictions are needed; default is \code{locs}
#' @param X_test \code{n_test x p} design matrix for test data;
#' default is \code{X}
#' @param nn number of nearest neighbors to use; default is 30
#' (larger values improve the approximation but increase computing cost)
#' @param emp_bayes logical; if TRUE, use a (faster!) empirical Bayes
#' approach for estimating the mean function
#' @param approx_g logical; if TRUE, apply large-sample
#' approximation for the transformation
#' @param nsave number of Monte Carlo simulations
#' @param ngrid number of grid points for inverse approximations
#' @return a list with the following elements:
#' \itemize{
#' \item \code{coefficients} the estimated regression coefficients
#' \item \code{fitted.values} the posterior predictive mean at the test points \code{locs_test}
#' \item \code{fit_gp} the fitted \code{GpGp_fit} object, which includes
#' covariance parameter estimates and other model information
#' \item \code{post_ypred}: \code{nsave x ntest} samples
#' from the posterior predictive distribution at \code{locs_test}
#' \item \code{post_g}: \code{nsave} posterior samples of the transformation
#' evaluated at the unique \code{y} values
#' \item \code{model}: the model fit (here, \code{sbgp})
#' }
#' as well as the arguments passed in.
#'
#' @details This function provides Bayesian inference for a
#' transformed Gaussian process model using Monte Carlo (not MCMC) sampling.
#' The transformation is modeled as unknown and learned jointly
#' with the regression function (unless \code{approx_g} = TRUE, which then uses
#' a point approximation). This model applies for real-valued data, positive data, and
#' compactly-supported data (the support is automatically deduced from the observed \code{y} values).
#' The results are typically unchanged whether \code{laplace_approx} is TRUE/FALSE;
#' setting it to TRUE may reduce sensitivity to the prior, while setting it to FALSE
#' may speed up computations for very large datasets. For computational efficiency,
#' the Gaussian process parameters are fixed at point estimates, and the latent Gaussian
#' process is only sampled when \code{emp_bayes} = FALSE. However, the uncertainty
#' from this term is often negligible compared to the observation errors, and the
#' transformation serves as an additional layer of robustness.
#'
#' @examples
#' \donttest{
#' # Simulate some data:
#' n = 200 # sample size
#' x = seq(0, 1, length = n) # observation points
#'
#' # Transform a noisy, periodic function:
#' y = g_inv_bc(
#' sin(2*pi*x) + sin(4*pi*x) + rnorm(n, sd = .5),
#' lambda = .5) # Signed square-root transformation
#'
#' # Fit the semiparametric Bayesian Gaussian process:
#' fit = sbgp(y = y, locs = x)
#' names(fit) # what is returned
#' coef(fit) # estimated regression coefficients (here, just an intercept)
#' class(fit$fit_gp) # the GpGp object is also returned
#'
#' # Plot the model predictions (point and interval estimates):
#' pi_y = t(apply(fit$post_ypred, 2, quantile, c(0.05, .95))) # 90% PI
#' plot(x, y, type='n', ylim = range(pi_y,y),
#' xlab = 'x', ylab = 'y', main = paste('Fitted values and prediction intervals'))
#' polygon(c(x, rev(x)),c(pi_y[,2], rev(pi_y[,1])),col='gray', border=NA)
#' lines(x, y, type='p')
#' lines(x, fitted(fit), lwd = 3)
#' }
#' @import GpGp fields
#' @export
sbgp = function(y, locs,
X = NULL,
covfun_name = "matern_isotropic",
locs_test = locs,
X_test = NULL,
nn = 30,
emp_bayes = TRUE,
approx_g = FALSE,
nsave = 1000,
ngrid = 100){
# library(GpGp) # see if this fixes it...
# For testing:
# X = matrix(1, nrow = length(y)); covfun_name = "matern_isotropic"; locs_test = locs; X_test = X; nn = 30; emp_bayes = TRUE; approx_g = FALSE; nsave = 1000; ngrid = 100
# Data dimensions:
y = as.matrix(y); n = length(y);
locs = as.matrix(locs); d = ncol(locs)
# Testing data:
locs_test = as.matrix(locs_test); n_test = nrow(locs_test)
# Covariates:
if(is.null(X)) X = matrix(1, nrow = n)
if(is.null(X_test)){ # supply our own testing matrix
if(isTRUE(all.equal(locs, locs_test))){
# If the training and testing points are the same,
# then we input the same design matrix for the testing:
X_test = X
} else {
# Otherwise, use an intercept-only with the correct dimensions:
X_test = matrix(1, n_test)
}
}
# And check:
X = as.matrix(X); p = ncol(X)
X_test = as.matrix(X_test)
# Some checks needed for locs, locs_test, X, X_test
if(nrow(locs) != n || nrow(X) != n || nrow(X_test) != n_test ||
ncol(X_test) != p || ncol(locs_test) != d){
stop('Check input dimensions!')
}
# To avoid errors for small n:
nn = min(nn, n-1)
# This is a temporary hack needed for sampling w/ one-dimensional inputs:
if(!emp_bayes && d==1){
aug = 1e-6*rnorm(n)
locs = cbind(locs, aug)
locs_test = cbind(locs_test, aug)
}
# Define the CDF of y:
Fy = function(t) n/(n+1)*ecdf(y)(t)
#----------------------------------------------------------------------------
print('Initial GP fit...')
# Initial GP fit:
z = qnorm(Fy(y))
fit_gp = GpGp::fit_model(y = z,
locs = locs,
X = X,
covfun_name = covfun_name,
m_seq = nn,
silent = TRUE)
# Fitted values for observed data:
mu_z = GpGp::predictions(fit = fit_gp,
locs_pred = locs,
X_pred = X)
# SD of latent term:
# Nugget variance (NOTE: this works for most (but not all!) covariance functions in GpGp!)
sigma_epsilon = sqrt(fit_gp$covparms[1]*fit_gp$covparms[length(fit_gp$covparms)])
if(n < 1000){
# Compute the covariance matrix, but remove the nugget:
K_theta = do.call(covfun_name, list(fit_gp$covparms, locs ))
#K_theta = match.fun(covfun_name)(fit_gp$covparms, locs)
diag(K_theta) = diag(K_theta) - sigma_epsilon^2
# Posterior covariance for mu requires inverses:
K_theta_inv = chol2inv(chol(K_theta))
Sigma_mu = chol2inv(chol(K_theta_inv + diag(1/sigma_epsilon^2, n)))
# Extract the diagonal elements for z:
sigma_z = sqrt(sigma_epsilon^2 + diag(Sigma_mu))
} else {
# Ignore the uncertainty in the regression function,
# which is likely small when n is very large (also much faster...)
sigma_z = rep(sigma_epsilon, n)
}
#----------------------------------------------------------------------------
# Initialize the transformation:
# Evaluate CDF of Y at the unique y-values:
y0 = sort(unique(y)); Fy_eval = Fy(y0)
# Grid of values for the CDF of z:
z_grid = sort(unique(
sapply(range(mu_z), function(xtemp){
qnorm(seq(0.01, 0.99, length.out = ngrid),
mean = xtemp,
sd = sigma_epsilon)
})
))
# Evaluate the CDF of z:
Fz_eval = Fz_fun(z = z_grid,
weights = rep(1/n, n),
mean_vec = mu_z,
sd_vec = sigma_z)
# Compute the transformation:
g = g_fun(y = y0, Fy_eval = Fy_eval,
z = z_grid, Fz_eval = Fz_eval)
# Latent data:
z = g(y)
# Define the grid for approximations using equally-spaced + quantile points:
y_grid = sort(unique(c(
seq(min(y), max(y), length.out = ngrid/2),
quantile(y0, seq(0, 1, length.out = ngrid/2)))))
# Inverse transformation function:
g_inv = g_inv_approx(g = g, t_grid = y_grid)
#----------------------------------------------------------------------------
print('Updated GP fit...')
# Now update the GP coefficients:
fit_gp = GpGp::fit_model(y = z,
locs = locs,
X = X,
covfun_name = covfun_name,
start_parms = fit_gp$covparms,
m_seq = nn,
silent = TRUE)
# Fitted values for observed data:
mu_z = GpGp::predictions(fit = fit_gp,
locs_pred = locs,
X_pred = X,
m = nn)
# Fitted values for testing data:
if(isTRUE(all.equal(X, X_test)) &&
isTRUE(all.equal(locs, locs_test))){
# If the testing and training data are identical,
# then there is no need to apply a separate predict function
z_test = mu_z
} else {
z_test = GpGp::predictions(fit = fit_gp,
locs_pred = locs_test,
X_pred = X_test,
m = nn)
}
# SD of latent term:
# Nugget variance (NOTE: this works for most (but not all!) covariance functions in GpGp!)
sigma_epsilon = sqrt(fit_gp$covparms[1]*fit_gp$covparms[length(fit_gp$covparms)])
if(n < 1000){
# Compute the covariance matrix, but remove the nugget:
K_theta = do.call(covfun_name, list(fit_gp$covparms, locs ))
#K_theta = match.fun(covfun_name)(fit_gp$covparms, locs)
diag(K_theta) = diag(K_theta) - sigma_epsilon^2
# Posterior covariance for mu requires inverses:
K_theta_inv = chol2inv(chol(K_theta))
Sigma_mu = chol2inv(chol(K_theta_inv + diag(1/sigma_epsilon^2, n)))
# Extract the diagonal elements for z:
sigma_z = sqrt(sigma_epsilon^2 + diag(Sigma_mu))
} else {
# Ignore the uncertainty in the regression function,
# which is likely small when n is very large (this is also faster...)
sigma_z = rep(sigma_epsilon, n)
}
# Estimated coefficients:
theta = fit_gp$betahat
#----------------------------------------------------------------------------
# Store MC output:
post_ypred = array(NA, c(nsave, n_test))
post_g = array(NA, c(nsave, length(y0)))
print('Sampling...')
# Run the MC:
for(nsi in 1:nsave){
#----------------------------------------------------------------------------
# Sample the transformation
if(!approx_g){
# Bayesian bootstrap for the CDFs
# Dirichlet(1) weights for y:
weights_y = rgamma(n = n, shape = 1)
weights_y = weights_y/sum(weights_y)
# Dirichlet(1) weights for x:
weights_x = rgamma(n = n, shape = 1)
weights_x = weights_x/sum(weights_x)
# BB CDF of y:
Fy_eval = sapply(y0, function(t)
n/(n+1)*sum(weights_y[y <= t]))
# BB CDF of z:
Fz_eval = Fz_fun(z = z_grid,
weights = weights_x,
mean_vec = mu_z,
sd_vec = sigma_z)
# Compute the transformation:
g = g_fun(y = y0, Fy_eval = Fy_eval,
z = z_grid, Fz_eval = Fz_eval)
# Update z:
z = g(y)
# Update the inverse transformation function:
g_inv = g_inv_approx(g = g, t_grid = y_grid)
}
#----------------------------------------------------------------------------
# Store the MC:
# Predictive samples of ytilde:
if(emp_bayes){
ztilde = z_test + sigma_epsilon*rnorm(n = n_test)
} else {
ztilde = cond_sim(fit = fit_gp,
locs_pred = locs_test,
X_pred = X_test,
m = nn)
}
post_ypred[nsi,] = g_inv(ztilde)
# Posterior samples of the transformation:
post_g[nsi,] = g(y0)
#----------------------------------------------------------------------------
}
print('Done!')
return(list(
coefficients = theta,
fitted.values = colMeans(post_ypred),
fit_gp = fit_gp,
post_ypred = post_ypred,
post_g = post_g,
model = 'sbgp', y = y, X = X, approx_g = approx_g, sigma_epsilon = sigma_epsilon))
}
#' Semiparametric Bayesian quantile regression
#'
#' MCMC sampling for Bayesian quantile regression with an
#' unknown (nonparametric) transformation. Like in traditional Bayesian
#' quantile regression, an asymmetric Laplace distribution is assumed
#' for the errors, so the regression models targets the specified quantile.
#' However, these models are often woefully inadequate for describing
#' observed data. We introduce a nonparametric transformation to
#' improve model adequacy while still providing inference for the
#' regression coefficients and the specified quantile. A g-prior is assumed
#' for the regression coefficients.
#'
#' @param y \code{n x 1} response vector
#' @param X \code{n x p} matrix of predictors
#' @param tau the target quantile (between zero and one)
#' @param X_test \code{n_test x p} matrix of predictors for test data;
#' default is the observed covariates \code{X}
#' @param psi prior variance (g-prior)
#' @param laplace_approx logical; if TRUE, use a normal approximation
#' to the posterior in the definition of the transformation;
#' otherwise the prior is used
#' @param approx_g logical; if TRUE, apply large-sample
#' approximation for the transformation
#' @param nsave number of MCMC iterations to save
#' @param nburn number of MCMC iterations to discard
#' @param ngrid number of grid points for inverse approximations
#' @param verbose logical; if TRUE, print time remaining
#' @return a list with the following elements:
#' \itemize{
#' \item \code{coefficients} the posterior mean of the regression coefficients
#' \item \code{fitted.values} the estimated \code{tau}th quantile at test points \code{X_test}
#' \item \code{post_theta}: \code{nsave x p} samples from the posterior distribution
#' of the regression coefficients
#' \item \code{post_ypred}: \code{nsave x n_test} samples
#' from the posterior predictive distribution at test points \code{X_test}
#' \item \code{post_qtau}: \code{nsave x n_test} samples of the \code{tau}th conditional quantile at test points \code{X_test}
#' \item \code{post_g}: \code{nsave} posterior samples of the transformation
#' evaluated at the unique \code{y} values
#' \item \code{model}: the model fit (here, \code{sbqr})
#' }
#' as well as the arguments passed in.
#'
#' @details This function provides fully Bayesian inference for a
#' transformed quantile linear model.
#' The transformation is modeled as unknown and learned jointly
#' with the regression coefficients (unless \code{approx_g} = TRUE, which then uses
#' a point approximation). This model applies for real-valued data, positive data, and
#' compactly-supported data (the support is automatically deduced from the observed \code{y} values).
#' The results are typically unchanged whether \code{laplace_approx} is TRUE/FALSE;
#' setting it to TRUE may reduce sensitivity to the prior, while setting it to FALSE
#' may speed up computations for very large datasets.
#'