{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# Poisson regression and non-normal loss\n\nThis example illustrates the use of log-linear Poisson regression on the\n[French Motor Third-Party Liability Claims dataset](https://www.openml.org/d/41214) from [1]_ and compares it with a linear\nmodel fitted with the usual least squared error and a non-linear GBRT model\nfitted with the Poisson loss (and a log-link).\n\nA few definitions:\n\n- A **policy** is a contract between an insurance company and an individual:\n  the **policyholder**, that is, the vehicle driver in this case.\n\n- A **claim** is the request made by a policyholder to the insurer to\n  compensate for a loss covered by the insurance.\n\n- The **exposure** is the duration of the insurance coverage of a given policy,\n  in years.\n\n- The claim **frequency** is the number of claims divided by the exposure,\n  typically measured in number of claims per year.\n\nIn this dataset, each sample corresponds to an insurance policy. Available\nfeatures include driver age, vehicle age, vehicle power, etc.\n\nOur goal is to predict the expected frequency of claims following car accidents\nfor a new policyholder given the historical data over a population of\npolicyholders.\n\n.. [1]  A. Noll, R. Salzmann and M.V. Wuthrich, Case Study: French Motor\n    Third-Party Liability Claims (November 8, 2018). [doi:10.2139/ssrn.3164764](https://doi.org/10.2139/ssrn.3164764)\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## The French Motor Third-Party Liability Claims dataset\n\nLet's load the motor claim dataset from OpenML:\nhttps://www.openml.org/d/41214\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "from sklearn.datasets import fetch_openml\n\ndf = fetch_openml(data_id=41214, as_frame=True).frame\ndf"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "The number of claims (``ClaimNb``) is a positive integer that can be modeled\nas a Poisson distribution. It is then assumed to be the number of discrete\nevents occurring with a constant rate in a given time interval (``Exposure``,\nin units of years).\n\nHere we want to model the frequency ``y = ClaimNb / Exposure`` conditionally\non ``X`` via a (scaled) Poisson distribution, and use ``Exposure`` as\n``sample_weight``.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "df[\"Frequency\"] = df[\"ClaimNb\"] / df[\"Exposure\"]\n\nprint(\n    \"Average Frequency = {}\".format(np.average(df[\"Frequency\"], weights=df[\"Exposure\"]))\n)\n\nprint(\n    \"Fraction of exposure with zero claims = {0:.1%}\".format(\n        df.loc[df[\"ClaimNb\"] == 0, \"Exposure\"].sum() / df[\"Exposure\"].sum()\n    )\n)\n\nfig, (ax0, ax1, ax2) = plt.subplots(ncols=3, figsize=(16, 4))\nax0.set_title(\"Number of claims\")\n_ = df[\"ClaimNb\"].hist(bins=30, log=True, ax=ax0)\nax1.set_title(\"Exposure in years\")\n_ = df[\"Exposure\"].hist(bins=30, log=True, ax=ax1)\nax2.set_title(\"Frequency (number of claims per year)\")\n_ = df[\"Frequency\"].hist(bins=30, log=True, ax=ax2)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "The remaining columns can be used to predict the frequency of claim events.\nThose columns are very heterogeneous with a mix of categorical and numeric\nvariables with different scales, possibly very unevenly distributed.\n\nIn order to fit linear models with those predictors it is therefore\nnecessary to perform standard feature transformations as follows:\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "from sklearn.compose import ColumnTransformer\nfrom sklearn.pipeline import make_pipeline\nfrom sklearn.preprocessing import (\n    FunctionTransformer,\n    KBinsDiscretizer,\n    OneHotEncoder,\n    StandardScaler,\n)\n\nlog_scale_transformer = make_pipeline(\n    FunctionTransformer(np.log, validate=False), StandardScaler()\n)\n\nlinear_model_preprocessor = ColumnTransformer(\n    [\n        (\"passthrough_numeric\", \"passthrough\", [\"BonusMalus\"]),\n        (\n            \"binned_numeric\",\n            KBinsDiscretizer(\n                n_bins=10, quantile_method=\"averaged_inverted_cdf\", random_state=0\n            ),\n            [\"VehAge\", \"DrivAge\"],\n        ),\n        (\"log_scaled_numeric\", log_scale_transformer, [\"Density\"]),\n        (\n            \"onehot_categorical\",\n            OneHotEncoder(),\n            [\"VehBrand\", \"VehPower\", \"VehGas\", \"Region\", \"Area\"],\n        ),\n    ],\n    remainder=\"drop\",\n)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## A constant prediction baseline\n\nIt is worth noting that more than 93% of policyholders have zero claims. If\nwe were to convert this problem into a binary classification task, it would\nbe significantly imbalanced, and even a simplistic model that would only\npredict mean can achieve an accuracy of 93%.\n\nTo evaluate the pertinence of the used metrics, we will consider as a\nbaseline a \"dummy\" estimator that constantly predicts the mean frequency of\nthe training sample.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "from sklearn.dummy import DummyRegressor\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.pipeline import Pipeline\n\ndf_train, df_test = train_test_split(df, test_size=0.33, random_state=0)\n\ndummy = Pipeline(\n    [\n        (\"preprocessor\", linear_model_preprocessor),\n        (\"regressor\", DummyRegressor(strategy=\"mean\")),\n    ]\n).fit(df_train, df_train[\"Frequency\"], regressor__sample_weight=df_train[\"Exposure\"])"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Let's compute the performance of this constant prediction baseline with 3\ndifferent regression metrics:\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "from sklearn.metrics import (\n    mean_absolute_error,\n    mean_poisson_deviance,\n    mean_squared_error,\n)\n\n\ndef score_estimator(estimator, df_test):\n    \"\"\"Score an estimator on the test set.\"\"\"\n    y_pred = estimator.predict(df_test)\n\n    print(\n        \"MSE: %.3f\"\n        % mean_squared_error(\n            df_test[\"Frequency\"], y_pred, sample_weight=df_test[\"Exposure\"]\n        )\n    )\n    print(\n        \"MAE: %.3f\"\n        % mean_absolute_error(\n            df_test[\"Frequency\"], y_pred, sample_weight=df_test[\"Exposure\"]\n        )\n    )\n\n    # Ignore non-positive predictions, as they are invalid for\n    # the Poisson deviance.\n    mask = y_pred > 0\n    if (~mask).any():\n        n_masked, n_samples = (~mask).sum(), mask.shape[0]\n        print(\n            \"WARNING: Estimator yields invalid, non-positive predictions \"\n            f\" for {n_masked} samples out of {n_samples}. These predictions \"\n            \"are ignored when computing the Poisson deviance.\"\n        )\n\n    print(\n        \"mean Poisson deviance: %.3f\"\n        % mean_poisson_deviance(\n            df_test[\"Frequency\"][mask],\n            y_pred[mask],\n            sample_weight=df_test[\"Exposure\"][mask],\n        )\n    )\n\n\nprint(\"Constant mean frequency evaluation:\")\nscore_estimator(dummy, df_test)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## (Generalized) linear models\n\nWe start by modeling the target variable with the (l2 penalized) least\nsquares linear regression model, more commonly known as Ridge regression. We\nuse a low penalization `alpha`, as we expect such a linear model to under-fit\non such a large dataset.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "from sklearn.linear_model import Ridge\n\nridge_glm = Pipeline(\n    [\n        (\"preprocessor\", linear_model_preprocessor),\n        (\"regressor\", Ridge(alpha=1e-6)),\n    ]\n).fit(df_train, df_train[\"Frequency\"], regressor__sample_weight=df_train[\"Exposure\"])"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "The Poisson deviance cannot be computed on non-positive values predicted by\nthe model. For models that do return a few non-positive predictions (e.g.\n:class:`~sklearn.linear_model.Ridge`) we ignore the corresponding samples,\nmeaning that the obtained Poisson deviance is approximate. An alternative\napproach could be to use :class:`~sklearn.compose.TransformedTargetRegressor`\nmeta-estimator to map ``y_pred`` to a strictly positive domain.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "print(\"Ridge evaluation:\")\nscore_estimator(ridge_glm, df_test)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Next we fit the Poisson regressor on the target variable. We set the\nregularization strength ``alpha`` to approximately 1e-6 over number of\nsamples (i.e. `1e-12`) in order to mimic the Ridge regressor whose L2 penalty\nterm scales differently with the number of samples.\n\nSince the Poisson regressor internally models the log of the expected target\nvalue instead of the expected value directly (log vs identity link function),\nthe relationship between X and y is not exactly linear anymore. Therefore the\nPoisson regressor is called a Generalized Linear Model (GLM) rather than a\nvanilla linear model as is the case for Ridge regression.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "from sklearn.linear_model import PoissonRegressor\n\nn_samples = df_train.shape[0]\n\npoisson_glm = Pipeline(\n    [\n        (\"preprocessor\", linear_model_preprocessor),\n        (\"regressor\", PoissonRegressor(alpha=1e-12, solver=\"newton-cholesky\")),\n    ]\n)\npoisson_glm.fit(\n    df_train, df_train[\"Frequency\"], regressor__sample_weight=df_train[\"Exposure\"]\n)\n\nprint(\"PoissonRegressor evaluation:\")\nscore_estimator(poisson_glm, df_test)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Gradient Boosting Regression Trees for Poisson regression\n\nFinally, we will consider a non-linear model, namely Gradient Boosting\nRegression Trees. Tree-based models do not require the categorical data to be\none-hot encoded: instead, we can encode each category label with an arbitrary\ninteger using :class:`~sklearn.preprocessing.OrdinalEncoder`. With this\nencoding, the trees will treat the categorical features as ordered features,\nwhich might not be always a desired behavior. However this effect is limited\nfor deep enough trees which are able to recover the categorical nature of the\nfeatures. The main advantage of the\n:class:`~sklearn.preprocessing.OrdinalEncoder` over the\n:class:`~sklearn.preprocessing.OneHotEncoder` is that it will make training\nfaster.\n\nGradient Boosting also gives the possibility to fit the trees with a Poisson\nloss (with an implicit log-link function) instead of the default\nleast-squares loss. Here we only fit trees with the Poisson loss to keep this\nexample concise.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "from sklearn.ensemble import HistGradientBoostingRegressor\nfrom sklearn.preprocessing import OrdinalEncoder\n\ntree_preprocessor = ColumnTransformer(\n    [\n        (\n            \"categorical\",\n            OrdinalEncoder(),\n            [\"VehBrand\", \"VehPower\", \"VehGas\", \"Region\", \"Area\"],\n        ),\n        (\"numeric\", \"passthrough\", [\"VehAge\", \"DrivAge\", \"BonusMalus\", \"Density\"]),\n    ],\n    remainder=\"drop\",\n)\npoisson_gbrt = Pipeline(\n    [\n        (\"preprocessor\", tree_preprocessor),\n        (\n            \"regressor\",\n            HistGradientBoostingRegressor(loss=\"poisson\", max_leaf_nodes=128),\n        ),\n    ]\n)\npoisson_gbrt.fit(\n    df_train, df_train[\"Frequency\"], regressor__sample_weight=df_train[\"Exposure\"]\n)\n\nprint(\"Poisson Gradient Boosted Trees evaluation:\")\nscore_estimator(poisson_gbrt, df_test)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Like the Poisson GLM above, the gradient boosted trees model minimizes\nthe Poisson deviance. However, because of a higher predictive power,\nit reaches lower values of Poisson deviance.\n\nEvaluating models with a single train / test split is prone to random\nfluctuations. If computing resources allow, it should be verified that\ncross-validated performance metrics would lead to similar conclusions.\n\nThe qualitative difference between these models can also be visualized by\ncomparing the histogram of observed target values with that of predicted\nvalues:\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "fig, axes = plt.subplots(nrows=2, ncols=4, figsize=(16, 6), sharey=True)\nfig.subplots_adjust(bottom=0.2)\nn_bins = 20\nfor row_idx, label, df in zip(range(2), [\"train\", \"test\"], [df_train, df_test]):\n    df[\"Frequency\"].hist(bins=np.linspace(-1, 30, n_bins), ax=axes[row_idx, 0])\n\n    axes[row_idx, 0].set_title(\"Data\")\n    axes[row_idx, 0].set_yscale(\"log\")\n    axes[row_idx, 0].set_xlabel(\"y (observed Frequency)\")\n    axes[row_idx, 0].set_ylim([1e1, 5e5])\n    axes[row_idx, 0].set_ylabel(label + \" samples\")\n\n    for idx, model in enumerate([ridge_glm, poisson_glm, poisson_gbrt]):\n        y_pred = model.predict(df)\n\n        pd.Series(y_pred).hist(\n            bins=np.linspace(-1, 4, n_bins), ax=axes[row_idx, idx + 1]\n        )\n        axes[row_idx, idx + 1].set(\n            title=model[-1].__class__.__name__,\n            yscale=\"log\",\n            xlabel=\"y_pred (predicted expected Frequency)\",\n        )\nplt.tight_layout()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "The experimental data presents a long tail distribution for ``y``. In all\nmodels, we predict the expected frequency of a random variable, so we will\nhave necessarily fewer extreme values than for the observed realizations of\nthat random variable. This explains that the mode of the histograms of model\npredictions doesn't necessarily correspond to the smallest value.\nAdditionally, the normal distribution used in ``Ridge`` has a constant\nvariance, while for the Poisson distribution used in ``PoissonRegressor`` and\n``HistGradientBoostingRegressor``, the variance is proportional to the\npredicted expected value.\n\nThus, among the considered estimators, ``PoissonRegressor`` and\n``HistGradientBoostingRegressor`` are a-priori better suited for modeling the\nlong tail distribution of the non-negative data as compared to the ``Ridge``\nmodel which makes a wrong assumption on the distribution of the target\nvariable.\n\nThe ``HistGradientBoostingRegressor`` estimator has the most flexibility and\nis able to predict higher expected values.\n\nNote that we could have used the least squares loss for the\n``HistGradientBoostingRegressor`` model. This would wrongly assume a normal\ndistributed response variable as does the `Ridge` model, and possibly\nalso lead to slightly negative predictions. However the gradient boosted\ntrees would still perform relatively well and in particular better than\n``PoissonRegressor`` thanks to the flexibility of the trees combined with the\nlarge number of training samples.\n\n## Evaluation of the calibration of predictions\n\nTo ensure that estimators yield reasonable predictions for different\npolicyholder types, we can bin test samples according to ``y_pred`` returned\nby each model. Then for each bin, we compare the mean predicted ``y_pred``,\nwith the mean observed target:\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "from sklearn.utils import gen_even_slices\n\n\ndef _mean_frequency_by_risk_group(y_true, y_pred, sample_weight=None, n_bins=100):\n    \"\"\"Compare predictions and observations for bins ordered by y_pred.\n\n    We order the samples by ``y_pred`` and split it in bins.\n    In each bin the observed mean is compared with the predicted mean.\n\n    Parameters\n    ----------\n    y_true: array-like of shape (n_samples,)\n        Ground truth (correct) target values.\n    y_pred: array-like of shape (n_samples,)\n        Estimated target values.\n    sample_weight : array-like of shape (n_samples,)\n        Sample weights.\n    n_bins: int\n        Number of bins to use.\n\n    Returns\n    -------\n    bin_centers: ndarray of shape (n_bins,)\n        bin centers\n    y_true_bin: ndarray of shape (n_bins,)\n        average y_pred for each bin\n    y_pred_bin: ndarray of shape (n_bins,)\n        average y_pred for each bin\n    \"\"\"\n    idx_sort = np.argsort(y_pred)\n    bin_centers = np.arange(0, 1, 1 / n_bins) + 0.5 / n_bins\n    y_pred_bin = np.zeros(n_bins)\n    y_true_bin = np.zeros(n_bins)\n\n    for n, sl in enumerate(gen_even_slices(len(y_true), n_bins)):\n        weights = sample_weight[idx_sort][sl]\n        y_pred_bin[n] = np.average(y_pred[idx_sort][sl], weights=weights)\n        y_true_bin[n] = np.average(y_true[idx_sort][sl], weights=weights)\n    return bin_centers, y_true_bin, y_pred_bin\n\n\nprint(f\"Actual number of claims: {df_test['ClaimNb'].sum()}\")\nfig, ax = plt.subplots(nrows=2, ncols=2, figsize=(12, 8))\nplt.subplots_adjust(wspace=0.3)\n\nfor axi, model in zip(ax.ravel(), [ridge_glm, poisson_glm, poisson_gbrt, dummy]):\n    y_pred = model.predict(df_test)\n    y_true = df_test[\"Frequency\"].values\n    exposure = df_test[\"Exposure\"].values\n    q, y_true_seg, y_pred_seg = _mean_frequency_by_risk_group(\n        y_true, y_pred, sample_weight=exposure, n_bins=10\n    )\n\n    # Name of the model after the estimator used in the last step of the\n    # pipeline.\n    print(f\"Predicted number of claims by {model[-1]}: {np.sum(y_pred * exposure):.1f}\")\n\n    axi.plot(q, y_pred_seg, marker=\"x\", linestyle=\"--\", label=\"predictions\")\n    axi.plot(q, y_true_seg, marker=\"o\", linestyle=\"--\", label=\"observations\")\n    axi.set_xlim(0, 1.0)\n    axi.set_ylim(0, 0.5)\n    axi.set(\n        title=model[-1],\n        xlabel=\"Fraction of samples sorted by y_pred\",\n        ylabel=\"Mean Frequency (y_pred)\",\n    )\n    axi.legend()\nplt.tight_layout()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "The dummy regression model predicts a constant frequency. This model does not\nattribute the same tied rank to all samples but is none-the-less globally\nwell calibrated (to estimate the mean frequency of the entire population).\n\nThe ``Ridge`` regression model can predict very low expected frequencies that\ndo not match the data. It can therefore severely under-estimate the risk for\nsome policyholders.\n\n``PoissonRegressor`` and ``HistGradientBoostingRegressor`` show better\nconsistency between predicted and observed targets, especially for low\npredicted target values.\n\nThe sum of all predictions also confirms the calibration issue of the\n``Ridge`` model: it under-estimates by more than 3% the total number of\nclaims in the test set while the other three models can approximately recover\nthe total number of claims of the test portfolio.\n\n## Evaluation of the ranking power\n\nFor some business applications, we are interested in the ability of the model\nto rank the riskiest from the safest policyholders, irrespective of the\nabsolute value of the prediction. In this case, the model evaluation would\ncast the problem as a ranking problem rather than a regression problem.\n\nTo compare the 3 models from this perspective, one can plot the cumulative\nproportion of claims vs the cumulative proportion of exposure for the test\nsamples order by the model predictions, from safest to riskiest according to\neach model.\n\nThis plot is called a Lorenz curve and can be summarized by the Gini index:\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "from sklearn.metrics import auc\n\n\ndef lorenz_curve(y_true, y_pred, exposure):\n    y_true, y_pred = np.asarray(y_true), np.asarray(y_pred)\n    exposure = np.asarray(exposure)\n\n    # order samples by increasing predicted risk:\n    ranking = np.argsort(y_pred)\n    ranked_frequencies = y_true[ranking]\n    ranked_exposure = exposure[ranking]\n    cumulated_claims = np.cumsum(ranked_frequencies * ranked_exposure)\n    cumulated_claims /= cumulated_claims[-1]\n    cumulated_exposure = np.cumsum(ranked_exposure)\n    cumulated_exposure /= cumulated_exposure[-1]\n    return cumulated_exposure, cumulated_claims\n\n\nfig, ax = plt.subplots(figsize=(8, 8))\n\nfor model in [dummy, ridge_glm, poisson_glm, poisson_gbrt]:\n    y_pred = model.predict(df_test)\n    cum_exposure, cum_claims = lorenz_curve(\n        df_test[\"Frequency\"], y_pred, df_test[\"Exposure\"]\n    )\n    gini = 1 - 2 * auc(cum_exposure, cum_claims)\n    label = \"{} (Gini: {:.2f})\".format(model[-1], gini)\n    ax.plot(cum_exposure, cum_claims, linestyle=\"-\", label=label)\n\n# Oracle model: y_pred == y_test\ncum_exposure, cum_claims = lorenz_curve(\n    df_test[\"Frequency\"], df_test[\"Frequency\"], df_test[\"Exposure\"]\n)\ngini = 1 - 2 * auc(cum_exposure, cum_claims)\nlabel = \"Oracle (Gini: {:.2f})\".format(gini)\nax.plot(cum_exposure, cum_claims, linestyle=\"-.\", color=\"gray\", label=label)\n\n# Random Baseline\nax.plot([0, 1], [0, 1], linestyle=\"--\", color=\"black\", label=\"Random baseline\")\nax.set(\n    title=\"Lorenz curves by model\",\n    xlabel=\"Cumulative proportion of exposure (from safest to riskiest)\",\n    ylabel=\"Cumulative proportion of claims\",\n)\nax.legend(loc=\"upper left\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "As expected, the dummy regressor is unable to correctly rank the samples and\ntherefore performs the worst on this plot.\n\nThe tree-based model is significantly better at ranking policyholders by risk\nwhile the two linear models perform similarly.\n\nAll three models are significantly better than chance but also very far from\nmaking perfect predictions.\n\nThis last point is expected due to the nature of the problem: the occurrence\nof accidents is mostly dominated by circumstantial causes that are not\ncaptured in the columns of the dataset and can indeed be considered as purely\nrandom.\n\nThe linear models assume no interactions between the input variables which\nlikely causes under-fitting. Inserting a polynomial feature extractor\n(:func:`~sklearn.preprocessing.PolynomialFeatures`) indeed increases their\ndiscrimative power by 2 points of Gini index. In particular it improves the\nability of the models to identify the top 5% riskiest profiles.\n\n## Main takeaways\n\n- The performance of the models can be evaluated by their ability to yield\n  well-calibrated predictions and a good ranking.\n\n- The calibration of the model can be assessed by plotting the mean observed\n  value vs the mean predicted value on groups of test samples binned by\n  predicted risk.\n\n- The least squares loss (along with the implicit use of the identity link\n  function) of the Ridge regression model seems to cause this model to be\n  badly calibrated. In particular, it tends to underestimate the risk and can\n  even predict invalid negative frequencies.\n\n- Using the Poisson loss with a log-link can correct these problems and lead\n  to a well-calibrated linear model.\n\n- The Gini index reflects the ability of a model to rank predictions\n  irrespective of their absolute values, and therefore only assess their\n  ranking power.\n\n- Despite the improvement in calibration, the ranking power of both linear\n  models are comparable and well below the ranking power of the Gradient\n  Boosting Regression Trees.\n\n- The Poisson deviance computed as an evaluation metric reflects both the\n  calibration and the ranking power of the model. It also makes a linear\n  assumption on the ideal relationship between the expected value and the\n  variance of the response variable. For the sake of conciseness we did not\n  check whether this assumption holds.\n\n- Traditional regression metrics such as Mean Squared Error and Mean Absolute\n  Error are hard to meaningfully interpret on count values with many zeros.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "plt.show()"
      ]
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3.11.14"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}