-
Notifications
You must be signed in to change notification settings - Fork 0
/
source_subsel.R
1708 lines (1477 loc) · 63.2 KB
/
source_subsel.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
#' Branch-and-bound algorithm for linear subset search
#'
#' Search for the "best" (according to residual sum of squares)
#' linear subsets of each size. The algorithm may collect
#' the \code{n_best} "best" subsets of each size, include or
#' exclude certain variables automatically, and apply
#' forward, backward, or exhaustive search.
#'
#' @param yy vector of response variables
#' @param XX matrix of covariates
#' @param wts vector of observation weights (for weighted least squares)
#' @param n_best number of "best" subsets for each model size
#' @param to_include indices of covariates to include in *all* subsets
#' @param to_exclude indices of covariates to exclude from *all* subsets
#' @param searchtype use exhaustive search, forward selection, backward selection or sequential replacement to search
#' @return \code{inclusion_index}: the matrix of inclusion indicators (columns) for
#' each subset returned (rows)
#'
#' @examples
#' # Simulate data:
#' dat = simulate_lm(n = 100, p = 10)
#'
#' # Run branch-and-bound:
#' indicators = branch_and_bound(yy = dat$y, XX = dat$X)
#'
#' # Inspect:
#' head(indicators)
#'
#' # Dimensions:
#' dim(indicators)
#'
#' # Model sizes:
#' rowSums(indicators)
#'
#' @importFrom leaps regsubsets
#' @export
branch_and_bound = function(yy,
XX,
wts = NULL,
n_best = 15,
to_include = 1,
to_exclude = NULL,
searchtype = 'exhaustive'
){
# Get dimensions of the covariate matrix:
n = nrow(XX); p = ncol(XX)
# Useful step:
xnames = colnames(XX);
colnames(XX) = 1:p
# Some basic checks:
if(length(yy) !=n)
stop('length of yy must equal the number of rows of XX')
if(!is.null(to_include) && !is.null(to_exclude)){
# Quick check:
if(any(!is.na(match(to_include, to_exclude))))
stop('Cannot include and exclude the same variables!')
# Reindex to account for the excluded terms:
to_include = match(to_include, (1:p)[-to_exclude])
}
# And a warning if the number of predictors is too large
if(p - length(to_exclude) > 40 && searchtype == 'exhaustive'){
warning("Inadvisable number of predictors for exhaustive search: slow computing! Try pre-screening to exclude some variables.")
}
if(!is.null(wts)){
if(length(wts) != n)
stop('wts must have length n')
} else wts = rep(1,n)
# Delete the excluded columns, if any:
if(!is.null(to_exclude))
XX = XX[,-to_exclude]
# Branch-and-bound search:
fit_all = leaps::regsubsets(x = XX, y = yy,
weights = wts,
nbest = n_best, nvmax = p,
method = searchtype,
intercept = FALSE,
really.big = TRUE,
force.in = to_include)
# Indicator matrix of variable inclusions for each subset:
temp_inclusion_index = summary(fit_all)$which
# Inclusion index: need to adjust for excluded variables
inclusion_index = matrix(FALSE, # FALSE means excluded
nrow = nrow(temp_inclusion_index),
ncol = p)
# Update the non-excluded entries:
inclusion_index[,match(colnames(temp_inclusion_index),
1:p)] = temp_inclusion_index
# And add the variable names:
colnames(inclusion_index) = xnames
# If we have any auto-include, then add those at the top:
if(!is.null(to_include)){
force_in = rep(FALSE, p)
force_in[to_include] = TRUE
inclusion_index = rbind(force_in, inclusion_index)
}
return(inclusion_index)
}
#' Compute the predictive and empirical cross-validated squared error loss
#'
#' Use posterior predictive draws and a sampling-importance resampling (SIR)
#' algorithm to approximate the cross-validated predictive squared error loss.
#' The empirical squared error loss (i.e., the usual quantity in cross-validation)
#' is also returned. The values are computed relative to the "best"
#' subset according to minimum empirical squared error loss.
#' Specifically, these quantities are computed for a collection of
#' linear models that are fit to the Bayesian model output, where
#' each linear model features a different subset of predictors.
#'
#' @param post_y_pred \code{S x n} matrix of posterior predictive draws
#' at the given \code{XX} covariate values
#' @param post_lpd \code{S} evaluations of the log-likelihood computed
#' at each posterior draw of the parameters
#' @param XX \code{n x p} matrix of covariates at which to evaluate
#' @param yy \code{n}-dimensional vector of response variables
#' @param indicators \code{L x p} matrix of inclusion indicators (booleans)
#' where each row denotes a candidate subset
#' @param post_y_hat \code{S x n} matrix of posterior fitted values
#' at the given \code{XX} covariate values
#' @param K number of cross-validation folds
#' @param sir_frac fraction of the posterior samples to use for SIR
#' @return a list with two elements: \code{pred_loss} and \code{emp_loss}
#' for the predictive and empirical loss, respectively, for each subset.
#' @details The quantity \code{post_y_hat} is the conditional expectation of the
#' response for each covariate value (columns) and using the parameters sampled
#' from the posterior (rows). For Bayesian linear regression, this term is
#' \code{X \%*\% beta}. If unspecified, the algorithm will instead use \code{post_y_pred},
#' which is still correct but has lower Monte Carlo efficiency.
#'
#' @export
pp_loss = function(post_y_pred,
post_lpd,
XX,
yy,
indicators,
post_y_hat = NULL,
K = 10,
sir_frac = 0.5
){
# Get dimensions of the covariate matrix:
n = nrow(XX); p = ncol(XX)
# And some other dimensions
S = nrow(post_y_pred) # number of posterior simulations
L = nrow(indicators) # number of subsets to consider
# Some basic checks:
if(length(yy) !=n)
stop('length of yy must equal the number of rows of XX')
if(ncol(post_y_pred) != n)
stop('number of columns of post_y_pred must equal the number of rows of XX')
if(nrow(post_lpd) != S)
stop('post_lpd must have the same number of rows (simulations) as post_y_pred')
if(is.null(post_y_hat)){
post_y_hat = post_y_pred # just use the predictive draws
} else {
# Check:
if(nrow(post_y_hat) != S)
stop('post_y_hat must have the same number of rows (simulations) as post_y_pred')
if(ncol(post_y_hat) != n)
stop('number of columns of post_y_hat must equal the number of rows of XX')
}
if(ncol(indicators) != p)
stop('indicators must have the same number of columns as XX has rows')
# Samples for sampling-importance resampling (SIR):
S_sir = ceiling(S*sir_frac) # should be a small fraction of S
# Indices of the kth *holdout* set, k=1:K
I_k = split(sample(1:n),
1:K)
# For each holdout set, obtain samples from the predictive distribution
# conditional only on the training data; then compare with test data
# and posterior predictive distribution of the test data
pred_loss = array(0, c(S_sir, L))
emp_loss = numeric(L)
for(k in 1:K){
# Log importance weights:
logw_k = -rowSums(as.matrix(post_lpd[,I_k[[k]]]))
logw_k = logw_k - min(logw_k) # useful numerical adjustment
# SIR indices:
samp_inds = sample(1:S,
S_sir,
prob=exp(logw_k),
replace = FALSE)
# Testing (out) and training (in) predictive distributions:
post_Y_out = post_y_pred[samp_inds, I_k[[k]]]
post_Y_in = post_y_pred[samp_inds, -I_k[[k]]]
# Testing quantities of interest:
n_out = length(I_k[[k]]); # number of out-of-sample (testing) points
X_out = matrix(XX[I_k[[k]],], nrow = n_out); # corresponding x-variables
XtX_out = crossprod(X_out) # X'X for these testing points
X_in = XX[-I_k[[k]],] # in-sample x-variables
postY2_out = rowMeans(post_Y_out^2) # squared predictive variables summed across n_out
# Predictive mean (training points):
y_hat_in = colMeans(post_y_hat[samp_inds,
-I_k[[k]]])
# Response variables on the testing data:
yy_out = yy[I_k[[k]]]
# Regression for each model:
beta_path_in = matrix(0, nrow = p, ncol = L)
for(ell in 1:L){
beta_path_in[indicators[ell,], ell] = coef(
lm(y_hat_in ~ X_in[,indicators[ell,]] - 1)
)
}
# Out-of-sample predictive loss:
pred_loss = pred_loss + 1/K*(
apply(beta_path_in, 2, function(beta_ell){
postY2_out +
1/n_out*as.numeric(crossprod(beta_ell, XtX_out)%*%beta_ell) -
2/n_out*tcrossprod(post_Y_out, t(X_out%*%beta_ell))
})
)
# Out-of-sample empirical loss:
emp_loss = emp_loss + 1/K*(
apply(beta_path_in, 2, function(beta_ell){
mean(yy_out^2) +
1/n_out*as.numeric(crossprod(beta_ell, XtX_out)%*%beta_ell) -
2/n_out*crossprod(yy_out, X_out%*%beta_ell)
})
)
}
# Best subset by out-of-sample empirical loss:
ell_ref = which.min(emp_loss)
# Adjust the empirical loss relative to this term:
emp_loss = 100*(emp_loss - emp_loss[ell_ref])/emp_loss[ell_ref]
# Percent difference in predictive loss relative to best model:
pred_loss = apply(pred_loss, 2, function(ploss)
100*(ploss - pred_loss[,ell_ref])/pred_loss[,ell_ref])
return(
list(pred_loss = pred_loss,
emp_loss = emp_loss)
)
}
#' Compute the predictive squared error loss on *new* testing points
#'
#' Use posterior predictive draws at new \code{XX} points, compute
#' the predictive squared error loss. The values are
#' computed relative to the largest subset provided, which is typically
#' the full set of covariates (and also the minimizer of the expected
#' predictive loss). These quantities are computed for a collection of
#' linear models that are fit to the Bayesian model output, where
#' each linear model features a different subset of predictors.
#'
#' @param post_y_pred \code{S x n} matrix of posterior predictive draws
#' at the given \code{XX} covariate values
#' @param XX \code{n x p} matrix of covariates at which to evaluate
#' @param indicators \code{L x p} matrix of inclusion indicators (booleans)
#' where each row denotes a candidate subset
#' @param post_y_hat \code{S x n} matrix of posterior fitted values
#' at the given \code{XX} covariate values
#' @return \code{pred_loss}: the predictive loss for each subset.
#' @details The quantity \code{post_y_hat} is the conditional expectation of the
#' response for each covariate value (columns) and using the parameters sampled
#' from the posterior (rows). For Bayesian linear regression, this term is
#' \code{X \%*\% beta}. If unspecified, the algorithm will instead use \code{post_y_pred},
#' which is still correct but has lower Monte Carlo efficiency.
#'
#' @export
pp_loss_out = function(post_y_pred,
XX,
indicators,
post_y_hat = NULL
){
# Get dimensions of the covariate matrix:
n = nrow(XX); p = ncol(XX)
# And some other dimensions
S = nrow(post_y_pred) # number of posterior simulations
L = nrow(indicators) # number of subsets to consider
if(ncol(post_y_pred) != n)
stop('number of columns of post_y_pred must equal the number of rows of XX')
if(is.null(post_y_hat)){
post_y_hat = post_y_pred # just use the predictive draws
} else {
# Check:
if(nrow(post_y_hat) != S)
stop('post_y_hat must have the same number of rows (simulations) as post_y_pred')
if(ncol(post_y_hat) != n)
stop('number of columns of post_y_hat must equal the number of rows of XX')
}
if(ncol(indicators) != p)
stop('indicators must have the same number of columns as XX has rows')
# Fitted values:
y_hat = colMeans(post_y_hat)
# Useful terms:
XtX = crossprod(XX) # X'X for these testing points
post_y2_pred = rowMeans(post_y_pred^2) # squared predictive variables summed across n_out
# Storage:
pred_loss = array(0, c(S, L))
for(ell in 1:L){
# Coefficients for this model:
beta_ell = rep(0, p)
beta_ell[indicators[ell,]] = coef(lm(y_hat ~ XX[,indicators[ell,]] - 1))
# And predictive loss:
pred_loss[,ell] = post_y2_pred +
1/n*as.numeric(crossprod(beta_ell, XtX)%*%beta_ell) -
2/n*tcrossprod(post_y_pred, t(XX%*%beta_ell))
}
# Reference: largest subset
ell_ref = L
# Percent difference in predictive loss relative to best model:
pred_loss = apply(pred_loss, 2, function(ploss)
100*(ploss - pred_loss[,ell_ref])/pred_loss[,ell_ref])
return(
pred_loss = pred_loss
)
}
#' Compute the predictive and empirical cross-validated loss for binary data.
#'
#' Use posterior predictive draws and a sampling-importance resampling (SIR)
#' algorithm to approximate the cross-validated predictive loss.
#' The empirical loss (i.e., the usual quantity in cross-validation)
#' is also returned. The values are computed relative to the "best"
#' subset according to minimum empirical loss.
#' Specifically, these quantities are computed for a collection of
#' linear models that are fit to the Bayesian model output, where
#' each linear model features a different subset of predictors.
#' The loss function may be chosen as cross-entropy or misclassification rate
#'
#' @param post_y_pred \code{S x n} matrix of posterior predictive draws
#' at the given \code{XX} covariate values
#' @param post_lpd \code{S} evaluations of the log-likelihood computed
#' at each posterior draw of the parameters
#' @param XX \code{n x p} matrix of covariates at which to evaluate
#' @param yy \code{n}-dimensional vector of response variables
#' @param indicators \code{L x p} matrix of inclusion indicators (booleans)
#' where each row denotes a candidate subset
#' @param loss_type loss function to be used:
#' "cross-ent" (cross-entropy) or "misclass" (misclassication rate)
#' @param post_y_hat \code{S x n} matrix of posterior fitted values
#' at the given \code{XX} covariate values
#' @param K number of cross-validation folds
#' @param sir_frac fraction of the posterior samples to use for SIR
#' @return a list with two elements: \code{pred_loss} and \code{emp_loss}
#' for the predictive and empirical loss, respectively, for each subset.
#' @details The quantity \code{post_y_hat} is the conditional expectation of the
#' response for each covariate value (columns) and using the parameters sampled
#' from the posterior (rows). For binary data, this is also the estimated
#' probability of "success".
#' If unspecified, the algorithm will instead use \code{post_y_pred},
#' which is still correct but has lower Monte Carlo efficiency.
#'
#' @importFrom stats glm
#' @export
pp_loss_binary = function(post_y_pred,
post_lpd,
XX,
yy,
indicators,
loss_type = 'cross-ent',
post_y_hat = NULL,
K = 10,
sir_frac = 0.5
){
# Get dimensions of the covariate matrix:
n = nrow(XX); p = ncol(XX)
# And some other dimensions
S = nrow(post_y_pred) # number of posterior simulations
L = nrow(indicators) # number of subsets to consider
# Some basic checks:
if(length(yy) !=n)
stop('length of yy must equal the number of rows of XX')
if(ncol(post_y_pred) != n)
stop('number of columns of post_y_pred must equal the number of rows of XX')
if(nrow(post_lpd) != S)
stop('post_lpd must have the same number of rows (simulations) as post_y_pred')
if(is.null(post_y_hat)){
post_y_hat = post_y_pred # just use the predictive draws
} else {
# Check:
if(nrow(post_y_hat) != S)
stop('post_y_hat must have the same number of rows (simulations) as post_y_pred')
if(ncol(post_y_hat) != n)
stop('number of columns of post_y_hat must equal the number of rows of XX')
}
if(ncol(indicators) != p)
stop('indicators must have the same number of columns as XX has rows')
if(is.na(match(loss_type, c("cross-ent", "misclass"))))
stop('loss_type must be one of "cross-ent" or "misclass"')
# Define the loss function:
# y_obs: observed data in {0,1}
# g_hat: prediction on link scale (R^1), e,g X%*%beta
if(loss_type == "cross-ent"){ # cross-entropy loss
loss_fun = function(y_obs, g_hat)
log(1 + exp(g_hat)) - g_hat*y_obs
}
if(loss_type == "misclass"){ # misclassification rate
loss_fun = function(y_obs, g_hat)
1.0*(y_obs != (g_hat > 0))
}
# Samples for sampling-importance resampling (SIR):
S_sir = ceiling(S*sir_frac) # should be a small fraction of S
# Indices of the kth *holdout* set, k=1:K
I_k = split(sample(1:n),
1:K)
# For each holdout set, obtain samples from the predictive distribution
# conditional only on the training data; then compare with test data
# and posterior predictive distribution of the test data
pred_loss = array(0, c(S_sir, L))
emp_loss = numeric(L)
for(k in 1:K){
# Log importance weights:
logw_k = -rowSums(as.matrix(post_lpd[,I_k[[k]]]))
logw_k = logw_k - min(logw_k) # useful numerical adjustment
# SIR indices:
samp_inds = sample(1:S,
S_sir,
prob=exp(logw_k),
replace = FALSE)
# Testing (out) and training (in) predictive distributions:
post_Y_out = post_y_pred[samp_inds, I_k[[k]]]
post_Y_in = post_y_pred[samp_inds, -I_k[[k]]]
# Testing quantities of interest:
n_out = length(I_k[[k]]); # number of out-of-sample (testing) points
X_out = matrix(XX[I_k[[k]],], nrow = n_out); # corresponding x-variables
X_in = XX[-I_k[[k]],] # in-sample x-variables
# Predictive mean (training points):
y_hat_in = colMeans(post_y_hat[samp_inds,
-I_k[[k]]])
# Response variables on the testing data:
yy_out = yy[I_k[[k]]]
# Regression for each model:
beta_path_in = matrix(0, nrow = p, ncol = L)
for(ell in 1:L){
beta_path_in[indicators[ell,], ell] =
suppressWarnings(
coef(
glm(y_hat_in ~ X_in[,indicators[ell,]] - 1,
family = 'binomial')
)
)
}
# Out-of-sample predictive loss:
pred_loss = pred_loss + 1/K*(
apply(beta_path_in, 2, function(beta_ell){
rowMeans(loss_fun(post_Y_out,
rep(X_out%*%beta_ell, each = S_sir)))
})
)
# Out-of-sample empirical loss:
emp_loss = emp_loss + 1/K*(
apply(beta_path_in, 2, function(beta_ell){
mean(loss_fun(yy_out, X_out%*%beta_ell))
})
)
}
# Best subset by out-of-sample empirical loss:
ell_ref = which.min(emp_loss)
# Adjust the empirical loss relative to this term:
emp_loss = 100*(emp_loss - emp_loss[ell_ref])/emp_loss[ell_ref]
# Percent difference in predictive loss relative to best model:
pred_loss = apply(pred_loss, 2, function(ploss)
100*(ploss - pred_loss[,ell_ref])/pred_loss[,ell_ref])
return(
list(pred_loss = pred_loss,
emp_loss = emp_loss)
)
}
#' Compute the predictive and empirical cross-validated Mahalanobis loss
#' under the random intercept model
#'
#' Use posterior predictive draws and a sampling-importance resampling (SIR)
#' algorithm to approximate the cross-validated predictive Mahalanobis loss.
#' The empirical Mahalanobis loss is also returned. The values are computed relative to the "best"
#' subset according to minimum empirical Mahalanobis loss.
#' Specifically, these quantities are computed for a collection of
#' linear models that are fit to the Bayesian model output, where
#' each linear model features a different subset of predictors.
#'
#' @param post_y_pred \code{S x m x n} matrix of posterior predictive draws
#' at the given \code{XX} covariate values for \code{m} replicates per subject
#' @param post_lpd \code{S} evaluations of the log-likelihood computed
#' at each posterior draw of the parameters
#' @param post_sigma_e (\code{nsave}) draws from the posterior distribution
#' of the observation error SD
#' @param post_sigma_u (\code{nsave}) draws from the posterior distribution
#' of the random intercept SD
#' @param XX \code{n x p} matrix of covariates at which to evaluate
#' @param YY \code{m x n} matrix of response variables (optional)
#' @param indicators \code{L x p} matrix of inclusion indicators (booleans)
#' where each row denotes a candidate subset
#' @param post_y_pred_sum (\code{nsave x n}) matrix of the posterior predictive
#' draws summed over the replicates within each subject (optional)
#' @param K number of cross-validation folds
#' @param sir_frac fraction of the posterior samples to use for SIR
#' @return a list with two elements: \code{pred_loss} and \code{emp_loss}
#' for the predictive and empirical loss, respectively, for each subset.
#'
#' @export
pp_loss_randint = function(post_y_pred,
post_lpd,
post_sigma_e,
post_sigma_u,
XX,
YY,
indicators,
post_y_pred_sum = NULL,
K = 10,
sir_frac = 0.5
){
# Get dimensions of the covariate matrix:
n = nrow(XX); p = ncol(XX)
# And some other dimensions
S = nrow(post_y_pred) # number of posterior simulations
m = dim(post_y_pred)[2] # number of replicates per subject
L = nrow(indicators) # number of subsets to consider
# Some basic checks:
if(!is.null(YY) && ncol(YY) !=n)
stop('the number of columns of YY must equal the number of rows of XX')
if(dim(post_y_pred)[3] != n)
stop('incorrect dimensions for post_y_pred')
if(!is.null(post_lpd) && nrow(post_lpd) != S)
stop('post_lpd must have the same number of rows (simulations) as post_y_pred')
if(ncol(indicators) != p)
stop('indicators must have the same number of columns as XX has rows')
# This can be slow if n is large:
if(is.null(post_y_pred_sum)){
post_y_pred_sum = apply(post_y_pred, c(1,3), sum)
}
# Samples for sampling-importance resampling (SIR):
S_sir = ceiling(S*sir_frac) # should be a small fraction of S
# Indices of the kth *holdout* set, k=1:K
I_k = split(sample(1:n),
1:K)
# For each holdout set, obtain samples from the predictive distribution
# conditional only on the training data; then compare with test data
# and posterior predictive distribution of the test data
pred_loss = array(0, c(S_sir, L))
emp_loss = numeric(L)
for(k in 1:K){
# Log importance weights:
logw_k = -rowSums(as.matrix(post_lpd[,I_k[[k]]]))
logw_k = logw_k - min(logw_k) # useful numerical adjustment
# SIR indices:
samp_inds = sample(1:S,
S_sir,
prob=exp(logw_k),
replace = FALSE)
# Compute the objects needed for in-sample regression:
objXY = getXY_randint(XX = XX[-I_k[[k]], ],
post_y_pred = post_y_pred[samp_inds, ,-I_k[[k]]],
post_sigma_e = post_sigma_e[samp_inds],
post_sigma_u = post_sigma_u[samp_inds],
post_y_pred_sum = post_y_pred_sum[samp_inds, -I_k[[k]]])
X_star_in = objXY$X_star; y_star_in = objXY$y_star; rm(objXY)
# Objects needed for out-of-sample regression:
n_out = length(I_k[[k]])
X_out = matrix(XX[I_k[[k]],], nrow = n_out); # corresponding x-variables
Y_out = matrix(YY[,I_k[[k]]], nrow = m); # corresponding y-variables
post_y_pred_out = post_y_pred[samp_inds, ,I_k[[k]]] # out-of-sample predictive points
# Recurring terms:
Y2_out = sum(Y_out^2, na.rm=TRUE); Y_sum_out = colSums(Y_out, na.rm=TRUE)
post_y_pred_sum_out = post_y_pred_sum[samp_inds, I_k[[k]]] # out-of-sample predictive sum
post_y2_pred_out = rowSums(post_y_pred_out^2)
post_m_scale = 1/(post_sigma_e[samp_inds]^2/post_sigma_u[samp_inds]^2 + m)
m_scale_hat = mean(post_m_scale)
# For each subsets compute (i) the coefficients and (ii) the predictive and empirical losses
for(ell in 1:L){
# Estimate the in-sample coefficients:
beta_ell = rep(0, p)
beta_ell[indicators[ell,]] = coef(
lm(y_star_in ~ X_star_in[,indicators[ell,]] - 1)
)
# Fitted values:
XB_ell = X_out%*%beta_ell
# Compute the *empirical* Mahalanobis loss:
emp_loss[ell] = emp_loss[ell] + 1/K*1/(n_out*m)*(
Y2_out - 2*crossprod(XB_ell, Y_sum_out) + m*sum((XB_ell)^2) -
m_scale_hat*(sum((Y_sum_out - m*XB_ell)^2))
)
# Compare to the full version:
# res = matrix(Y_out - rep(X_out%*%beta_ell, each = m))
# Omega_hat = diag(1, m) - m_scale_hat
# Omega_block_hat = bdiag(lapply(1:n_out, function(i){Omega_hat}))
# t(res)%*%Omega_block_hat%*%res
# Compute the *predictive* Mahalanobis loss:
pred_loss[,ell] = pred_loss[,ell] + 1/K*1/(n_out*m)*(
post_y2_pred_out - 2*tcrossprod(post_y_pred_sum_out, t(XB_ell)) + m*sum((XB_ell)^2) -
post_m_scale*rowSums((post_y_pred_sum_out - rep(m*XB_ell, each = S_sir))^2)
)
}
}
# Under missingness, use predictive expectation:
if(any(is.na(YY))) emp_loss = colMeans(pred_loss)
# Best subset by out-of-sample empirical loss:
ell_ref = which.min(emp_loss)
# Adjust the empirical loss relative to this term:
emp_loss = 100*(emp_loss - emp_loss[ell_ref])/emp_loss[ell_ref]
# Percent difference in predictive loss relative to best model:
pred_loss = apply(pred_loss, 2, function(ploss)
100*(ploss - pred_loss[,ell_ref])/pred_loss[,ell_ref])
return(
list(pred_loss = pred_loss,
emp_loss = emp_loss)
)
}
#' Compute the acceptable family of linear subsets
#'
#' Given output from a Bayesian model and a candidate of
#' subsets, compute the *acceptable family* of subsets that
#' match or nearly match the predictive accuracy of the "best" subset.
#' The acceptable family may be computed for any set of covariate values
#' \code{XX}; if \code{XX = X} are the in-sample points, then
#' cross-validation is used to assess out-of-sample predictive performance.
#'
#' @param post_y_pred \code{S x n} matrix of posterior predictive draws
#' at the given \code{XX} covariate values
#' @param post_lpd \code{S} evaluations of the log-likelihood computed
#' at each posterior draw of the parameters (optional)
#' @param XX \code{n x p} matrix of covariates at which to evaluate
#' @param yy \code{n}-dimensional vector of response variables (optional)
#' @param indicators \code{L x p} matrix of inclusion indicators (booleans)
#' where each row denotes a candidate subset
#' @param eps_level probability required to match the predictive
#' performance of the "best" model (up to \code{eta_level})
#' @param eta_level allowable margin (%) between each acceptable model
#' and the "best" model
#' @param post_y_hat \code{S x n} matrix of posterior fitted values
#' at the given \code{XX} covariate values (optional)
#' @param K number of cross-validation folds (optional)
#' @param sir_frac fraction of the posterior samples to use for SIR (optional)
#' @param plot logical; if TRUE, include a plot to summarize the predictive
#' performance across candidate subsets
#' @return a list containing the following elements:
#' \itemize{
#' \item \code{all_accept}: indices (i.e., rows of \code{indicators})
#' that correspond to the acceptable subsets
#' \item \code{beta_hat_small} linear coefficients for the
#' smallest acceptable model
#' \item \code{beta_hat_min} linear coefficients for the
#' "best" acceptable model
#' \item \code{ell_small}: index (i.e., row of \code{indicators}) of the
#' smallest acceptable model
#' \item \code{ell_min}: index (i.e., row of \code{indicators}) of the
#' "best" acceptable model
#' }
#' @details When \code{XX = X} is the observed covariate values,
#' then \code{post_lpd} and \code{yy} must be provided. These
#' are used to compute the cross-validated predictive and empirical
#' squared errors; the predictive version relies on a sampling importance-resampling
#' procedure.
#'
#' When \code{XX} corresponds to a new set of covariate values, then set \code{post_lpd = NULL}
#' and \code{yy = NULL} (these are the default values).
#'
#' Additional details on the predictive and empirical comparisons are
#' in \code{pp_loss} and \code{pp_loss_out}.
#'
#' @importFrom graphics abline arrows lines
#' @importFrom stats approxfun binomial coef lm quantile runif
#' @export
accept_family = function(post_y_pred,
post_lpd = NULL,
XX,
yy = NULL,
indicators,
eps_level = 0.05,
eta_level = 0.00,
post_y_hat = NULL,
K = 10,
sir_frac = 0.5,
plot = TRUE
){
# Get dimensions of the covariate matrix:
n = nrow(XX); p = ncol(XX)
# And some other dimensions
S = nrow(post_y_pred) # number of posterior simulations
L = nrow(indicators) # number of subsets to consider
# Some basic checks:
if(!is.null(yy) && length(yy) !=n)
stop('length of yy must equal the number of rows of XX')
if(ncol(post_y_pred) != n)
stop('number of columns of post_y_pred must equal the number of rows of XX')
if(!is.null(post_lpd) && nrow(post_lpd) != S)
stop('post_lpd must have the same number of rows (simulations) as post_y_pred')
if(is.null(post_y_hat)){
post_y_hat = post_y_pred # just use the predictive draws
} else {
# Check:
if(nrow(post_y_hat) != S)
stop('post_y_hat must have the same number of rows (simulations) as post_y_pred')
if(ncol(post_y_hat) != n)
stop('number of columns of post_y_hat must equal the number of rows of XX')
}
if(ncol(indicators) != p)
stop('indicators must have the same number of columns as XX has rows')
# Compute the empirical and predictive losses:
if(is.null(post_lpd) && is.null(yy)){
# Totally out-of-sample:
pred_loss = pp_loss_out(post_y_pred = post_y_pred,
XX = XX,
indicators = indicators,
post_y_hat = post_y_hat)
emp_loss = NULL
} else {
# In-sample, so use cross-validation:
pred_emp_loss = pp_loss(post_y_pred = post_y_pred,
post_lpd = post_lpd,
XX = XX,
yy = yy,
indicators = indicators,
post_y_hat = post_y_hat,
K = K,
sir_frac = sir_frac)
# Store these better:
emp_loss = pred_emp_loss$emp_loss
pred_loss = pred_emp_loss$pred_loss
rm(pred_emp_loss)
}
# Indices of acceptable subsets:
all_accept = which(colMeans(pred_loss <= eta_level)
>= eps_level)
# Index of "best" subset, if possible:
if(!is.null(emp_loss)){
ell_min = which.min(emp_loss)
} else ell_min = NULL
# Subset sizes:
subset_size = rowSums(indicators)
# Minimize size of acceptable subset:
min_size_accept = min(subset_size[all_accept])
# Index of acceptable subsets with this size:
ind_min_size_accept = which(subset_size[all_accept] == min_size_accept)
# If more than one, select the minimum empirical loss (or expected predictive loss)
if(length(ind_min_size_accept) > 1){
if(!is.null(emp_loss)){
# use empirical loss, if available
ell_small = all_accept[ind_min_size_accept][which.min(emp_loss[all_accept[ind_min_size_accept]])]
} else {
# otherwise, use expected predictive loss
ell_small = all_accept[ind_min_size_accept][which.min(colMeans(pred_loss)[all_accept[ind_min_size_accept]])]
}
} else ell_small = all_accept[ind_min_size_accept]
if(is.infinite(ell_small)) ell_small = ell_min # in case there is none?
# Compute the coefficients for each index:
# fitted values (pseudo-response)
if(!is.null(post_y_hat)){
y_hat = colMeans(post_y_hat)
} else y_hat = colMeans(post_y_pred)
# coefficients for "best" subset
if(!is.null(ell_min)){
beta_hat_min = numeric(p)
beta_hat_min[indicators[ell_min,]] =
coef(lm(y_hat ~ XX[, indicators[ell_min,]] - 1))
} else beta_hat_min = NULL
# coefficients for smallest acceptable subset:
beta_hat_small = numeric(p)
beta_hat_small[indicators[ell_small,]] =
coef(lm(y_hat ~ XX[, indicators[ell_small,]] - 1))
# Now add the plot, if desired:
if(plot){
# 100(1 - 2*eps_level)% prediction interval for the loss
pi_loss = t(apply(pred_loss, 2,
quantile, c(eps_level, 1 - eps_level)))
jitter = runif(L, min = -0.25, max = 0.25)
plot(subset_size + jitter,
colMeans(pred_loss), type='p', ylim = range(pi_loss, 0), lwd=4,
xlab = 'Subset Size',
ylab = 'Difference in loss (%)',
main = paste('Difference in ',K,'-fold loss (%)', sep=''))
abline(v = 1:p, col='gray')
abline(h = eta_level, lwd=2, lty=6)
abline(v = (subset_size + jitter)[ell_small], lwd=5, col='darkgray')
if(!is.null(ell_min)) abline(v = (subset_size + jitter)[ell_min], lwd=3, col='lightgray', lty=3)
arrows(jitter + subset_size, pi_loss[,1],
jitter + subset_size, pi_loss[,2],
length=0.05, angle=90, code=3, lwd=4)
if(!is.null(emp_loss)) lines(subset_size + jitter, emp_loss, type='p', lwd=4, col='gray', pch=4, cex = 1.5)
}
return(
list(
all_accept = all_accept,
beta_hat_small = beta_hat_small,
beta_hat_min = beta_hat_min,
ell_small = ell_small,
ell_min = ell_min
)
)
}
#' Compute the acceptable family for binary data
#'
#' Given output from a Bayesian model and a candidate of
#' subsets, compute the *acceptable family* of subsets that
#' match or nearly match the predictive accuracy of the "best" subset.
#' This function applies for binary data, such as logistic regression.
#'
#' @param post_y_pred \code{S x n} matrix of posterior predictive draws
#' at the given \code{XX} covariate values
#' @param post_lpd \code{S} evaluations of the log-likelihood computed
#' at each posterior draw of the parameters
#' @param XX \code{n x p} matrix of covariates at which to evaluate
#' @param indicators \code{L x p} matrix of inclusion indicators (booleans)
#' where each row denotes a candidate subset
#' @param eps_level probability required to match the predictive
#' performance of the "best" model (up to \code{eta_level})
#' @param eta_level allowable margin (%) between each acceptable model
#' and the "best" model
#' @param loss_type loss function to be used:
#' "cross-ent" (cross-entropy) or "misclass" (misclassication rate)
#' @param yy \code{n}-dimensional vector of response variables
#' @param post_y_hat \code{S x n} matrix of posterior fitted values
#' at the given \code{XX} covariate values (optional)
#' @param K number of cross-validation folds
#' @param sir_frac fraction of the posterior samples to use for SIR
#' @param plot logical; if TRUE, include a plot to summarize the predictive
#' performance across candidate subsets
#' @return a list containing the following elements:
#' \itemize{
#' \item \code{all_accept}: indices (i.e., rows of \code{indicators})
#' that correspond to the acceptable subsets
#' \item \code{beta_hat_small} linear coefficients for the
#' smallest acceptable model
#' \item \code{beta_hat_min} linear coefficients for the
#' "best" acceptable model
#' \item \code{ell_small}: index (i.e., row of \code{indicators}) of the
#' smallest acceptable model
#' \item \code{ell_min}: index (i.e., row of \code{indicators}) of the
#' "best" acceptable model
#' }
#' @details see \code{pp_loss_binary} for additional details
#' about the predictive and empirical comparisons.
#'
#' @export
accept_family_binary = function(post_y_pred,
post_lpd,
XX,
indicators,
eps_level = 0.05,
eta_level = 0.00,
loss_type = "cross-ent",
yy = NULL,
post_y_hat = NULL,
K = 10,
sir_frac = 0.5,
plot = TRUE
){
# Get dimensions of the covariate matrix:
n = nrow(XX); p = ncol(XX)
# And some other dimensions
S = nrow(post_y_pred) # number of posterior simulations
L = nrow(indicators) # number of subsets to consider
# Some basic checks:
if(length(yy) !=n)
stop('length of yy must equal the number of rows of XX')
if(ncol(post_y_pred) != n)
stop('number of columns of post_y_pred must equal the number of rows of XX')
if(nrow(post_lpd) != S)
stop('post_lpd must have the same number of rows (simulations) as post_y_pred')
if(is.null(post_y_hat)){
post_y_hat = post_y_pred # just use the predictive draws
} else {
# Check:
if(nrow(post_y_hat) != S)
stop('post_y_hat must have the same number of rows (simulations) as post_y_pred')
if(ncol(post_y_hat) != n)
stop('number of columns of post_y_hat must equal the number of rows of XX')
}
if(ncol(indicators) != p)
stop('indicators must have the same number of columns as XX has rows')
# Check the loss types:
if(is.na(match(loss_type, c("cross-ent", "misclass"))))
stop('loss_type must be one of "cross-ent" or "misclass"')
# Compute the empirical and predictive losses:
pred_emp_loss = pp_loss_binary(post_y_pred = post_y_pred,
post_lpd = post_lpd,
XX = XX,
yy = yy,
indicators = indicators,
loss_type = loss_type,
post_y_hat = post_y_hat,
K = K,
sir_frac = sir_frac)
# Store these better:
emp_loss = pred_emp_loss$emp_loss
pred_loss = pred_emp_loss$pred_loss
rm(pred_emp_loss)
# Indices of acceptable subsets: