-
-
Notifications
You must be signed in to change notification settings - Fork 190
/
Copy pathposterior_epred.R
805 lines (738 loc) · 26.6 KB
/
posterior_epred.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
#' Expected Values of the Posterior Predictive Distribution
#'
#' Compute posterior samples of the expected value/mean of the posterior
#' predictive distribution. Can be performed for the data used to fit the model
#' (posterior predictive checks) or for new data. By definition, these
#' predictions have smaller variance than the posterior predictions performed by
#' the \code{\link{posterior_predict.brmsfit}} method. This is because only the
#' uncertainty in the mean is incorporated in the samples computed by
#' \code{posterior_epred} while any residual error is ignored. However, the
#' estimated means of both methods averaged across samples should be very
#' similar.
#'
#' @aliases pp_expect
#'
#' @inheritParams posterior_predict.brmsfit
#' @param dpar Optional name of a predicted distributional parameter.
#' If specified, expected predictions of this parameters are returned.
#' @param nlpar Optional name of a predicted non-linear parameter.
#' If specified, expected predictions of this parameters are returned.
#'
#' @return An \code{array} of predicted \emph{mean} response values. For
#' categorical and ordinal models, the output is an S x N x C array.
#' Otherwise, the output is an S x N matrix, where S is the number of
#' posterior samples, N is the number of observations, and C is the number of
#' categories. In multivariate models, an additional dimension is added to the
#' output which indexes along the different response variables.
#'
#' @template details-newdata-na
#' @template details-allow_new_levels
#'
#' @examples
#' \dontrun{
#' ## fit a model
#' fit <- brm(rating ~ treat + period + carry + (1|subject),
#' data = inhaler)
#'
#' ## compute expected predictions
#' ppe <- posterior_epred(fit)
#' str(ppe)
#' }
#'
#' @aliases posterior_epred
#' @method posterior_epred brmsfit
#' @importFrom rstantools posterior_epred
#' @export posterior_epred
#' @export
posterior_epred.brmsfit <- function(object, newdata = NULL, re_formula = NULL,
re.form = NULL, resp = NULL, dpar = NULL,
nlpar = NULL, nsamples = NULL, subset = NULL,
sort = FALSE, ...) {
cl <- match.call()
if ("re.form" %in% names(cl)) {
re_formula <- re.form
}
contains_samples(object)
object <- restructure(object)
prep <- prepare_predictions(
object, newdata = newdata, re_formula = re_formula, resp = resp,
nsamples = nsamples, subset = subset, check_response = FALSE, ...
)
posterior_epred(
prep, scale = "response", dpar = dpar,
nlpar = nlpar, sort = sort, summary = FALSE
)
}
#' @export
posterior_epred.mvbrmsprep <- function(object, ...) {
out <- lapply(object$resps, posterior_epred, ...)
along <- ifelse(length(out) > 1L, 3, 2)
do_call(abind, c(out, along = along))
}
#' @export
posterior_epred.brmsprep <- function(object, scale, dpar, nlpar, sort,
summary, robust, probs, ...) {
dpars <- names(object$dpars)
nlpars <- names(object$nlpars)
if (length(dpar)) {
# predict a distributional parameter
dpar <- as_one_character(dpar)
if (!dpar %in% dpars) {
stop2("Invalid argument 'dpar'. Valid distributional ",
"parameters are: ", collapse_comma(dpars))
}
if (length(nlpar)) {
stop2("Cannot use 'dpar' and 'nlpar' at the same time.")
}
predicted <- is.bprepl(object$dpars[[dpar]]) ||
is.bprepnl(object$dpars[[dpar]])
if (predicted) {
# parameter varies across observations
if (scale == "linear") {
object$dpars[[dpar]]$family$link <- "identity"
}
if (is_ordinal(object$family)) {
object$dpars[[dpar]]$cs <- NULL
object$family <- object$dpars[[dpar]]$family <-
.dpar_family(link = object$dpars[[dpar]]$family$link)
}
if (dpar_class(dpar) == "theta" && scale == "response") {
ap_id <- as.numeric(dpar_id(dpar))
out <- get_theta(object)[, , ap_id, drop = FALSE]
dim(out) <- dim(out)[c(1, 2)]
} else {
out <- get_dpar(object, dpar = dpar, ilink = TRUE)
}
} else {
# parameter is constant across observations
out <- object$dpars[[dpar]]
out <- matrix(out, nrow = object$nsamples, ncol = object$nobs)
}
} else if (length(nlpar)) {
# predict a non-linear parameter
nlpar <- as_one_character(nlpar)
if (!nlpar %in% nlpars) {
stop2("Invalid argument 'nlpar'. Valid non-linear ",
"parameters are: ", collapse_comma(nlpars))
}
out <- get_nlpar(object, nlpar = nlpar)
} else {
# predict the mean of the response distribution
if (scale == "response") {
for (nlp in nlpars) {
object$nlpars[[nlp]] <- get_nlpar(object, nlpar = nlp)
}
for (dp in dpars) {
object$dpars[[dp]] <- get_dpar(object, dpar = dp)
}
if (is_trunc(object)) {
out <- posterior_epred_trunc(object)
} else {
posterior_epred_fun <- paste0("posterior_epred_", object$family$family)
posterior_epred_fun <- get(posterior_epred_fun, asNamespace("brms"))
out <- posterior_epred_fun(object)
}
} else {
if (conv_cats_dpars(object$family)) {
mus <- dpars[grepl("^mu", dpars)]
} else {
mus <- dpars[dpar_class(dpars) %in% "mu"]
}
if (length(mus) == 1L) {
out <- get_dpar(object, dpar = mus, ilink = FALSE)
} else {
# multiple mu parameters in categorical or mixture models
out <- lapply(mus, get_dpar, prep = object, ilink = FALSE)
out <- abind::abind(out, along = 3)
}
}
}
if (is.null(dim(out))) {
out <- as.matrix(out)
}
colnames(out) <- NULL
out <- reorder_obs(out, object$old_order, sort = sort)
if (summary) {
# only for compatibility with the 'fitted' method
out <- posterior_summary(out, probs = probs, robust = robust)
if (has_cat(object$family) && length(dim(out)) == 3L) {
if (scale == "linear") {
dimnames(out)[[3]] <- paste0("eta", seq_dim(out, 3))
} else {
dimnames(out)[[3]] <- paste0("P(Y = ", dimnames(out)[[3]], ")")
}
}
}
out
}
#' Expected Values of the Posterior Predictive Distribution
#'
#' This method is an alias of \code{\link{posterior_epred.brmsfit}}
#' with additional arguments for obtaining summaries of the computed samples.
#'
#' @inheritParams posterior_epred.brmsfit
#' @param object An object of class \code{brmsfit}.
#' @param scale Either \code{"response"} or \code{"linear"}.
#' If \code{"response"}, results are returned on the scale
#' of the response variable. If \code{"linear"},
#' results are returned on the scale of the linear predictor term,
#' that is without applying the inverse link function or
#' other transformations.
#' @param summary Should summary statistics be returned
#' instead of the raw values? Default is \code{TRUE}..
#' @param robust If \code{FALSE} (the default) the mean is used as
#' the measure of central tendency and the standard deviation as
#' the measure of variability. If \code{TRUE}, the median and the
#' median absolute deviation (MAD) are applied instead.
#' Only used if \code{summary} is \code{TRUE}.
#' @param probs The percentiles to be computed by the \code{quantile}
#' function. Only used if \code{summary} is \code{TRUE}.
#'
#' @return An \code{array} of predicted \emph{mean} response values.
#' If \code{summary = FALSE} the output resembles those of
#' \code{\link{posterior_epred.brmsfit}}.
#'
#' If \code{summary = TRUE} the output depends on the family: For categorical
#' and ordinal families, the output is an N x E x C array, where N is the
#' number of observations, E is the number of summary statistics, and C is the
#' number of categories. For all other families, the output is an N x E
#' matrix. The number of summary statistics E is equal to \code{2 +
#' length(probs)}: The \code{Estimate} column contains point estimates (either
#' mean or median depending on argument \code{robust}), while the
#' \code{Est.Error} column contains uncertainty estimates (either standard
#' deviation or median absolute deviation depending on argument
#' \code{robust}). The remaining columns starting with \code{Q} contain
#' quantile estimates as specified via argument \code{probs}.
#'
#' In multivariate models, an additional dimension is added to the output
#' which indexes along the different response variables.
#'
#' @seealso \code{\link{posterior_epred.brmsfit}}
#'
#' @examples
#' \dontrun{
#' ## fit a model
#' fit <- brm(rating ~ treat + period + carry + (1|subject),
#' data = inhaler)
#'
#' ## compute expected predictions
#' fitted_values <- fitted(fit)
#' head(fitted_values)
#'
#' ## plot expected predictions against actual response
#' dat <- as.data.frame(cbind(Y = standata(fit)$Y, fitted_values))
#' ggplot(dat) + geom_point(aes(x = Estimate, y = Y))
#' }
#'
#' @export
fitted.brmsfit <- function(object, newdata = NULL, re_formula = NULL,
scale = c("response", "linear"),
resp = NULL, dpar = NULL, nlpar = NULL,
nsamples = NULL, subset = NULL, sort = FALSE,
summary = TRUE, robust = FALSE,
probs = c(0.025, 0.975), ...) {
scale <- match.arg(scale)
summary <- as_one_logical(summary)
contains_samples(object)
object <- restructure(object)
prep <- prepare_predictions(
object, newdata = newdata, re_formula = re_formula, resp = resp,
nsamples = nsamples, subset = subset, check_response = FALSE, ...
)
posterior_epred(
prep, scale = scale, dpar = dpar, nlpar = nlpar, sort = sort,
summary = summary, robust = robust, probs = probs
)
}
#' Posterior Samples of the Linear Predictor
#'
#' Compute posterior samples of the linear predictor, that is samples before
#' applying any link functions or other transformations. Can be performed for
#' the data used to fit the model (posterior predictive checks) or for new data.
#'
#' @inheritParams posterior_epred.brmsfit
#' @param object An object of class \code{brmsfit}.
#' @param transform (Deprecated) Logical; if \code{FALSE}
#' (the default), samples of the linear predictor are returned.
#' If \code{TRUE}, samples of transformed linear predictor,
#' that is, the mean of the posterior predictive distribution
#' are returned instead (see \code{\link{posterior_epred}} for details).
#' Only implemented for compatibility with the
#' \code{\link[rstantools:posterior_linpred]{posterior_linpred}}
#' generic.
#'
#' @seealso \code{\link{posterior_epred.brmsfit}}
#'
#' @examples
#' \dontrun{
#' ## fit a model
#' fit <- brm(rating ~ treat + period + carry + (1|subject),
#' data = inhaler)
#'
#' ## extract linear predictor values
#' pl <- posterior_linpred(fit)
#' str(pl)
#' }
#'
#' @aliases posterior_linpred
#' @method posterior_linpred brmsfit
#' @importFrom rstantools posterior_linpred
#' @export
#' @export posterior_linpred
posterior_linpred.brmsfit <- function(
object, transform = FALSE, newdata = NULL, re_formula = NULL,
re.form = NULL, resp = NULL, dpar = NULL, nlpar = NULL,
nsamples = NULL, subset = NULL, sort = FALSE, ...
) {
cl <- match.call()
if ("re.form" %in% names(cl)) {
re_formula <- re.form
}
scale <- "linear"
transform <- as_one_logical(transform)
if (transform) {
warning2("posterior_linpred(transform = TRUE) is deprecated. Please ",
"use posterior_epred() instead, without the 'transform' argument.")
scale <- "response"
}
contains_samples(object)
object <- restructure(object)
prep <- prepare_predictions(
object, newdata = newdata, re_formula = re_formula, resp = resp,
nsamples = nsamples, subset = subset, check_response = FALSE, ...
)
posterior_epred(
prep, scale = scale, dpar = dpar,
nlpar = nlpar, sort = sort, summary = FALSE
)
}
# ------------------- family specific posterior_epred methods ---------------------
# All posterior_epred_<family> functions have the same arguments structure
# @param prep A named list returned by prepare_predictions containing
# all required data and draws
# @return transformed linear predictor representing the mean
# of the posterior predictive distribution
posterior_epred_gaussian <- function(prep) {
if (!is.null(prep$ac$lagsar)) {
prep$dpars$mu <- posterior_epred_lagsar(prep)
}
prep$dpars$mu
}
posterior_epred_student <- function(prep) {
if (!is.null(prep$ac$lagsar)) {
prep$dpars$mu <- posterior_epred_lagsar(prep)
}
prep$dpars$mu
}
posterior_epred_skew_normal <- function(prep) {
prep$dpars$mu
}
posterior_epred_lognormal <- function(prep) {
with(prep$dpars, exp(mu + sigma^2 / 2))
}
posterior_epred_shifted_lognormal <- function(prep) {
with(prep$dpars, exp(mu + sigma^2 / 2) + ndt)
}
posterior_epred_binomial <- function(prep) {
trials <- as_draws_matrix(prep$data$trials, dim_mu(prep))
prep$dpars$mu * trials
}
posterior_epred_bernoulli <- function(prep) {
prep$dpars$mu
}
posterior_epred_poisson <- function(prep) {
multiply_dpar_rate_denom(prep$dpars$mu, prep)
}
posterior_epred_negbinomial <- function(prep) {
multiply_dpar_rate_denom(prep$dpars$mu, prep)
}
posterior_epred_negbinomial2 <- function(prep) {
multiply_dpar_rate_denom(prep$dpars$mu, prep)
}
posterior_epred_geometric <- function(prep) {
multiply_dpar_rate_denom(prep$dpars$mu, prep)
}
posterior_epred_discrete_weibull <- function(prep) {
mean_discrete_weibull(prep$dpars$mu, prep$dpars$shape)
}
posterior_epred_com_poisson <- function(prep) {
mean_com_poisson(prep$dpars$mu, prep$dpars$shape)
}
posterior_epred_exponential <- function(prep) {
prep$dpars$mu
}
posterior_epred_gamma <- function(prep) {
prep$dpars$mu
}
posterior_epred_weibull <- function(prep) {
prep$dpars$mu
}
posterior_epred_frechet <- function(prep) {
prep$dpars$mu
}
posterior_epred_gen_extreme_value <- function(prep) {
with(prep$dpars, mu + sigma * (gamma(1 - xi) - 1) / xi)
}
posterior_epred_inverse.gaussian <- function(prep) {
prep$dpars$mu
}
posterior_epred_exgaussian <- function(prep) {
prep$dpars$mu
}
posterior_epred_wiener <- function(prep) {
# mu is the drift rate
with(prep$dpars,
ndt - bias / mu + bs / mu *
(exp(-2 * mu * bias) - 1) / (exp(-2 * mu * bs) - 1)
)
}
posterior_epred_beta <- function(prep) {
prep$dpars$mu
}
posterior_epred_von_mises <- function(prep) {
prep$dpars$mu
}
posterior_epred_asym_laplace <- function(prep) {
with(prep$dpars,
mu + sigma * (1 - 2 * quantile) / (quantile * (1 - quantile))
)
}
posterior_epred_zero_inflated_asym_laplace <- function(prep) {
posterior_epred_asym_laplace(prep) * (1 - prep$dpars$zi)
}
posterior_epred_cox <- function(prep) {
stop2("Cannot compute expected values of the posterior predictive ",
"distribution for family 'cox'.")
}
posterior_epred_hurdle_poisson <- function(prep) {
with(prep$dpars, mu / (1 - exp(-mu)) * (1 - hu))
}
posterior_epred_hurdle_negbinomial <- function(prep) {
with(prep$dpars, mu / (1 - (shape / (mu + shape))^shape) * (1 - hu))
}
posterior_epred_hurdle_gamma <- function(prep) {
with(prep$dpars, mu * (1 - hu))
}
posterior_epred_hurdle_lognormal <- function(prep) {
with(prep$dpars, exp(mu + sigma^2 / 2) * (1 - hu))
}
posterior_epred_zero_inflated_poisson <- function(prep) {
with(prep$dpars, mu * (1 - zi))
}
posterior_epred_zero_inflated_negbinomial <- function(prep) {
with(prep$dpars, mu * (1 - zi))
}
posterior_epred_zero_inflated_binomial <- function(prep) {
trials <- as_draws_matrix(prep$data$trials, dim_mu(prep))
prep$dpars$mu * trials * (1 - prep$dpars$zi)
}
posterior_epred_zero_inflated_beta <- function(prep) {
with(prep$dpars, mu * (1 - zi))
}
posterior_epred_zero_one_inflated_beta <- function(prep) {
with(prep$dpars, zoi * coi + mu * (1 - zoi))
}
posterior_epred_categorical <- function(prep) {
get_probs <- function(i) {
eta <- insert_refcat(extract_col(eta, i), family = prep$family)
dcategorical(cats, eta = eta)
}
eta <- abind(prep$dpars, along = 3)
cats <- seq_len(prep$data$ncat)
out <- abind(lapply(seq_cols(eta), get_probs), along = 3)
out <- aperm(out, perm = c(1, 3, 2))
dimnames(out)[[3]] <- prep$cats
out
}
posterior_epred_multinomial <- function(prep) {
get_counts <- function(i) {
eta <- insert_refcat(extract_col(eta, i), family = prep$family)
dcategorical(cats, eta = eta) * trials[i]
}
eta <- abind(prep$dpars, along = 3)
cats <- seq_len(prep$data$ncat)
trials <- prep$data$trials
out <- abind(lapply(seq_cols(eta), get_counts), along = 3)
out <- aperm(out, perm = c(1, 3, 2))
dimnames(out)[[3]] <- prep$cats
out
}
posterior_epred_dirichlet <- function(prep) {
get_probs <- function(i) {
eta <- insert_refcat(extract_col(eta, i), family = prep$family)
dcategorical(cats, eta = eta)
}
eta <- prep$dpars[grepl("^mu", names(prep$dpars))]
eta <- abind(eta, along = 3)
cats <- seq_len(prep$data$ncat)
out <- abind(lapply(seq_cols(eta), get_probs), along = 3)
out <- aperm(out, perm = c(1, 3, 2))
dimnames(out)[[3]] <- prep$cats
out
}
posterior_epred_cumulative <- function(prep) {
posterior_epred_ordinal(prep)
}
posterior_epred_sratio <- function(prep) {
posterior_epred_ordinal(prep)
}
posterior_epred_cratio <- function(prep) {
posterior_epred_ordinal(prep)
}
posterior_epred_acat <- function(prep) {
posterior_epred_ordinal(prep)
}
posterior_epred_custom <- function(prep) {
posterior_epred_fun <- prep$family$posterior_epred
if (!is.function(posterior_epred_fun)) {
posterior_epred_fun <- paste0("posterior_epred_", prep$family$name)
posterior_epred_fun <- get(posterior_epred_fun, prep$family$env)
}
posterior_epred_fun(prep)
}
posterior_epred_mixture <- function(prep) {
families <- family_names(prep$family)
prep$dpars$theta <- get_theta(prep)
out <- 0
for (j in seq_along(families)) {
posterior_epred_fun <- paste0("posterior_epred_", families[j])
posterior_epred_fun <- get(posterior_epred_fun, asNamespace("brms"))
tmp_prep <- pseudo_prep_for_mixture(prep, j)
if (length(dim(prep$dpars$theta)) == 3L) {
theta <- prep$dpars$theta[, , j]
} else {
theta <- prep$dpars$theta[, j]
}
out <- out + theta * posterior_epred_fun(tmp_prep)
}
out
}
# ------ posterior_epred helper functions ------
# compute 'posterior_epred' for ordinal models
posterior_epred_ordinal <- function(prep) {
dens <- get(paste0("d", prep$family$family), mode = "function")
ncat_max <- max(prep$data$nthres) + 1
nact_min <- min(prep$data$nthres) + 1
zero_mat <- matrix(0, nrow = prep$nsamples, ncol = ncat_max - nact_min)
args <- list(link = prep$family$link)
out <- vector("list", prep$nobs)
for (i in seq_along(out)) {
args_i <- args
args_i$eta <- extract_col(prep$dpars$mu, i)
args_i$disc <- extract_col(prep$dpars$disc, i)
args_i$thres <- subset_thres(prep, i)
ncat_i <- NCOL(args_i$thres) + 1
args_i$x <- seq_len(ncat_i)
out[[i]] <- do_call(dens, args_i)
if (ncat_i < ncat_max) {
sel <- seq_len(ncat_max - ncat_i)
out[[i]] <- cbind(out[[i]], zero_mat[, sel])
}
}
out <- abind(out, along = 3)
out <- aperm(out, perm = c(1, 3, 2))
dimnames(out)[[3]] <- seq_len(ncat_max)
out
}
# compute 'posterior_epred' for lagsar models
posterior_epred_lagsar <- function(prep) {
stopifnot(!is.null(prep$ac$lagsar))
I <- diag(prep$nobs)
.posterior_epred <- function(s) {
IB <- I - with(prep$ac, lagsar[s, ] * Msar)
as.numeric(solve(IB, prep$dpars$mu[s, ]))
}
out <- rblapply(seq_len(prep$nsamples), .posterior_epred)
rownames(out) <- NULL
out
}
# expand data to dimension appropriate for
# vectorized multiplication with posterior samples
as_draws_matrix <- function(x, dim) {
stopifnot(length(dim) == 2L, length(x) %in% c(1, dim[2]))
matrix(x, nrow = dim[1], ncol = dim[2], byrow = TRUE)
}
# expected dimension of the main parameter 'mu'
dim_mu <- function(prep) {
c(prep$nsamples, prep$nobs)
}
# is the model truncated?
is_trunc <- function(prep) {
stopifnot(is.brmsprep(prep))
any(prep$data[["lb"]] > -Inf) || any(prep$data[["ub"]] < Inf)
}
# prepares data required for truncation and calles the
# family specific truncation function for posterior_epred values
posterior_epred_trunc <- function(prep) {
stopifnot(is_trunc(prep))
lb <- as_draws_matrix(prep$data[["lb"]], dim_mu(prep))
ub <- as_draws_matrix(prep$data[["ub"]], dim_mu(prep))
posterior_epred_trunc_fun <- paste0("posterior_epred_trunc_", prep$family$family)
posterior_epred_trunc_fun <- try(
get(posterior_epred_trunc_fun, asNamespace("brms")),
silent = TRUE
)
if (is(posterior_epred_trunc_fun, "try-error")) {
stop2("posterior_epred values on the respone scale not yet implemented ",
"for truncated '", prep$family$family, "' models.")
}
trunc_args <- nlist(prep, lb, ub)
do_call(posterior_epred_trunc_fun, trunc_args)
}
# ----- family specific truncation functions -----
# @param prep output of 'prepare_predictions'
# @param lb lower truncation bound
# @param ub upper truncation bound
# @return samples of the truncated mean parameter
posterior_epred_trunc_gaussian <- function(prep, lb, ub) {
zlb <- (lb - prep$dpars$mu) / prep$dpars$sigma
zub <- (ub - prep$dpars$mu) / prep$dpars$sigma
# truncated mean of standard normal; see Wikipedia
trunc_zmean <- (dnorm(zlb) - dnorm(zub)) / (pnorm(zub) - pnorm(zlb))
prep$dpars$mu + trunc_zmean * prep$dpars$sigma
}
posterior_epred_trunc_student <- function(prep, lb, ub) {
zlb <- with(prep$dpars, (lb - mu) / sigma)
zub <- with(prep$dpars, (ub - mu) / sigma)
nu <- prep$dpars$nu
# see Kim 2008: Moments of truncated Student-t distribution
G1 <- gamma((nu - 1) / 2) * nu^(nu / 2) /
(2 * (pt(zub, df = nu) - pt(zlb, df = nu))
* gamma(nu / 2) * gamma(0.5))
A <- (nu + zlb^2) ^ (-(nu - 1) / 2)
B <- (nu + zub^2) ^ (-(nu - 1) / 2)
trunc_zmean <- G1 * (A - B)
prep$dpars$mu + trunc_zmean * prep$dpars$sigma
}
posterior_epred_trunc_lognormal <- function(prep, lb, ub) {
lb <- ifelse(lb < 0, 0, lb)
m1 <- with(prep$dpars,
exp(mu + sigma^2 / 2) *
(pnorm((log(ub) - mu) / sigma - sigma) -
pnorm((log(lb) - mu) / sigma - sigma))
)
with(prep$dpars,
m1 / (plnorm(ub, meanlog = mu, sdlog = sigma) -
plnorm(lb, meanlog = mu, sdlog = sigma))
)
}
posterior_epred_trunc_gamma <- function(prep, lb, ub) {
lb <- ifelse(lb < 0, 0, lb)
prep$dpars$scale <- prep$dpars$mu / prep$dpars$shape
# see Jawitz 2004: Moments of truncated continuous univariate distributions
m1 <- with(prep$dpars,
scale / gamma(shape) *
(incgamma(1 + shape, ub / scale) -
incgamma(1 + shape, lb / scale))
)
with(prep$dpars,
m1 / (pgamma(ub, shape, scale = scale) -
pgamma(lb, shape, scale = scale))
)
}
posterior_epred_trunc_exponential <- function(prep, lb, ub) {
lb <- ifelse(lb < 0, 0, lb)
inv_mu <- 1 / prep$dpars$mu
# see Jawitz 2004: Moments of truncated continuous univariate distributions
m1 <- with(prep$dpars, mu * (incgamma(2, ub / mu) - incgamma(2, lb / mu)))
m1 / (pexp(ub, rate = inv_mu) - pexp(lb, rate = inv_mu))
}
posterior_epred_trunc_weibull <- function(prep, lb, ub) {
lb <- ifelse(lb < 0, 0, lb)
prep$dpars$a <- 1 + 1 / prep$dpars$shape
prep$dpars$scale <- with(prep$dpars, mu / gamma(a))
# see Jawitz 2004: Moments of truncated continuous univariate distributions
m1 <- with(prep$dpars,
scale * (incgamma(a, (ub / scale)^shape) -
incgamma(a, (lb / scale)^shape))
)
with(prep$dpars,
m1 / (pweibull(ub, shape, scale = scale) -
pweibull(lb, shape, scale = scale))
)
}
posterior_epred_trunc_binomial <- function(prep, lb, ub) {
lb <- ifelse(lb < -1, -1, lb)
max_value <- max(prep$data$trials)
ub <- ifelse(ub > max_value, max_value, ub)
trials <- prep$data$trials
if (length(trials) > 1) {
trials <- as_draws_matrix(trials, dim_mu(prep))
}
args <- list(size = trials, prob = prep$dpars$mu)
posterior_epred_trunc_discrete(dist = "binom", args = args, lb = lb, ub = ub)
}
posterior_epred_trunc_poisson <- function(prep, lb, ub) {
lb <- ifelse(lb < -1, -1, lb)
mu <- multiply_dpar_rate_denom(prep$dpars$mu, prep)
max_value <- 3 * max(mu)
ub <- ifelse(ub > max_value, max_value, ub)
args <- list(lambda = mu)
posterior_epred_trunc_discrete(dist = "pois", args = args, lb = lb, ub = ub)
}
posterior_epred_trunc_negbinomial <- function(prep, lb, ub) {
lb <- ifelse(lb < -1, -1, lb)
mu <- multiply_dpar_rate_denom(prep$dpars$mu, prep)
max_value <- 3 * max(mu)
ub <- ifelse(ub > max_value, max_value, ub)
shape <- multiply_dpar_rate_denom(prep$dpars$shape, prep)
args <- list(mu = mu, size = shape)
posterior_epred_trunc_discrete(dist = "nbinom", args = args, lb = lb, ub = ub)
}
posterior_epred_trunc_negbinomial2 <- function(prep, lb, ub) {
lb <- ifelse(lb < -1, -1, lb)
mu <- multiply_dpar_rate_denom(prep$dpars$mu, prep)
max_value <- 3 * max(mu)
ub <- ifelse(ub > max_value, max_value, ub)
shape <- multiply_dpar_rate_denom(1 / prep$dpars$sigma, prep)
args <- list(mu = mu, size = shape)
posterior_epred_trunc_discrete(dist = "nbinom", args = args, lb = lb, ub = ub)
}
posterior_epred_trunc_geometric <- function(prep, lb, ub) {
lb <- ifelse(lb < -1, -1, lb)
mu <- multiply_dpar_rate_denom(prep$dpars$mu, prep)
max_value <- 3 * max(mu)
ub <- ifelse(ub > max_value, max_value, ub)
shape <- multiply_dpar_rate_denom(1, prep, i = i)
args <- list(mu = mu, size = shape)
posterior_epred_trunc_discrete(dist = "nbinom", args = args, lb = lb, ub = ub)
}
# posterior_epred values for truncated discrete distributions
posterior_epred_trunc_discrete <- function(dist, args, lb, ub) {
stopifnot(is.matrix(lb), is.matrix(ub))
message(
"Computing posterior_epred values for truncated ",
"discrete models may take a while."
)
pdf <- get(paste0("d", dist), mode = "function")
cdf <- get(paste0("p", dist), mode = "function")
mean_kernel <- function(x, args) {
# just x * density(x)
x * do_call(pdf, c(x, args))
}
if (any(is.infinite(c(lb, ub)))) {
stop("lb and ub must be finite")
}
# simplify lb and ub back to vector format
vec_lb <- lb[1, ]
vec_ub <- ub[1, ]
min_lb <- min(vec_lb)
# array of dimension S x N x length((lb+1):ub)
mk <- lapply((min_lb + 1):max(vec_ub), mean_kernel, args = args)
mk <- do_call(abind, c(mk, along = 3))
m1 <- vector("list", ncol(mk))
for (n in seq_along(m1)) {
# summarize only over non-truncated values for this observation
J <- (vec_lb[n] - min_lb + 1):(vec_ub[n] - min_lb)
m1[[n]] <- rowSums(mk[, n, ][, J, drop = FALSE])
}
rm(mk)
m1 <- do.call(cbind, m1)
m1 / (do.call(cdf, c(list(ub), args)) - do.call(cdf, c(list(lb), args)))
}
#' @export
pp_expect <- function(object, ...) {
warning2("Method 'pp_expect' is deprecated. ",
"Please use 'posterior_epred' instead.")
UseMethod("posterior_epred")
}