{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# Model Fairness Analysis (Classification)\n\nThis example requires full licence, and the program will break if you use the trial licence.\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Installation\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "# To install the required package, use the following command:\n# !pip install modeva"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Authentication\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "# To get authentication, use the following command: (To get full access please replace the token to your own token)\n# from modeva.utils.authenticate import authenticate\n# authenticate(auth_code='eaaa4301-b140-484c-8e93-f9f633c8bacb')"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Import required modules\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "from modeva import DataSet\nfrom modeva import TestSuite\nfrom modeva.models import MoLGBMClassifier\nfrom modeva.models import MoXGBClassifier\nfrom modeva.data.utils.loading import load_builtin_data\nfrom modeva.testsuite.utils.slicing_utils import get_data_info"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Load and prepare dataset\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "data = load_builtin_data(\"TaiwanCredit\").drop(['SEX', 'MARRIAGE', 'AGE'], axis=1)\n\nds = DataSet()\nds.load_dataframe(data.iloc[:5000])\nds.set_target(\"FlagDefault\")\nds.set_random_split()\n\nprotected_data = load_builtin_data(\"TaiwanCredit\")[['SEX', 'MARRIAGE', 'AGE']]\nds.set_protected_data(protected_data.iloc[:5000])\nds.set_raw_extra_data(name=\"oot\", data=data.iloc[5000:])\nds.set_protected_extra_data(name=\"oot\", data=protected_data.iloc[5000:])"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Train models\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "model1 = MoXGBClassifier()\nmodel1.fit(ds.train_x, ds.train_y)\n\nmodel2 = MoLGBMClassifier(max_depth=2, verbose=-1, random_state=0)\nmodel2.fit(ds.train_x.astype(float), ds.train_y.ravel().astype(float))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Basic fairness analysis\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "ts = TestSuite(ds, model1)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Config protected and reference groups\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "group_config = {\n    \"Gender-Male\": {\"feature\": \"SEX\", \"protected\": 2.0, \"reference\": 1.0},\n    \"Gender-Female\": {\"feature\": \"SEX\", \"protected\": 1.0, \"reference\": 2.0},\n    \"MARRIAGE\": {\"feature\": \"MARRIAGE\", \"protected\": 2.0, \"reference\": 1.0},\n    \"AGE\": {\"feature\": \"AGE\", \"protected\": {\"lower\": 60, \"lower_inclusive\": True},\n            \"reference\": {\"upper\": 60, \"upper_inclusive\": False}}\n}"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Calculate adverse impact ratio (AIR)\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "results = ts.diagnose_fairness(group_config=group_config,\n                               favorable_label=1,\n                               metric=\"AIR\",\n                               threshold=0.8)\nresults.plot()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Check distribution drift of protected and reference groups (example for the \"Gender-Male\" group)\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "data_results = ds.data_drift_test(\n    **results.value[\"Gender-Male\"][\"data_info\"],\n    distance_metric=\"PSI\",\n    psi_method=\"uniform\",\n    psi_bins=10\n)\ndata_results.plot(name=\"summary\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Analyze data drift for single variable\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "data_results.plot(name=(\"density\", \"PAY_1\"))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Slicing fairness analysis\nSingle feature slicing\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "results = ts.diagnose_slicing_fairness(features=\"PAY_1\",\n                                       group_config=group_config,\n                                       dataset=\"test\",\n                                       metric=\"AIR\")\nresults.plot()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Bivariate features slicing\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "results = ts.diagnose_slicing_fairness(features=(\"PAY_1\", \"BILL_AMT1\"),\n                                       group_config=group_config,\n                                       dataset=\"test\",\n                                       metric=\"AIR\",\n                                       threshold=0.9)\nresults.plot(name=\"Gender-Male\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Batch mode single feature slicing\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "results = ts.diagnose_slicing_fairness(features=((\"BILL_AMT1\",), (\"BILL_AMT2\",), (\"BILL_AMT3\",)),\n                                       group_config=group_config,\n                                       dataset=\"test\",\n                                       metric=\"AIR\",\n                                       method=\"auto-xgb1\", bins=5)\nresults.table[\"Gender-Male\"]"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Batch mode 1D Slicing (all features by setting features=None)\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "results = ts.diagnose_slicing_fairness(features=None,\n                                       group_config=group_config,\n                                       dataset=\"test\",\n                                       metric=\"AIR\",\n                                       method=\"auto-xgb1\", bins=5)\nresults.table[\"Gender-Male\"]"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Analyze data drift\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "data_info = get_data_info(res_value=results.value[\"PAY_1\"][\"Gender-Male\"])\ndata_results = ds.data_drift_test(\n    **data_info[\"PAY_1\"],\n    distance_metric=\"PSI\",\n    psi_method=\"uniform\",\n    psi_bins=10\n)\ndata_results.plot(\"summary\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Single feature density plot\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "data_results.plot((\"density\", \"PAY_1\"))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Fairness comparison\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "tsc = TestSuite(ds, models=[model1, model2])\nresults = tsc.compare_fairness(group_config=group_config,\n                               metric=\"AIR\",\n                               threshold=0.8)\nresults.plot()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Compare robustness performance of multiple models under single slicing feature\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "result = tsc.compare_slicing_fairness(features=\"BILL_AMT1\",\n                                      group_config=group_config,\n                                      favorable_label=1,\n                                      dataset=\"test\",\n                                      metric=\"AIR\")\nresult.table[\"Gender-Male\"]"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Unfairness mitigation\nBy adjusting threshold of predict proba\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "result = ts.diagnose_mitigate_unfair_thresholding(group_config=group_config,\n                                                  favorable_label=1,\n                                                  dataset=\"test\",\n                                                  metric=\"AIR\",\n                                                  performance_metric=\"AUC\",\n                                                  proba_cutoff=30)\nresult.plot(\"Gender-Male\", figsize=(8, 5))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "By binning features\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "result = ts.diagnose_mitigate_unfair_binning(group_config=group_config,\n                                             favorable_label=1,\n                                             dataset=\"test\",\n                                             metric=\"AIR\",\n                                             performance_metric=\"AUC\",\n                                             binning_method='uniform',\n                                             bins=10)\nresult.plot(\"Gender-Male\")"
      ]
    }
  ],
  "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.11"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}