{
  "cells": [
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "%matplotlib inline"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\nVisualizing cross-validation behavior in scikit-learn\n=====================================================\n\nChoosing the right cross-validation object is a crucial part of fitting a\nmodel properly. There are many ways to split data into training and test\nsets in order to avoid model overfitting, to standardize the number of\ngroups in test sets, etc.\n\nThis example visualizes the behavior of several common scikit-learn objects\nfor comparison.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "from sklearn.model_selection import (TimeSeriesSplit, KFold, ShuffleSplit,\n                                     StratifiedKFold, GroupShuffleSplit,\n                                     GroupKFold, StratifiedShuffleSplit)\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.patches import Patch\nnp.random.seed(1338)\ncmap_data = plt.cm.Paired\ncmap_cv = plt.cm.coolwarm\nn_splits = 4"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Visualize our data\n------------------\n\nFirst, we must understand the structure of our data. It has 100 randomly\ngenerated input datapoints, 3 classes split unevenly across datapoints,\nand 10 \"groups\" split evenly across datapoints.\n\nAs we'll see, some cross-validation objects do specific things with\nlabeled data, others behave differently with grouped data, and others\ndo not use this information.\n\nTo begin, we'll visualize our data.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "# Generate the class/group data\nn_points = 100\nX = np.random.randn(100, 10)\n\npercentiles_classes = [.1, .3, .6]\ny = np.hstack([[ii] * int(100 * perc)\n               for ii, perc in enumerate(percentiles_classes)])\n\n# Evenly spaced groups repeated once\ngroups = np.hstack([[ii] * 10 for ii in range(10)])\n\n\ndef visualize_groups(classes, groups, name):\n    # Visualize dataset groups\n    fig, ax = plt.subplots()\n    ax.scatter(range(len(groups)),  [.5] * len(groups), c=groups, marker='_',\n               lw=50, cmap=cmap_data)\n    ax.scatter(range(len(groups)),  [3.5] * len(groups), c=classes, marker='_',\n               lw=50, cmap=cmap_data)\n    ax.set(ylim=[-1, 5], yticks=[.5, 3.5],\n           yticklabels=['Data\\ngroup', 'Data\\nclass'], xlabel=\"Sample index\")\n\n\nvisualize_groups(y, groups, 'no groups')"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Define a function to visualize cross-validation behavior\n--------------------------------------------------------\n\nWe'll define a function that lets us visualize the behavior of each\ncross-validation object. We'll perform 4 splits of the data. On each\nsplit, we'll visualize the indices chosen for the training set\n(in blue) and the test set (in red).\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "def plot_cv_indices(cv, X, y, group, ax, n_splits, lw=10):\n    \"\"\"Create a sample plot for indices of a cross-validation object.\"\"\"\n\n    # Generate the training/testing visualizations for each CV split\n    for ii, (tr, tt) in enumerate(cv.split(X=X, y=y, groups=group)):\n        # Fill in indices with the training/test groups\n        indices = np.array([np.nan] * len(X))\n        indices[tt] = 1\n        indices[tr] = 0\n\n        # Visualize the results\n        ax.scatter(range(len(indices)), [ii + .5] * len(indices),\n                   c=indices, marker='_', lw=lw, cmap=cmap_cv,\n                   vmin=-.2, vmax=1.2)\n\n    # Plot the data classes and groups at the end\n    ax.scatter(range(len(X)), [ii + 1.5] * len(X),\n               c=y, marker='_', lw=lw, cmap=cmap_data)\n\n    ax.scatter(range(len(X)), [ii + 2.5] * len(X),\n               c=group, marker='_', lw=lw, cmap=cmap_data)\n\n    # Formatting\n    yticklabels = list(range(n_splits)) + ['class', 'group']\n    ax.set(yticks=np.arange(n_splits+2) + .5, yticklabels=yticklabels,\n           xlabel='Sample index', ylabel=\"CV iteration\",\n           ylim=[n_splits+2.2, -.2], xlim=[0, 100])\n    ax.set_title('{}'.format(type(cv).__name__), fontsize=15)\n    return ax"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Let's see how it looks for the `KFold` cross-validation object:\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "fig, ax = plt.subplots()\ncv = KFold(n_splits)\nplot_cv_indices(cv, X, y, groups, ax, n_splits)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "As you can see, by default the KFold cross-validation iterator does not\ntake either datapoint class or group into consideration. We can change this\nby using the ``StratifiedKFold`` like so.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "fig, ax = plt.subplots()\ncv = StratifiedKFold(n_splits)\nplot_cv_indices(cv, X, y, groups, ax, n_splits)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "In this case, the cross-validation retained the same ratio of classes across\neach CV split. Next we'll visualize this behavior for a number of CV\niterators.\n\nVisualize cross-validation indices for many CV objects\n------------------------------------------------------\n\nLet's visually compare the cross validation behavior for many\nscikit-learn cross-validation objects. Below we will loop through several\ncommon cross-validation objects, visualizing the behavior of each.\n\nNote how some use the group/class information while others do not.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "cvs = [KFold, GroupKFold, ShuffleSplit, StratifiedKFold,\n       GroupShuffleSplit, StratifiedShuffleSplit, TimeSeriesSplit]\n\n\nfor cv in cvs:\n    this_cv = cv(n_splits=n_splits)\n    fig, ax = plt.subplots(figsize=(6, 3))\n    plot_cv_indices(this_cv, X, y, groups, ax, n_splits)\n\n    ax.legend([Patch(color=cmap_cv(.8)), Patch(color=cmap_cv(.02))],\n              ['Testing set', 'Training set'], loc=(1.02, .8))\n    # Make the legend fit\n    plt.tight_layout()\n    fig.subplots_adjust(right=.7)\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.6.7"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}