{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "#### Cross Validation" ] }, { "cell_type": "code", "execution_count": 34, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# import\n", "from sklearn.datasets import load_iris\n", "from sklearn.model_selection import cross_val_score, KFold, train_test_split, cross_val_predict, LeaveOneOut, LeavePOut\n", "from sklearn.model_selection import ShuffleSplit, StratifiedKFold, StratifiedShuffleSplit, GroupKFold, LeaveOneGroupOut\n", "from sklearn.model_selection import LeavePGroupsOut, GroupShuffleSplit, TimeSeriesSplit\n", "from sklearn.metrics import accuracy_score\n", "from sklearn.svm import SVC\n", "\n", "from scipy.stats import sem\n", "import numpy as np\n", "import matplotlib.pyplot as plt\n", "\n", "%matplotlib inline" ] }, { "cell_type": "code", "execution_count": 2, "metadata": { "collapsed": true }, "outputs": [], "source": [ "iris = load_iris()\n", "\n", "X, y = iris.data, iris.target" ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "(112, 4) (38, 4) 112\n" ] } ], "source": [ "# splotting the data into train and test\n", "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=27)\n", "\n", "print(X_train.shape, X_test.shape, X_train.shape[0])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " cross_val_score uses the KFold or StratifiedKFold strategies by default " ] }, { "cell_type": "code", "execution_count": 38, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# define cross_val func\n", "\n", "def xVal_score(clf, X, y, K):\n", " \n", " # creating K using KFold\n", " cv = KFold(n_splits=2)\n", " \n", " # Can use suffle as well\n", " # cv = ShuffleSplit(n_splits=3, test_size=0.3, random_state=0)\n", " \n", " # doing cross validation\n", " scores = cross_val_score(clf, X, y, cv=cv)\n", " print(scores)\n", " print(\"Accuracy Mean : %0.3f\" %np.mean(scores))\n", " print(\"Std : \", np.std(scores))\n", " print(\"Standard Err : +/- {0:0.6f} \".format(sem(scores)))" ] }, { "cell_type": "code", "execution_count": 39, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[ 0.98214286 0.94642857]\n", "Accuracy Mean : 0.964\n", "Std : 0.0178571428571\n", "Standard Err : +/- 0.017857 \n" ] } ], "source": [ "svc1 = SVC()\n", "xVal_score(svc1, X_train, y_train, 10)" ] }, { "cell_type": "code", "execution_count": 8, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# define cross_val predict\n", "# The function cross_val_predict has a similar interface to cross_val_score, but returns, \n", "# for each element in the input, the prediction that was obtained for that element when it \n", "# was in the test set. Only cross-validation strategies that assign all elements to a test \n", "# set exactly once can be used (otherwise, an exception is raised).\n", "\n", "def xVal_predict(clf, X, y, K):\n", " \n", " # creating K using KFold\n", " cv = KFold(n_splits=K)\n", " \n", " # Can use suffle as well\n", " # cv = ShuffleSplit(n_splits=3, test_size=0.3, random_state=0)\n", " \n", " # doing cross validation prediction\n", " predicted = cross_val_predict(clf, X, y, cv=cv)\n", " print(predicted)\n", " print(\"Accuracy Score : %0.3f\" % accuracy_score(y, predicted))" ] }, { "cell_type": "code", "execution_count": 9, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[1 0 0 2 2 2 0 1 2 2 1 0 0 0 1 0 1 0 2 0 0 1 2 2 1 2 2 1 2 2 0 2 0 2 2 0 1\n", " 0 0 0 1 1 2 2 0 2 0 1 2 2 1 0 1 2 1 2 1 1 0 1 0 0 0 0 2 2 0 1 1 2 0 1 2 2\n", " 0 0 2 1 0 2 1 0 1 1 2 1 0 1 1 1 1 2 0 1 1 0 1 0 2 0 2 2 0 2 2 0 0 0 1 0 1\n", " 0]\n", "Accuracy Score : 0.973\n" ] } ], "source": [ "xVal_predict(svc1, X_train, y_train, 10)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "** Cross Validation Iterator ** \n", "\n", "** K-Fold ** - KFold divides all the samples in k groups of samples, called folds (if k = n, this is equivalent to the Leave One Out strategy), of equal sizes (if possible). The prediction function is learned using k - 1 folds, and the fold left out is used for test." ] }, { "cell_type": "code", "execution_count": 11, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "KFold(n_splits=2, random_state=None, shuffle=False)\n", "(array([3, 4]), array([0, 1, 2]))\n", "(array([0, 1, 2]), array([3, 4]))\n" ] } ], "source": [ "X = [1,2,3,4,5]\n", "kf = KFold(n_splits=2)\n", "print(kf)\n", "for i in kf.split(X):\n", " print(i)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "** Leave One Out (LOO) ** - LeaveOneOut (or LOO) is a simple cross-validation. Each learning set is created by taking all the samples except one, the test set being the sample left out. Thus, for n samples, we have n different training sets and n different tests set. This cross-validation procedure does not waste much data as only one sample is removed from the training set:" ] }, { "cell_type": "code", "execution_count": 12, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "LeaveOneOut()\n", "(array([1, 2, 3, 4]), array([0]))\n", "(array([0, 2, 3, 4]), array([1]))\n", "(array([0, 1, 3, 4]), array([2]))\n", "(array([0, 1, 2, 4]), array([3]))\n", "(array([0, 1, 2, 3]), array([4]))\n" ] } ], "source": [ "X = [1,2,3,4,5]\n", "loo = LeaveOneOut()\n", "print(loo)\n", "for i in loo.split(X):\n", " print(i)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "** Leave P Out (LPO) ** - LeavePOut is very similar to LeaveOneOut as it creates all the possible training/test sets by removing p samples from the complete set. For n samples, this produces {n \\choose p} train-test pairs. Unlike LeaveOneOut and KFold, the test sets will overlap for p > 1" ] }, { "cell_type": "code", "execution_count": 13, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "LeavePOut(p=3)\n", "(array([3, 4]), array([0, 1, 2]))\n", "(array([2, 4]), array([0, 1, 3]))\n", "(array([2, 3]), array([0, 1, 4]))\n", "(array([1, 4]), array([0, 2, 3]))\n", "(array([1, 3]), array([0, 2, 4]))\n", "(array([1, 2]), array([0, 3, 4]))\n", "(array([0, 4]), array([1, 2, 3]))\n", "(array([0, 3]), array([1, 2, 4]))\n", "(array([0, 2]), array([1, 3, 4]))\n", "(array([0, 1]), array([2, 3, 4]))\n" ] } ], "source": [ "X = [1,2,3,4,5]\n", "loo = LeavePOut(p=3)\n", "print(loo)\n", "for i in loo.split(X):\n", " print(i)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "** Random permutations cross-validation a.k.a. Shuffle & Split ** - The ShuffleSplit iterator will generate a user defined number of independent train / test dataset splits. Samples are first shuffled and then split into a pair of train and test sets.\n", "\n", "It is possible to control the randomness for reproducibility of the results by explicitly seeding the random_state pseudo random number generator." ] }, { "cell_type": "code", "execution_count": 14, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "ShuffleSplit(n_splits=3, random_state=0, test_size=0.25, train_size=None)\n", "(array([1, 3, 4]), array([2, 0]))\n", "(array([1, 4, 3]), array([0, 2]))\n", "(array([4, 0, 2]), array([1, 3]))\n" ] } ], "source": [ "X = [1,2,3,4,5]\n", "loo = ShuffleSplit(n_splits=3, test_size=0.25,random_state=0)\n", "print(loo)\n", "for i in loo.split(X):\n", " print(i)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Some classification problems can exhibit a large imbalance in the distribution of the target classes: for instance there could be several times more negative samples than positive samples. In such cases it is recommended to use stratified sampling as implemented in StratifiedKFold and StratifiedShuffleSplit to ensure that relative class frequencies is approximately preserved in each train and validation fold. \n", "\n", "** Stratified k-fold ** \n", "StratifiedKFold is a variation of k-fold which returns stratified folds: each set contains approximately the same percentage of samples of each target class as the complete set." ] }, { "cell_type": "code", "execution_count": 16, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "(array([2, 3, 6, 7, 8, 9]), array([0, 1, 4, 5]))\n", "(array([0, 1, 3, 4, 5, 8, 9]), array([2, 6, 7]))\n", "(array([0, 1, 2, 4, 5, 6, 7]), array([3, 8, 9]))\n" ] } ], "source": [ "X = np.ones(10)\n", "y = [0, 0, 0, 0, 1, 1, 1, 1, 1, 1]\n", "\n", "skf = StratifiedKFold(n_splits=3)\n", "for i in skf.split(X, y):\n", " print(i)" ] }, { "cell_type": "markdown", "metadata": { "collapsed": true }, "source": [ "** Stratified Shuffle Split ** \n", "StratifiedShuffleSplit is a variation of ShuffleSplit, which returns stratified splits, i.e which creates splits by preserving the same percentage for each target class as in the complete set." ] }, { "cell_type": "code", "execution_count": 19, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "(array([1, 9, 8, 2, 3, 7, 4], dtype=int64), array([5, 6, 0], dtype=int64))\n", "(array([5, 0, 1, 7, 6, 8, 2], dtype=int64), array([3, 9, 4], dtype=int64))\n", "(array([9, 1, 4, 5, 6, 0, 2], dtype=int64), array([7, 3, 8], dtype=int64))\n" ] } ], "source": [ "X = np.ones(10)\n", "y = [0, 0, 0, 0, 1, 1, 1, 1, 1, 1]\n", "\n", "skf = StratifiedShuffleSplit(n_splits=3, test_size=0.25, random_state=33)\n", "for i in skf.split(X, y):\n", " print(i)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Cross-validation iterators for grouped data \n", "\n", "The i.i.d. assumption is broken if the underlying generative process yield groups of dependent samples.\n", "\n", "Such a grouping of data is domain specific. An example would be when there is medical data collected from multiple patients, with multiple samples taken from each patient. And such data is likely to be dependent on the individual group. In our example, the patient id for each sample will be its group identifier.\n", "\n", "In this case we would like to know if a model trained on a particular set of groups generalizes well to the unseen groups. To measure this, we need to ensure that all the samples in the validation fold come from groups that are not represented at all in the paired training fold.\n", "\n", "The following cross-validation splitters can be used to do that. The grouping identifier for the samples is specified via the groups parameter. \n", "\n", "** Group k-fold ** \n", "class:GroupKFold is a variation of k-fold which ensures that the same group is not represented in both testing and training sets. For example if the data is obtained from different subjects with several samples per-subject and if the model is flexible enough to learn from highly person specific features it could fail to generalize to new subjects. class:GroupKFold makes it possible to detect this kind of overfitting situations." ] }, { "cell_type": "code", "execution_count": 21, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[0 1 2 3 4 5] [6 7 8 9]\n", "[0 1 2 6 7 8 9] [3 4 5]\n", "[3 4 5 6 7 8 9] [0 1 2]\n" ] } ], "source": [ "X = [0.1, 0.2, 2.2, 2.4, 2.3, 4.55, 5.8, 8.8, 9, 10]\n", "y = [\"a\", \"b\", \"b\", \"b\", \"c\", \"c\", \"c\", \"d\", \"d\", \"d\"]\n", "groups = [1, 1, 1, 2, 2, 2, 3, 3, 3, 3]\n", "\n", "gkf = GroupKFold(n_splits=3)\n", "for train, test in gkf.split(X, y, groups=groups):\n", " print(\"%s %s\" % (train, test))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "** LeaveOneGroupOut ** \n", "LeaveOneGroupOut is a cross-validation scheme which holds out the samples according to a third-party provided array of integer groups. This group information can be used to encode arbitrary domain specific pre-defined cross-validation folds.\n", "\n", "Each training set is thus constituted by all the samples except the ones related to a specific group." ] }, { "cell_type": "code", "execution_count": 23, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[3 4 5 6 7 8 9] [0 1 2]\n", "[0 1 2 6 7 8 9] [3 4 5]\n", "[0 1 2 3 4 5] [6 7 8 9]\n" ] } ], "source": [ "X = [0.1, 0.2, 2.2, 2.4, 2.3, 4.55, 5.8, 8.8, 9, 10]\n", "y = [\"a\", \"b\", \"b\", \"b\", \"c\", \"c\", \"c\", \"d\", \"d\", \"d\"]\n", "groups = [1, 1, 1, 2, 2, 2, 3, 3, 3, 3]\n", "\n", "gkf = LeaveOneGroupOut()\n", "for train, test in gkf.split(X, y, groups=groups):\n", " print(\"%s %s\" % (train, test))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "** Leave P Groups Out ** \n", "LeavePGroupsOut is similar as LeaveOneGroupOut, but removes samples related to P groups for each training/test set." ] }, { "cell_type": "code", "execution_count": 30, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[6 7 8 9] [0 1 2 3 4 5]\n", "[3 4 5] [0 1 2 6 7 8 9]\n", "[0 1 2] [3 4 5 6 7 8 9]\n" ] } ], "source": [ "X = [0.1, 0.2, 2.2, 2.4, 2.3, 4.55, 5.8, 8.8, 9, 10]\n", "y = [\"a\", \"b\", \"b\", \"b\", \"c\", \"c\", \"c\", \"d\", \"d\", \"d\"]\n", "groups = [1, 1, 1, 2, 2, 2, 3, 3, 3, 3]\n", "\n", "gkf = LeavePGroupsOut(n_groups=2)\n", "for train, test in gkf.split(X, y, groups=groups):\n", " print(\"%s %s\" % (train, test))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "** Group Shuffle Split ** \n", "The GroupShuffleSplit iterator behaves as a combination of ShuffleSplit and LeavePGroupsOut, and generates a sequence of randomized partitions in which a subset of groups are held out for each split." ] }, { "cell_type": "code", "execution_count": 33, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[0 1 2] [3 4 5 6 7 8 9]\n", "[0 1 2] [3 4 5 6 7 8 9]\n", "[6 7 8 9] [0 1 2 3 4 5]\n", "[3 4 5] [0 1 2 6 7 8 9]\n" ] } ], "source": [ "X = [0.1, 0.2, 2.2, 2.4, 2.3, 4.55, 5.8, 8.8, 9, 10]\n", "y = [\"a\", \"b\", \"b\", \"b\", \"c\", \"c\", \"c\", \"d\", \"d\", \"d\"]\n", "groups = [1, 1, 1, 2, 2, 2, 3, 3, 3, 3]\n", "\n", "gkf = GroupShuffleSplit(n_splits=4, test_size=0.5, random_state=33)\n", "for train, test in gkf.split(X, y, groups=groups):\n", " print(\"%s %s\" % (train, test))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "** Time Series Split ** \n", "TimeSeriesSplit is a variation of k-fold which returns first k folds as train set and the (k+1) th fold as test set. Note that unlike standard cross-validation methods, successive training sets are supersets of those that come before them. Also, it adds all surplus data to the first training partition, which is always used to train the model.\n", "\n", "This class can be used to cross-validate time series data samples that are observed at fixed time intervals." ] }, { "cell_type": "code", "execution_count": 35, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "TimeSeriesSplit(n_splits=3)\n", "[0 1 2] [3]\n", "[0 1 2 3] [4]\n", "[0 1 2 3 4] [5]\n" ] } ], "source": [ "X = np.array([[1, 2], [3, 4], [1, 2], [3, 4], [1, 2], [3, 4]])\n", "y = np.array([1, 2, 3, 4, 5, 6])\n", "tscv = TimeSeriesSplit(n_splits=3)\n", "print(tscv) \n", "for train, test in tscv.split(X):\n", " print(\"%s %s\" % (train, test))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Model evaluation: quantifying the quality of predictions \n", "\n", "**Estimator score method:** Estimators have a score method providing a default evaluation criterion for the problem they are designed to solve. \n", "**Scoring parameter:** Model-evaluation tools using cross-validation (such as model_selection.cross_val_score and model_selection.GridSearchCV) rely on an internal scoring strategy. \n", "**Metric functions:** The metrics module implements functions assessing prediction error for specific purposes." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [] } ], "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.5.2" } }, "nbformat": 4, "nbformat_minor": 0 }