|
| 1 | +""" |
| 2 | +=========================================================== |
| 3 | +Estimating prediction intervals of Gamma distributed target |
| 4 | +=========================================================== |
| 5 | +This example uses :class:`mapie.regression.MapieRegressor` to estimate |
| 6 | +prediction intervals associated with Gamma distributed target. |
| 7 | +The limit of the absolute residual conformity score is illustrated. |
| 8 | +
|
| 9 | +We use here the OpenML house_prices dataset: |
| 10 | +https://www.openml.org/search?type=data&sort=runs&id=42165&status=active. |
| 11 | +
|
| 12 | +The data is modelled by a Random Forest model |
| 13 | +:class:`sklearn.ensemble.RandomForestRegressor` with a fixed parameter set. |
| 14 | +The prediction intervals are determined by means of the MAPIE regressor |
| 15 | +:class:`mapie.regression.MapieRegressor` considering two conformity scores: |
| 16 | +:class:`mapie.conformity_scores.AbsoluteConformityScore` which |
| 17 | +considers the absolute residuals as the conformity scores and |
| 18 | +:class:`mapie.conformity_scores.GammaConformityScore` which |
| 19 | +considers the residuals divided by the predicted means as conformity scores. |
| 20 | +We consider the standard CV+ resampling method. |
| 21 | +
|
| 22 | +We would like to emphasize one main limitation with this example. |
| 23 | +With the default conformity score, the prediction intervals |
| 24 | +are approximately equal over the range of house prices which may |
| 25 | +be inapporpriate when the price range is wide. The Gamma conformity score |
| 26 | +overcomes this issue by considering prediction intervals with width |
| 27 | +proportional to the predicted mean. For low prices, the Gamma prediction |
| 28 | +intervals are narrower than the default ones, conversely to high prices |
| 29 | +for which the conficence intervals are higher but visually more relevant. |
| 30 | +The empirical coverage is similar between the two conformity scores. |
| 31 | +""" |
| 32 | +import matplotlib.pyplot as plt |
| 33 | +import numpy as np |
| 34 | + |
| 35 | +from sklearn.datasets import fetch_openml |
| 36 | +from sklearn.ensemble import RandomForestRegressor |
| 37 | +from sklearn.model_selection import train_test_split |
| 38 | + |
| 39 | +from mapie.conformity_scores import GammaConformityScore |
| 40 | +from mapie.metrics import regression_coverage_score |
| 41 | +from mapie.regression import MapieRegressor |
| 42 | + |
| 43 | +np.random.seed(0) |
| 44 | + |
| 45 | +# Parameters |
| 46 | +features = [ |
| 47 | + "MSSubClass", |
| 48 | + "LotArea", |
| 49 | + "OverallQual", |
| 50 | + "OverallCond", |
| 51 | + "GarageArea", |
| 52 | +] |
| 53 | +alpha = 0.05 |
| 54 | +rf_kwargs = {"n_estimators": 10, "random_state": 0} |
| 55 | +model = RandomForestRegressor(**rf_kwargs) |
| 56 | + |
| 57 | +############################################################################## |
| 58 | +# 1. Load dataset with a target following approximativeley a Gamma distribution |
| 59 | +# ----------------------------------------------------------------------------- |
| 60 | +# |
| 61 | +# We start by loading a dataset with a target following approximately |
| 62 | +# a Gamma distribution. The GammaConformityScore is relevant in such cases. |
| 63 | +# Two sub datasets are extracted: the training and test ones. |
| 64 | + |
| 65 | +X, y = fetch_openml(name="house_prices", return_X_y=True) |
| 66 | + |
| 67 | +X_train, X_test, y_train, y_test = train_test_split( |
| 68 | + X[features], y, test_size=0.2 |
| 69 | +) |
| 70 | + |
| 71 | +############################################################################## |
| 72 | +# 2. Train model with two conformity scores |
| 73 | +# ----------------------------------------- |
| 74 | +# |
| 75 | +# Two models are trained with two different conformity score: |
| 76 | +# |
| 77 | +# - :class:mapie.conformity_scores.AbsoluteConformityScore (default conformity |
| 78 | +# score) relevant for target positive as well as negative. |
| 79 | +# The prediction interval widths are, in this case, approximately the same |
| 80 | +# over the range of prediction. |
| 81 | +# |
| 82 | +# - :class:mapie.conformity_scores.GammaConformityScore relevant for target |
| 83 | +# following roughly a Gamma distribution. The prediction interval widths |
| 84 | +# scale with the predicted value. |
| 85 | + |
| 86 | +############################################################################## |
| 87 | +# First, train model with |
| 88 | +# :class:mapie.conformity_scores.AbsoluteConformityScore. |
| 89 | +mapie = MapieRegressor(model) |
| 90 | +mapie.fit(X_train, y_train) |
| 91 | +y_pred_absconfscore, y_pis_absconfscore = mapie.predict(X_test, alpha=alpha) |
| 92 | + |
| 93 | +coverage_absconfscore = regression_coverage_score( |
| 94 | + y_test, y_pis_absconfscore[:, 0, 0], y_pis_absconfscore[:, 1, 0] |
| 95 | +) |
| 96 | + |
| 97 | +############################################################################## |
| 98 | +# Prepare the results for matplotlib. Get the prediction intervals and their |
| 99 | +# corresponding widths. |
| 100 | + |
| 101 | + |
| 102 | +def get_yerr(y_pred, y_pis): |
| 103 | + return np.concatenate( |
| 104 | + [ |
| 105 | + np.expand_dims(y_pred, 0) - y_pis[:, 0, 0].T, |
| 106 | + y_pis[:, 1, 0].T - np.expand_dims(y_pred, 0), |
| 107 | + ], |
| 108 | + axis=0, |
| 109 | + ) |
| 110 | + |
| 111 | + |
| 112 | +yerr_absconfscore = get_yerr(y_pred_absconfscore, y_pis_absconfscore) |
| 113 | +pred_int_width_absconfscore = ( |
| 114 | + y_pis_absconfscore[:, 1, 0] - y_pis_absconfscore[:, 0, 0] |
| 115 | +) |
| 116 | + |
| 117 | +############################################################################## |
| 118 | +# Then, train the model with |
| 119 | +# :class:mapie.conformity_scores.GammaConformityScore. |
| 120 | +mapie = MapieRegressor(model, conformity_score=GammaConformityScore()) |
| 121 | +mapie.fit(X_train, y_train) |
| 122 | +y_pred_gammaconfscore, y_pis_gammaconfscore = mapie.predict( |
| 123 | + X_test, alpha=[alpha] |
| 124 | +) |
| 125 | + |
| 126 | +coverage_gammaconfscore = regression_coverage_score( |
| 127 | + y_test, y_pis_gammaconfscore[:, 0, 0], y_pis_gammaconfscore[:, 1, 0] |
| 128 | +) |
| 129 | + |
| 130 | +yerr_gammaconfscore = get_yerr(y_pred_gammaconfscore, y_pis_gammaconfscore) |
| 131 | +pred_int_width_gammaconfscore = ( |
| 132 | + y_pis_gammaconfscore[:, 1, 0] - y_pis_gammaconfscore[:, 0, 0] |
| 133 | +) |
| 134 | + |
| 135 | + |
| 136 | +############################################################################## |
| 137 | +# 3. Compare the prediction intervals |
| 138 | +# ----------------------------------- |
| 139 | +# |
| 140 | +# Once the models have been trained, we now compare the prediction intervals |
| 141 | +# obtained from the two conformity scores. We can see that the |
| 142 | +# :class:AbsoluteConformityScore generates prediction interval with almost the |
| 143 | +# same width for all the predicted values. Converly, the GammaConformityScore |
| 144 | +# yields prediction interval with width scaling with the predicted values. |
| 145 | +# |
| 146 | +# The choice of the conformity score depends on the problem we face. |
| 147 | + |
| 148 | +fig, axs = plt.subplots(2, 2, figsize=(10, 10)) |
| 149 | + |
| 150 | +for img_id, y_pred, y_err, cov, class_name, int_width in zip( |
| 151 | + [0, 1], |
| 152 | + [y_pred_absconfscore, y_pred_gammaconfscore], |
| 153 | + [yerr_absconfscore, yerr_gammaconfscore], |
| 154 | + [coverage_absconfscore, coverage_gammaconfscore], |
| 155 | + ["AbsoluteResidualScore", "GammaResidualScore"], |
| 156 | + [pred_int_width_absconfscore, pred_int_width_gammaconfscore], |
| 157 | +): |
| 158 | + axs[0, img_id].errorbar( |
| 159 | + y_test, |
| 160 | + y_pred, |
| 161 | + yerr=y_err, |
| 162 | + alpha=0.5, |
| 163 | + linestyle="None", |
| 164 | + ) |
| 165 | + axs[0, img_id].scatter(y_test, y_pred, s=1, color="black") |
| 166 | + axs[0, img_id].plot( |
| 167 | + [0, max(max(y_test), max(y_pred))], |
| 168 | + [0, max(max(y_test), max(y_pred))], |
| 169 | + "-r", |
| 170 | + ) |
| 171 | + axs[0, img_id].set_xlabel("Actual price [$]") |
| 172 | + axs[0, img_id].set_ylabel("Predicted price [$]") |
| 173 | + axs[0, img_id].grid() |
| 174 | + axs[0, img_id].set_title(f"{class_name} - coverage={cov:.0%}") |
| 175 | + |
| 176 | + xmin, xmax = axs[0, img_id].get_xlim() |
| 177 | + ymin, ymax = axs[0, img_id].get_ylim() |
| 178 | + axs[1, img_id].scatter(y_test, int_width, marker="+") |
| 179 | + axs[1, img_id].set_xlabel("Actual price [$]") |
| 180 | + axs[1, img_id].set_ylabel("Prediction interval width [$]") |
| 181 | + axs[1, img_id].grid() |
| 182 | + axs[1, img_id].set_xlim([xmin, xmax]) |
| 183 | + axs[1, img_id].set_ylim([ymin, ymax]) |
| 184 | + |
| 185 | +fig.suptitle( |
| 186 | + f"Predicted values with the prediction intervals of level {alpha}" |
| 187 | +) |
| 188 | +plt.subplots_adjust(wspace=0.3, hspace=0.3) |
| 189 | +plt.show() |
0 commit comments