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
|
# Family-specific helper functions
#
# `extend_family(family)` returns a `family` object augmented with auxiliary
# functions that are needed for computing KL-divergence, log predictive density,
# dispersion projection, etc.
#
# Missing: Quasi-families are not implemented. If dis_gamma is the correct shape
# parameter for projected Gamma regression, everything should be OK for gamma.
#' Extend a family
#'
#' This function adds some internally required elements to an object of class
#' `family` (see, e.g., [family()]). It is called internally by
#' [init_refmodel()], so you will rarely need to call it yourself.
#'
#' @param family An object of class `family`.
#'
#' @return The `family` object extended in the way needed by \pkg{projpred}.
#'
#' @export
extend_family <- function(family) {
if (.has_family_extras(family)) {
# If the family was already extended using this function, then return as-is:
return(family)
}
extend_family_specific <- paste0("extend_family_", tolower(family$family))
if (!exists(extend_family_specific, mode = "function")) {
stop("Family '", family$family, "' is not supported by projpred.")
}
extend_family_specific <- get(extend_family_specific, mode = "function")
family <- extend_family_specific(family)
family$is_extended <- TRUE
return(family)
}
extend_family_binomial <- function(family) {
# Helper function for calculating the log PMF of the binomial distribution,
# but (i) modified to be non-zero at `x` not contained in the support and (ii)
# "reduced" in the sense of lacking the (additive) part
# `log(choose(size, size * x))`:
dbinom_log_reduced <- function(x, size, prob) {
size * (x * log(prob) + (1 - x) * log(1 - prob))
}
ce_binom <- function(pref, data, psub) {
ce_sums <- -colSums(
dbinom_log_reduced(x = pref$mu, size = data$weights, prob = psub$mu)
)
return(ce_sums / sum(data$weights))
}
dis_na <- function(pref, psub, wobs = 1) {
rep(NA, ncol(pref$mu))
}
predvar_na <- function(mu, dis, wsample = 1) {
rep(NA, NROW(mu))
}
ll_binom <- function(mu, dis, y, weights = 1) {
y <- as.matrix(y)
dbinom(y, weights, mu, log = TRUE)
}
dev_binom <- function(mu, y, weights = 1, dis = NULL) {
if (NCOL(y) < NCOL(mu)) {
y <- matrix(y, nrow = length(y), ncol = NCOL(mu))
}
-2 * dbinom_log_reduced(x = y, size = weights, prob = mu)
}
ppd_binom <- function(mu, dis, weights = 1) {
rbinom(length(mu), weights, mu)
}
initialize_binom <- expression({
if (NCOL(y) == 1) {
if (is.factor(y)) {
y <- y != levels(y)[1L]
}
n <- rep.int(1, nobs)
y[weights == 0] <- 0
if (any(y < 0 | y > 1)) {
stop("y values must be 0 <= y <= 1")
}
mustart <- (weights * y + 0.5) / (weights + 1)
m <- weights * y
if ("binomial" == "binomial" && any(abs(m - round(m)) >
0.001)) {
### Deactivated because in general, this will be the case in 'projpred':
# warning(gettextf("non-integer #successes in a %s glm!",
# "binomial"), domain = NA)
###
}
}
else if (NCOL(y) == 2) {
if ("binomial" == "binomial" && any(abs(y - round(y)) >
0.001)) {
warning(gettextf("non-integer counts in a %s glm!",
"binomial"), domain = NA)
}
n <- (y1 <- y[, 1L]) + y[, 2L]
y <- y1 / n
if (any(n0 <- n == 0)) {
y[n0] <- 0
}
weights <- weights * n
mustart <- (n * y + 0.5) / (n + 1)
} else {
stop(gettextf(paste("for the '%s' family, y must be a vector of 0 and",
"1's\nor a 2 column matrix where col 1 is no.",
"successes and col 2 is no. failures"),
"binomial"), domain = NA)
}
})
family$initialize <- initialize_binom
family$ce <- ce_binom
family$dis_fun <- dis_na
family$predvar <- predvar_na
family$ll_fun <- ll_binom
family$deviance <- dev_binom
family$ppd <- ppd_binom
return(family)
}
extend_family_poisson <- function(family) {
# Helper function for calculating the log PMF of the Poisson distribution,
# but (i) modified to be non-zero at `x` not contained in the support and (ii)
# "reduced" in the sense of lacking the (additive) part
# `- wobs * log(factorial(x))`:
dpois_log_reduced <- function(x, lamb, wobs) {
wobs * (x * log(lamb) - lamb)
}
ce_poiss <- function(pref, data, psub) {
ce_sums <- -colSums(
dpois_log_reduced(x = pref$mu, lamb = psub$mu, wobs = data$weights)
)
return(ce_sums / sum(data$weights))
}
dis_na <- function(pref, psub, wobs = 1) {
rep(NA, ncol(pref$mu))
}
predvar_na <- function(mu, dis, wsample = 1) {
rep(NA, NROW(mu))
}
ll_poiss <- function(mu, dis, y, weights = 1) {
y <- as.matrix(y)
weights * dpois(y, mu, log = TRUE)
}
dev_poiss <- function(mu, y, weights = 1, dis = NULL) {
if (NCOL(y) < NCOL(mu)) {
y <- matrix(y, nrow = length(y), ncol = NCOL(mu))
}
-2 * dpois_log_reduced(x = y, lamb = mu, wobs = weights)
}
ppd_poiss <- function(mu, dis, weights = 1) {
rpois(length(mu), mu)
}
family$ce <- ce_poiss
family$dis_fun <- dis_na
family$predvar <- predvar_na
family$ll_fun <- ll_poiss
family$deviance <- dev_poiss
family$ppd <- ppd_poiss
return(family)
}
extend_family_gaussian <- function(family) {
# ce_gauss() does not give the actual cross-entropy (not even the one which
# would result from dropping terms which would cancel out when calculating the
# KL divergence) but a reasonable surrogate. This additional approximation was
# already made back when this used to be the KL divergence, not the
# cross-entropy.
ce_gauss <- function(pref, data, psub) {
ce_sums <- colSums(data$weights * (-2 * pref$mu * psub$mu + psub$mu^2))
return(ce_sums / sum(data$weights))
}
dis_gauss <- function(pref, psub, wobs = 1) {
sqrt(colSums(wobs / sum(wobs) * (pref$var + (pref$mu - psub$mu)^2)))
}
predvar_gauss <- function(mu, dis, wsample = 1) {
wsample <- wsample / sum(wsample)
mu_mean <- mu %*% wsample
mu_var <- mu^2 %*% wsample - mu_mean^2
as.vector(sum(wsample * dis^2) + mu_var)
}
ll_gauss <- function(mu, dis, y, weights = 1) {
y <- as.matrix(y)
dis <- matrix(rep(dis, each = length(y)), ncol = NCOL(mu))
weights * dnorm(y, mu, dis, log = TRUE)
}
dev_gauss <- function(mu, y, weights = 1, dis = NULL) {
if (is.null(dis)) {
dis <- 1
} else {
dis <- matrix(rep(dis, each = length(y)), ncol = NCOL(mu))
}
if (NCOL(y) < NCOL(mu)) {
y <- matrix(y, nrow = length(y), ncol = NCOL(mu))
}
-2 * weights * (-0.5 / dis^2 * (y - mu)^2 - log(dis))
}
ppd_gauss <- function(mu, dis, weights = 1) {
rnorm(length(mu), mu, dis)
}
family$ce <- ce_gauss
family$dis_fun <- dis_gauss
family$predvar <- predvar_gauss
family$ll_fun <- ll_gauss
family$deviance <- dev_gauss
family$ppd <- ppd_gauss
return(family)
}
extend_family_gamma <- function(family) {
ce_gamma <- function(pref, data, psub) {
stop("Cross-entropy for the Gamma() family not implemented yet.")
### TODO (Gamma()): This commented code stems from a time when this was
### still the actual KL divergence and not the (possibly reduced)
### cross-entropy ("possibly reduced" means: possibly reduced to only those
### terms which would not cancel out when calculating the KL divergence):
## mean(data$weights*(
## p_sub$dis*(log(pref$dis)-log(p_sub$dis)+log(psub$mu)-log(pref$mu)) +
## digamma(pref$dis)*(pref$dis - p_sub$dis) - lgamma(pref$dis) +
## lgamma(p_sub$dis) + pref$mu*p_sub$dis/p_sub$mu - pref$dis))
###
}
dis_gamma <- function(pref, psub, wobs = 1) {
## TODO (Gamma()), IMPLEMENT THIS
stop("Projection of dispersion parameter not yet implemented for family",
" Gamma.")
## mean(wobs*((pref$mu - p_sub$mu)/
## family$mu.eta(family$linkfun(p_sub$mu))^2))
}
predvar_gamma <- function(mu, dis, wsample = 1) {
stop("Family Gamma not implemented yet.")
}
ll_gamma <- function(mu, dis, y, weights = 1) {
y <- as.matrix(y)
dis <- matrix(rep(dis, each = length(y)), ncol = NCOL(mu))
weights * dgamma(y, dis, dis / matrix(mu), log = TRUE)
}
dev_gamma <- function(mu, dis, y, weights = 1) {
stop("Loss function not implemented for Gamma-family yet.")
## dis <- matrix(rep(dis, each=length(y)), ncol=NCOL(mu))
## weights*dgamma(y, dis, dis/matrix(mu), log= TRUE)
}
ppd_gamma <- function(mu, dis, weights = 1) {
rgamma(length(mu), dis, dis / mu)
}
family$ce <- ce_gamma
family$dis_fun <- dis_gamma
family$predvar <- predvar_gamma
family$ll_fun <- ll_gamma
family$deviance <- dev_gamma
family$ppd <- ppd_gamma
return(family)
}
extend_family_student_t <- function(family) {
ce_student_t <- function(pref, data, psub) {
stop("Cross-entropy for the Student_t() family not implemented yet.")
### TODO (Student_t()): This commented code stems from a time when this was
### still the actual KL divergence and not the (possibly reduced)
### cross-entropy ("possibly reduced" means: possibly reduced to only those
### terms which would not cancel out when calculating the KL divergence):
# log(psub$dis)
##- 0.5*log(pref$var) # FIX THIS, NOT CORRECT
###
}
dis_student_t <- function(pref, psub, wobs = 1) {
s2 <- colSums(psub$w / sum(wobs) *
(pref$var + (pref$mu - psub$mu)^2)) # CHECK THIS
sqrt(s2)
## stop('Projection of dispersion not yet implemented for student-t')
}
predvar_student_t <- function(mu, dis, wsample = 1) {
wsample <- wsample / sum(wsample)
mu_mean <- mu %*% wsample
mu_var <- mu^2 %*% wsample - mu_mean^2
as.vector(family$nu / (family$nu - 2) * sum(wsample * dis^2) + mu_var)
}
ll_student_t <- function(mu, dis, y, weights = 1) {
y <- as.matrix(y)
dis <- matrix(rep(dis, each = length(y)), ncol = NCOL(mu))
weights * (dt((y - mu) / dis, family$nu, log = TRUE) - log(dis))
}
dev_student_t <- function(mu, y, weights = 1, dis = NULL) {
if (is.null(dis)) {
dis <- 1
} else {
dis <- matrix(rep(dis, each = length(y)), ncol = NCOL(mu))
}
if (NCOL(y) < NCOL(mu)) {
y <- matrix(y, nrow = length(y), ncol = NCOL(mu))
}
(-2 * weights * (-0.5 * (family$nu + 1)
* log(1 + 1 / family$nu * ((y - mu) / dis)^2) - log(dis)))
}
ppd_student_t <- function(mu, dis, weights = 1) {
rt(length(mu), family$nu) * dis + mu
}
family$ce <- ce_student_t
family$dis_fun <- dis_student_t
family$predvar <- predvar_student_t
family$ll_fun <- ll_student_t
family$deviance <- dev_student_t
family$ppd <- ppd_student_t
return(family)
}
.has_dispersion <- function(family) {
# a function for checking whether the family has a dispersion parameter
family$family %in% c("gaussian", "Student_t", "Gamma")
}
# A function for checking whether a `family` object has the required extra
# functions, that is, whether it has already been extended (typically by a call
# to extend_family()):
.has_family_extras <- function(family) {
return(isTRUE(family$is_extended))
}
|