{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# A demo of CRFE on German Credit Data\n\nRecursive feature elimination with :class:`~tagarnina.crfe.CRFE` on the German\ncredit dataset (1,000 applicants, 20 features). The one-hot columns of each\ncategorical feature are kept or removed together, and two numerical features with\na Pearson correlation of at least 0.5 cannot both be selected.\n\nThe dataset is public and is available on OpenML (ID 31). Please cite it as:\nDr. Hans Hofmann, Statlog (German Credit Data), UCI Machine Learning Repository,\n1994.\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Load the data\nThe target is ``good`` or ``bad`` credit risk. It is encoded as 1 for good.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "from sklearn.datasets import fetch_openml\n\nX, y = fetch_openml(data_id=31, as_frame=True, return_X_y=True, parser=\"auto\")\ny = (y == \"good\").astype(int)\n\ncategorical_features = X.select_dtypes(\"category\").columns.tolist()\nnumerical_features = X.select_dtypes(\"number\").columns.tolist()\n\nprint(\n    f\"{len(categorical_features)} categorical and {len(numerical_features)} numerical features\"\n)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## One-hot encoding\nEach categorical feature is one-hot encoded. The encoded columns keep the\noriginal feature name as a prefix, so they can be grouped by name.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import pandas as pd\nfrom sklearn.compose import ColumnTransformer, make_column_selector\nfrom sklearn.preprocessing import OneHotEncoder\n\npreprocessor = ColumnTransformer(\n    transformers=[\n        (\"cat\", OneHotEncoder(), make_column_selector(dtype_include=\"category\"))\n    ],\n    remainder=\"passthrough\",\n    verbose_feature_names_out=False,\n)\nX_transformed = pd.DataFrame(\n    data=preprocessor.fit_transform(X),\n    columns=preprocessor.get_feature_names_out(),\n)\n\nprint(X_transformed.shape)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Constraints\nAn :class:`~tagarnina.optimization.constraints.AllOrNoneConstraint` on the\nencoded columns of each categorical feature keeps the whole feature or removes\nit. A :class:`~tagarnina.optimization.constraints.MaxCorrelationConstraint` on\nthe numerical features limits their pairwise correlation.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "from tagarnina.optimization.constraints import (\n    AllOrNoneConstraint,\n    Constraints,\n    MaxCorrelationConstraint,\n)\n\nall_or_none_constraints = [\n    AllOrNoneConstraint(\n        features=[c for c in X_transformed.columns if c.startswith(f\"{feature}_\")]\n    )\n    for feature in categorical_features\n]\n\nmax_corr_constraint = MaxCorrelationConstraint(\n    features=numerical_features,\n    max_corr=0.5,\n    method=\"pearson\",\n)\n\nconstraints = Constraints(\n    constraints=[*all_or_none_constraints, max_corr_constraint],\n)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Feature elimination\n:class:`~tagarnina.crfe.CRFE` refits the estimator at each step and removes\nfeatures until 20 remain. The constraints decide which features can be removed.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "from sklearn.ensemble import RandomForestClassifier\n\nfrom tagarnina.crfe import CRFE\n\nestimator = RandomForestClassifier(max_depth=10, min_samples_leaf=0.2, random_state=0)\n\ncrfe = CRFE(\n    estimator=estimator,\n    constraints=constraints,\n    step=0.1,\n    n_features_to_select=20,\n    scoring=\"roc_auc\",\n)\ncrfe.fit(X_transformed, y)\n\nselected_features = crfe.get_feature_names_out()\nprint(selected_features)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Each categorical feature is either fully selected or fully removed:\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "for feature in categorical_features:\n    columns = [c for c in X_transformed.columns if c.startswith(f\"{feature}_\")]\n    n_selected = sum(c in selected_features for c in columns)\n    print(f\"{feature}: {n_selected} of {len(columns)} columns selected\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "The correlation constraint is checked the same way. The check lists the pairs\nof selected numerical features with a correlation of at least 0.5, which\nshould be none.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "from itertools import combinations\n\nselected_numerical = [f for f in numerical_features if f in selected_features]\ncorr = X_transformed[selected_numerical].corr(method=\"pearson\")\npairs = [(a, b, corr.loc[a, b]) for a, b in combinations(selected_numerical, 2)]\nviolations = [(a, b, round(r, 3)) for a, b, r in pairs if r >= 0.5]\n\nprint(f\"{len(selected_numerical)} numerical features selected, {len(pairs)} pairs\")\nprint(f\"Pairs with correlation >= 0.5: {violations}\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## History\n:attr:`~tagarnina.crfe.CRFE.history_` has one entry per fitted support, from\nall features down to the 20 selected ones. The fields shown below are:\n\n- ``n_features``: number of features in the support.\n- ``removed``: number of features removed from the support in the next step.\n- ``score``: ROC AUC on the training data.\n- ``importance_gap``: importance lost because of the constraints. It compares\n  the importance kept with the constraints to the importance that standard RFE\n  would keep with the same number of features. It is 0 without constraints.\n- ``n_infeasible_probes``: candidate removals rejected by the constraints.\n\nThe last row has no next step, so ``removed`` and ``n_infeasible_probes`` are\nNaN.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import pandas as pd\n\nhistory = pd.DataFrame(\n    {\n        key: crfe.history_[key]\n        for key in [\n            \"n_features\",\n            \"removed\",\n            \"score\",\n            \"importance_gap\",\n            \"n_infeasible_probes\",\n        ]\n    }\n)\nprint(history.round(3).to_string(index=False))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "The score history is plotted below. The score is computed on the training data,\nso it is optimistic and tends to increase with the number of features.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import matplotlib.pyplot as plt\n\nfig, ax = plt.subplots()\nax.plot(crfe.history_[\"n_features\"], crfe.history_[\"score\"], marker=\"o\")\nax.set_xlabel(\"Number of features\")\nax.set_ylabel(\"ROC AUC (training data)\")\nax.set_title(\"CRFE score history\")\nfig.tight_layout()"
      ]
    }
  ],
  "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.13.17"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}