Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Model-averaged estimates/intervals/distributions #771

Draft
wants to merge 6 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions NAMESPACE
Original file line number Diff line number Diff line change
Expand Up @@ -860,6 +860,7 @@ S3method(visualisation_recipe,n_clusters_dbscan)
S3method(visualisation_recipe,n_clusters_elbow)
S3method(visualisation_recipe,n_clusters_gap)
S3method(visualisation_recipe,n_clusters_silhouette)
export(averaged_parameters)
export(bootstrap_model)
export(bootstrap_parameters)
export(ci)
Expand Down
55 changes: 55 additions & 0 deletions R/averaged_parameters.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
#' @export
averaged_parameters <- function(..., ci = .95, verbose = TRUE) {
insight::check_if_installed("performance")
models <- list(...)

# compute model weights
aic_values <- sapply(models, performance::performance_aic)
delta_aic <- aic_values - min(aic_values)
model_weights <- exp(-0.5 * delta_aic) / sum(exp(-0.5 * delta_aic))

# residual df's
residual_dfs <- sapply(models, degrees_of_freedom, method = "residual")

# data grid for average predictions
predictions <- lapply(models, function(m) {
d <- insight::get_datagrid(m)
new_data <- as.data.frame(lapply(d, function(i) {
if (is.factor(i)) {
as.factor(levels(i)[1])
} else if (is.numeric(i)) {
mean(i, na.rm = TRUE)
} else {
unique(i)[1]
}
}))
insight::get_predicted(m, data = new_data, ci = .95, predict = "link")
})

theta_hats <- unlist(predictions)
se_theta_hats <- sapply(predictions, function(p) {
attributes(p)$ci_data$SE
})

alpha <- (1 - ci) / 2

CI_low <- stats::uniroot(
f = .tailarea, interval = c(-1e+10, 1e+10), theta_hats = theta_hats,
se_theta_hats = se_theta_hats, model_weights = model_weights, alpha = alpha,
residual_dfs = residual_dfs, tol = 1e-10
)$root

CI_high <- stats::uniroot(
f = .tailarea, interval = c(-1e+10, 1e+10), theta_hats = theta_hats,
se_theta_hats = se_theta_hats, model_weights = model_weights, alpha = 1 - alpha,
residual_dfs = residual_dfs, tol = 1e-10
)$root

c(CI_low, CI_high)
}


.tailarea <- function(theta, theta_hats, se_theta_hats, model_weights, alpha, residual_dfs) {
t_quantiles <- (theta - theta_hats) / se_theta_hats
sum(model_weights * stats::pt(t_quantiles, df = residual_dfs)) - alpha
}