Bayesian Model Averaging with BIC Weights

Quick Overview

Implement Bayesian model averaging in NumPy: posterior model weights from BIC values or validation log-likelihoods, a weighted ensemble prediction, and a split of predictive variance into aleatoric and epistemic parts. Tests numerical stability with very large BIC values, input validation, and judgment about when BMA weights help.

Bayesian Model Averaging with BIC Weights

Role: Machine Learning Engineer

Category: Machine Learning

Difficulty: hard

Interview Round: Other

Bayesian model averaging (BMA) combines M candidate models by weighting each one with its posterior probability. Implement six functions that compute posterior model weights from BIC values or validation log-likelihoods, combine the members' predictions with those weights, decompose the BMA predictive variance, and compare BMA with an equal-weight average. ```python def gaussian_bic(y, y_pred, n_params): ... def bic_weights(bic, prior=None): ... def loglik_weights(loglik, prior=None): ... def bma_average(preds, weights): ... def bma_moments(means, variances, weights): ... def compare_to_equal(preds, y, weights): ... ``` Requirements: - `gaussian_bic` returns the float $n \ln(\text{RSS}/n) + k \ln n$, where n is the number of targets, RSS is the residual sum of squares and k is `n_params`. - `bic_weights` returns weights proportional to `prior * exp(-BIC / 2)`, and `loglik_weights` returns weights proportional to `prior * exp(loglik)`. Both sum to 1 and stay finite for very large inputs, such as BIC values around 1e6. With `prior=None` they use a uniform prior, and a given prior is normalized first. - `bma_average(preds, weights)` takes `preds` of shape `(M, ...)`, normalizes the weights, and returns the weighted sum over the first axis, with shape `preds.shape[1:]`. - `bma_moments(means, variances, weights)` returns `(mean, aleatoric, epistemic, total)` with mean $\bar\mu = \sum_i w_i \mu_i$, aleatoric $\sum_i w_i \sigma_i^2$, epistemic $\sum_i w_i (\mu_i - \bar\mu)^2$, and total equal to aleatoric plus epistemic. - `compare_to_equal(preds, y, weights)` returns `{"bma_mse": ..., "equal_mse": ..., "improvement": ...}` with `improvement = equal_mse - bma_mse`. The equal-weight average is the plain mean of the members. - Raise `ValueError` for negative, zero-sum or mis-shaped weights or priors, and for negative variances. Example: ```python bic_weights([100.0, 102.0, 104.0]) # proportional to [1, e^-1, e^-2] -> [0.6652, 0.2447, 0.0900] preds = [[1, 2, 3], [3, 2, 1]] y = [1, 2, 3] compare_to_equal(preds, y, [3.0, 1.0]) # {'bma_mse': 0.1667, 'equal_mse': 0.6667, 'improvement': 0.5} ``` Outputs are rounded to four decimals. In the second call the weights normalize to 0.75 and 0.25. ```hint Numerical stability For BIC values near 1e6, `exp(-BIC / 2)` is 0.0 in floating point for every model. Look for a constant you can subtract inside every exponent without changing the normalized weights. ``` ```hint One helper for both weight functions Write BIC weights and log-likelihood weights as the same computation on log evidence plus log prior. Then the prior handling and the stability fix live in one place. ``` ```hint Trailing shapes `preds` and `means` can have any shape after the model axis. Check what `w @ x` does when `x` is 3-D before relying on it. ``` ### Constraints & Assumptions - M is the number of candidate models. Weights, priors, BIC values and log-likelihoods are 1-D with one entry per model. - `preds`, `means` and `variances` have a leading model axis of length M and any trailing shape. - Inputs can be as large as BIC values around 1e6. Logarithms are natural. - Every model's BIC or log-likelihood is computed on the same targets. ### What a Strong Answer Covers - A max-shifted computation of the posterior weights that stays finite for BIC values near 1e6 and folds in a normalized or uniform prior. - One shared posterior routine for BIC and log-likelihood weights, with the correct sign and the factor of one half on BIC. - Weighted averages and moments that work for any trailing prediction shape, and a clear account of the aleatoric and epistemic terms. - Validation that raises `ValueError` for negative, zero-sum, non-finite or mis-shaped weights and priors and for negative variances. - A correct MSE comparison against the equal-weight average, and an understanding of when that comparison is optimistic. ### Follow-up Questions - Why can BMA weights collapse onto a single model, and is that desirable? - When would you prefer validation log-likelihood weights over BIC weights? - How would you use the epistemic term from `bma_moments` in practice?

Overview: Implement Bayesian model averaging in NumPy: posterior model weights from BIC values or validation log-likelihoods, a weighted ensemble prediction, and a split of predictive variance into aleatoric and epistemic parts. Tests numerical stability with very large BIC values, input validation, and judgment about when BMA weights help.

PracHub logo
General
Nov 25, 2026
hardMachine Learning EngineerOtherMachine Learning
0
0

Bayesian model averaging (BMA) combines M candidate models by weighting each one with its posterior probability. Implement six functions that compute posterior model weights from BIC values or validation log-likelihoods, combine the members' predictions with those weights, decompose the BMA predictive variance, and compare BMA with an equal-weight average.

def gaussian_bic(y, y_pred, n_params): ...
def bic_weights(bic, prior=None): ...
def loglik_weights(loglik, prior=None): ...
def bma_average(preds, weights): ...
def bma_moments(means, variances, weights): ...
def compare_to_equal(preds, y, weights): ...

Requirements:

  • gaussian_bic returns the float nln⁡(RSS/n)+kln⁡nn \ln(\text{RSS}/n) + k \ln n , where n is the number of targets, RSS is the residual sum of squares and k is n_params .
  • bic_weights returns weights proportional to prior * exp(-BIC / 2) , and loglik_weights returns weights proportional to prior * exp(loglik) . Both sum to 1 and stay finite for very large inputs, such as BIC values around 1e6. With prior=None they use a uniform prior, and a given prior is normalized first.
  • bma_average(preds, weights) takes preds of shape (M, ...) , normalizes the weights, and returns the weighted sum over the first axis, with shape preds.shape[1:] .
  • bma_moments(means, variances, weights) returns (mean, aleatoric, epistemic, total) with mean μˉ=∑iwiμi\bar\mu = \sum_i w_i \mu_i , aleatoric ∑iwiσi2\sum_i w_i \sigma_i^2 , epistemic ∑iwi(μi−μˉ)2\sum_i w_i (\mu_i - \bar\mu)^2 , and total equal to aleatoric plus epistemic.
  • compare_to_equal(preds, y, weights) returns {"bma_mse": ..., "equal_mse": ..., "improvement": ...} with improvement = equal_mse - bma_mse . The equal-weight average is the plain mean of the members.
  • Raise ValueError for negative, zero-sum or mis-shaped weights or priors, and for negative variances.

Example:

bic_weights([100.0, 102.0, 104.0])
# proportional to [1, e^-1, e^-2] -> [0.6652, 0.2447, 0.0900]

preds = [[1, 2, 3], [3, 2, 1]]
y = [1, 2, 3]
compare_to_equal(preds, y, [3.0, 1.0])
# {'bma_mse': 0.1667, 'equal_mse': 0.6667, 'improvement': 0.5}

Outputs are rounded to four decimals. In the second call the weights normalize to 0.75 and 0.25.

Constraints & Assumptions

  • M is the number of candidate models. Weights, priors, BIC values and log-likelihoods are 1-D with one entry per model.
  • preds , means and variances have a leading model axis of length M and any trailing shape.
  • Inputs can be as large as BIC values around 1e6. Logarithms are natural.
  • Every model's BIC or log-likelihood is computed on the same targets.

What a Strong Answer Covers Guidance

  • A max-shifted computation of the posterior weights that stays finite for BIC values near 1e6 and folds in a normalized or uniform prior.
  • One shared posterior routine for BIC and log-likelihood weights, with the correct sign and the factor of one half on BIC.
  • Weighted averages and moments that work for any trailing prediction shape, and a clear account of the aleatoric and epistemic terms.
  • Validation that raises ValueError for negative, zero-sum, non-finite or mis-shaped weights and priors and for negative variances.
  • A correct MSE comparison against the equal-weight average, and an understanding of when that comparison is optimistic.

Follow-up Questions Guidance

  • Why can BMA weights collapse onto a single model, and is that desirable?
  • When would you prefer validation log-likelihood weights over BIC weights?
  • How would you use the epistemic term from bma_moments in practice?