|
| 1 | +import numpy as np |
| 2 | +from keras import ops |
| 3 | +from typing import Sequence, Any, Mapping |
| 4 | + |
| 5 | +from ...utils.exceptions import ShapeError |
| 6 | +from sklearn.calibration import calibration_curve |
| 7 | + |
| 8 | + |
| 9 | +def expected_calibration_error( |
| 10 | + estimates: np.ndarray, |
| 11 | + targets: np.ndarray, |
| 12 | + model_names: Sequence[str] = None, |
| 13 | + n_bins: int = 10, |
| 14 | + return_probs: bool = False, |
| 15 | +) -> Mapping[str, Any]: |
| 16 | + """Estimates the expected calibration error (ECE) of a model comparison network according to [1]. |
| 17 | +
|
| 18 | + [1] Naeini, M. P., Cooper, G., & Hauskrecht, M. (2015). |
| 19 | + Obtaining well calibrated probabilities using bayesian binning. |
| 20 | + In Proceedings of the AAAI conference on artificial intelligence (Vol. 29, No. 1). |
| 21 | +
|
| 22 | + Notes |
| 23 | + ----- |
| 24 | + Make sure that ``targets`` are **one-hot encoded** classes! |
| 25 | +
|
| 26 | + Parameters |
| 27 | + ---------- |
| 28 | + estimates : array of shape (num_sim, num_models) |
| 29 | + The predicted posterior model probabilities. |
| 30 | + targets : array of shape (num_sim, num_models) |
| 31 | + The one-hot-encoded true model indices. |
| 32 | + model_names : Sequence[str], optional (default = None) |
| 33 | + Optional model names to show in the output. By default, models are called "M_" + model index. |
| 34 | + n_bins : int, optional, default: 10 |
| 35 | + The number of bins to use for the calibration curves (and marginal histograms). |
| 36 | + Passed into ``sklearn.calibration.calibration_curve()``. |
| 37 | + return_probs : bool (default = False) |
| 38 | + Do you want to obtain the output of ``sklearn.calibration.calibration_curve()``? |
| 39 | +
|
| 40 | + Returns |
| 41 | + ------- |
| 42 | + result : dict |
| 43 | + Dictionary containing: |
| 44 | + - "values" : float or np.ndarray |
| 45 | + The expected calibration error per model |
| 46 | + - "metric_name" : str |
| 47 | + The name of the metric ("Expected Calibration Error"). |
| 48 | + - "model_names" : str |
| 49 | + The (inferred) variable names. |
| 50 | + - "probs_true": (optional) list: |
| 51 | + Outputs of ``sklearn.calibration.calibration_curve()`` per model |
| 52 | + - "probs_pred": (optional) list: |
| 53 | + Outputs of ``sklearn.calibration.calibration_curve()`` per model |
| 54 | + """ |
| 55 | + |
| 56 | + # Convert tensors to numpy, if passed |
| 57 | + estimates = ops.convert_to_numpy(estimates) |
| 58 | + targets = ops.convert_to_numpy(targets) |
| 59 | + |
| 60 | + if estimates.shape != targets.shape: |
| 61 | + raise ShapeError("`estimates` and `targets` must have the same shape.") |
| 62 | + |
| 63 | + if model_names is None: |
| 64 | + model_names = ["M_" + str(i) for i in range(estimates.shape[-1])] |
| 65 | + elif len(model_names) != estimates.shape[-1]: |
| 66 | + raise ShapeError("There must be exactly one `model_name` for each model in `estimates`") |
| 67 | + |
| 68 | + # Extract number of models and prepare containers |
| 69 | + ece = [] |
| 70 | + probs_true = [] |
| 71 | + probs_pred = [] |
| 72 | + |
| 73 | + targets = targets.argmax(axis=-1) |
| 74 | + |
| 75 | + # Loop for each model and compute calibration errs per bin |
| 76 | + for model_index in range(estimates.shape[-1]): |
| 77 | + y_true = (targets == model_index).astype(np.float32) |
| 78 | + y_prob = estimates[..., model_index] |
| 79 | + prob_true, prob_pred = calibration_curve(y_true, y_prob, n_bins=n_bins) |
| 80 | + |
| 81 | + # Compute ECE by weighting bin errors by bin size |
| 82 | + bins = np.linspace(0.0, 1.0, n_bins + 1) |
| 83 | + binids = np.searchsorted(bins[1:-1], y_prob) |
| 84 | + bin_total = np.bincount(binids, minlength=len(bins)) |
| 85 | + nonzero = bin_total != 0 |
| 86 | + error = np.sum(np.abs(prob_true - prob_pred) * (bin_total[nonzero] / len(y_true))) |
| 87 | + |
| 88 | + ece.append(error) |
| 89 | + probs_true.append(prob_true) |
| 90 | + probs_pred.append(prob_pred) |
| 91 | + |
| 92 | + output = dict(values=ece, metric_name="Expected Calibration Error", model_names=model_names) |
| 93 | + |
| 94 | + if return_probs: |
| 95 | + output["probs_true"] = probs_true |
| 96 | + output["probs_pred"] = probs_pred |
| 97 | + |
| 98 | + return output |
0 commit comments