{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# CRFECV on German Credit Data\n\nChoosing the number of features with :class:`~tagarnina.crfe.CRFECV` on the German\ncredit dataset (1,000 applicants, 20 features). :class:`~tagarnina.crfe.CRFE` runs\ninside each cross-validation fold, and every size it reaches is scored on the\nheld-out rows. The size with the best mean score is selected, and the final run\nuses all the data.\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()"
      ]
    },
    {
      "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)"
      ]
    },
    {
      "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\nlimits the pairwise Pearson correlation of the numerical features to 0.5.\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]\nmax_corr_constraint = MaxCorrelationConstraint(\n    features=numerical_features, max_corr=0.5, method=\"pearson\"\n)\nconstraints = Constraints(constraints=[*all_or_none_constraints, max_corr_constraint])"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## The selector\n:class:`~tagarnina.crfe.CRFECV` uses 5 stratified folds and ROC AUC as the score.\nEach fold runs CRFE and scores every size on its test rows.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "from sklearn.ensemble import RandomForestClassifier\nfrom sklearn.model_selection import StratifiedKFold\n\nfrom tagarnina.crfe import CRFECV\n\nselector = CRFECV(\n    estimator=RandomForestClassifier(\n        max_depth=10, min_samples_leaf=0.2, random_state=0\n    ),\n    constraints=constraints,\n    step=0.1,\n    cv=StratifiedKFold(n_splits=5, shuffle=True, random_state=0),\n    scoring=\"roc_auc\",\n)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Fitting\nThe duration and credit amount features have a correlation of about 0.62, so\nthey cannot both be selected. The full set of features therefore violates the\nconstraints. Its score exists, because the first round of CRFE is\nunconstrained, but it is not a valid choice. CRFECV excludes it from the\ncomparison and warns.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import warnings\n\nwith warnings.catch_warnings(record=True) as caught:\n    warnings.simplefilter(\"always\")\n    selector.fit(X_transformed, y)\nfor warning in caught:\n    print(f\"{warning.category.__name__}: {warning.message}\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Cross-validation results\n:attr:`~tagarnina.crfe.CRFECV.cv_results_` holds the mean and standard deviation\nof the held-out score for each size that all folds reached. The size with the\nbest mean is selected, and ties go to fewer features.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "cv_results = pd.DataFrame(selector.cv_results_)\nprint(\n    cv_results[[\"n_features\", \"mean_test_score\", \"std_test_score\"]]\n    .round(3)\n    .to_string(index=False)\n)\nprint(f\"Selected: {selector.n_features_} features\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Selected features\nThe final run uses all the data and stops at the selected size. As in the basic\nexample, the selection keeps each categorical feature whole and does not hold\nboth duration and credit amount.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "selected_features = selector.get_feature_names_out()\nfor 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    assert n_selected in (0, len(columns))\nprint(\n    \"duration and credit_amount:\",\n    [f for f in (\"duration\", \"credit_amount\") if f in selected_features],\n)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "The full set is absent, and the best mean score is at 51 features. The score\ndecreases as more features are removed. The plot shows it for each size, with the\nselected size marked.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import matplotlib.pyplot as plt\n\nfig, ax = plt.subplots()\nax.errorbar(\n    cv_results[\"n_features\"],\n    cv_results[\"mean_test_score\"],\n    yerr=cv_results[\"std_test_score\"],\n    marker=\"o\",\n    capsize=3,\n)\nax.axvline(\n    selector.n_features_,\n    color=\"gray\",\n    linestyle=\"--\",\n    label=f\"selected: {selector.n_features_}\",\n)\nax.set_xlabel(\"Number of features\")\nax.set_ylabel(\"ROC AUC (held-out)\")\nax.set_title(\"CRFECV scores by number of features\")\nax.legend()\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
}