{
  "cells": [
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "%matplotlib inline"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# Recursive feature elimination with cross-validation\n\nA recursive feature elimination example with automatic tuning of the\nnumber of features selected with cross-validation.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import matplotlib.pyplot as plt\nfrom sklearn.svm import SVC\nfrom sklearn.model_selection import StratifiedKFold\nfrom sklearn.feature_selection import RFECV\nfrom sklearn.datasets import make_classification\n\n# Build a classification task using 3 informative features\nX, y = make_classification(\n    n_samples=1000,\n    n_features=25,\n    n_informative=3,\n    n_redundant=2,\n    n_repeated=0,\n    n_classes=8,\n    n_clusters_per_class=1,\n    random_state=0,\n)\n\n# Create the RFE object and compute a cross-validated score.\nsvc = SVC(kernel=\"linear\")\n# The \"accuracy\" scoring shows the proportion of correct classifications\n\nmin_features_to_select = 1  # Minimum number of features to consider\nrfecv = RFECV(\n    estimator=svc,\n    step=1,\n    cv=StratifiedKFold(2),\n    scoring=\"accuracy\",\n    min_features_to_select=min_features_to_select,\n)\nrfecv.fit(X, y)\n\nprint(\"Optimal number of features : %d\" % rfecv.n_features_)\n\n# Plot number of features VS. cross-validation scores\nplt.figure()\nplt.xlabel(\"Number of features selected\")\nplt.ylabel(\"Cross validation score (accuracy)\")\nplt.plot(\n    range(min_features_to_select, len(rfecv.grid_scores_) + min_features_to_select),\n    rfecv.grid_scores_,\n)\nplt.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.9.13"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}