{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Introduction" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In this document I'll show a python implementation of *stacked generalization* (or *stacking*), an ensemble technique introduced in [Wolpert, David H., 1992. Stacked generalization, Neural Networks, Volume 5, Issue 2, Pages 241-259].\n", "Stacking uses cross validation to combine the results of several predictive models to improve their accuracy. \n", "\n", "A particular case of stacked generalization (*blending*) was used by the winners of the Netflix Prize (http://www.netflixprize.com/assets/GrandPrize2009_BPC_BigChaos.pdf). Ensemble techniques are also extremely popular in several other competitions like the ones hosted on Kaggle. More important, these methods usually perform very well also on \"real world\" predictive modeling tasks. Stacked generalization is particularly effective when we have datasets describing different aspects of the \"thing\" we are trying to predict (eg. a dataset of patients' signals). [Olivetti et. at. 2014. MEG Decoding Across Subjects](http://arxiv.org/abs/1404.4175) - [and a related Kaggle competition](https://www.kaggle.com/c/decoding-the-human-brain) - is an example of using stacking to build a robust predictor across subjects. " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Stacked Generalization" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In its original formulation, the method works as follows:\n", "\n", "1. Split a dataset set into two disjoint sets (train/test).\n", "2. Train and test $k$ models, with *cross validation*, on the first part. These are called **level-0 models**\n", "3. Build train and test **level-1 datasets**, using the predictions from 2) as inputs\n", "4. Train a higher level model (**level-1 model**) on the **level 1 data** from 3) and use it to predict unseen instances from the test set in 1.\n", "\n", "A complement to Wolpert's work is [Ting, Witten 1998. Issues in Stacked Generalization http://arxiv.org/pdf/1105.5466.pdf]; this paper presents empirical results that fill in on what Wolpert described as \"black art\". These can be considered a sort of \"best practices\" for stacking. In particular:\n", "1. Logistic Regression performs well as the level-1 model\n", "2. For classification tasks, build level-1 data using class probabilities rather than the predicted class labels.\n", "3. Like any ensemble method, stacking is ideal for parallel computation\n", "4. Stacking can work well with just two or three level-0 models\n", "\n", "In terms of potential pitfalls, the common issue with loss of interpretability in model ensembles comes to mind. [Perlich, Swirszcz 2010](http://www.sigkdd.org/sites/default/files/issues/12-2-2010-12/v12-02-4-UR-Perlich.pdf) suggest tha cross validation and stacking should be handled with care (eg. use stratified k-fold to improve robustness) when the dataset is skewed (eg. very small number of positive examples). " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Data" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "I'm not really interested in the method performance, so I'll create an artificial dataset to experiment with a classification task. " ] }, { "cell_type": "code", "execution_count": 69, "metadata": { "collapsed": false }, "outputs": [], "source": [ "from sklearn.cross_validation import train_test_split, StratifiedKFold\n", "from sklearn.metrics import accuracy_score\n", "from sklearn.datasets import make_classification\n", "import numpy as np\n", "\n", "n_features = 20\n", "n_samples = 10000\n", "\n", "X, y = make_classification(n_features=n_features, n_samples=n_samples)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Divide the dataset into a 75% - 25% training/test split to satisfy Step 1." ] }, { "cell_type": "code", "execution_count": 70, "metadata": { "collapsed": true }, "outputs": [], "source": [ "X_train, X_test, y_train, y_test = train_test_split(X, y)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Cross validation will be carried out by means of stratified k-fold." ] }, { "cell_type": "code", "execution_count": 71, "metadata": { "collapsed": false }, "outputs": [], "source": [ "skf = StratifiedKFold(y_test, n_folds=3)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Models" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "I'm using decision trees (cart) as level-0 classifiers" ] }, { "cell_type": "code", "execution_count": 72, "metadata": { "collapsed": false }, "outputs": [], "source": [ "from sklearn.tree import DecisionTreeClassifier\n", "\n", "n_models = 3\n", "clfs = [DecisionTreeClassifier()] * n_models" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "and logistic regression as the level 1 model" ] }, { "cell_type": "code", "execution_count": 74, "metadata": { "collapsed": true }, "outputs": [], "source": [ "from sklearn.linear_model import LogisticRegression \n", "lr = LogisticRegression()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Iterative version" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We start the process by training and testing a classification tree $M_k^{-j}$ on a training set $L^{-j}$, for each fold $j$. We use the predictions of these models to build the level-1 dataset $L_{cv}$ that is the train set for the level-1 classifier $\\tilde{M}$. In this loop we also take care of building a level-1 test set for $\\tilde{M}$, by collecting the predictions of each models $M_k^{-j}$ on unseen instances (X_test).\n", "\n", "The code comments follow [Ting, Witten 1998] naming conventions." ] }, { "cell_type": "code", "execution_count": 75, "metadata": { "collapsed": false }, "outputs": [], "source": [ "level_1_train = np.zeros((X_train.shape[0], len(clfs)))\n", "level_1_test = np.zeros((X_test.shape[0], len(clfs), len(skf)))" ] }, { "cell_type": "code", "execution_count": 105, "metadata": { "collapsed": false }, "outputs": [], "source": [ "for k, clf in enumerate(clfs):\n", " for j, (train_index, test_index) in enumerate(skf):\n", " # L^(-j), L_j \n", " X_train_cv, X_test_cv = X_train[train_index], X_test[test_index]\n", " y_train_cv, y_test_cv = y_train[train_index], y_test[test_index]\n", " \n", " # M_k^(-j) - level 0 model (M_k) on the training set L^{-j}\n", " clf.fit(X_train_cv, y_train_cv)\n", " \n", " # L_cv = z_kj \n", " # we use this dataset to train the level-1 model \n", " # this is a 2-class problems, so we consider only the probability\n", " # p of class 0. \n", " level_1_train[test_index, k] = clf.predict_proba(X_test_cv)[:, 0]\n", " \n", " # We build a level-1 test set to be used with the level 1 classifier.\n", " # This is the output of model M_k^(-j) on the held out test set\n", " level_1_test[:, k, j] = clf.predict_proba(X_test)[:, 0]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We conclude the training process by fitting a logistic regression on level-1 data." ] }, { "cell_type": "code", "execution_count": 81, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "LogisticRegression(C=1.0, class_weight=None, dual=False, fit_intercept=True,\n", " intercept_scaling=1, penalty='l2', random_state=None, tol=0.0001)" ] }, "execution_count": 81, "metadata": {}, "output_type": "execute_result" } ], "source": [ "lr.fit(level_1_train, y_train)" ] }, { "cell_type": "markdown", "metadata": { "collapsed": true }, "source": [ "Finally we predict labels on the level-1 test set. The per-fold classifiers predictions of each model $M_k^{-j}$ are blended using their mean as a combiner. This leads to what [Ting, Witten 1998] refer to as *final level-0 models* $M_k$." ] }, { "cell_type": "code", "execution_count": 82, "metadata": { "collapsed": false }, "outputs": [], "source": [ "pred = lr.predict(level_1_test.mean(2))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Parallel version" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Cross validation does not require any form of comunication between the models being trained. This makes stacked generalization a good candidate for parallelization." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In this section I'll be using [joblib](https://pythonhosted.org/joblib/parallel.html#working-with-numerical-data-in-shared-memory-memmaping), a frontend to the [multiprocessing](https://docs.python.org/2/library/multiprocessing.html) framework, to paralleize the training/testing of level-0 models as well as the generation of level 1 data. The results of parallel computations are written to shared, mem-mapped, *ndarray*s. In general this is **not** a good idea; numpy does not provide atomic operations and writes to shared segments can lead to data corruption. However, in this specific case we can rely on the fact that each classifier $k$ and fold $j$ are allocated exclusive segments of the shared *ndarray*s." ] }, { "cell_type": "code", "execution_count": 107, "metadata": { "collapsed": true }, "outputs": [], "source": [ "from joblib import Parallel, delayed\n", "from joblib import load, dump, cpu_count\n", "\n", "import tempfile\n", "import shutil\n", "import os\n", "import numpy as np" ] }, { "cell_type": "code", "execution_count": 13, "metadata": { "collapsed": true }, "outputs": [], "source": [ "mmap_dir = tempfile.mkdtemp()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "X_train, X_test, y_train, y_test have been defined above. \n", "\n", "For each input dataset, I'm releaseing the reference on the original in memory array (dump) and replacing it with a reference to the mem mapped ndarray. gc.collect() is called in Parallel just before forking. joblib.dump crashes Ipython Notebook, so for the sake of this example I **will not** mmap input dataset. I leave to code here as a template for future reuse." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "{python}\n", "X_train = np.memmap(os.path.join(mmap_dir, \"X_train\"), \n", " shape=X_train.shape,\n", " mode='w+')\n", "dump(X_train, os.path.join(mmap_dir, \"X_train\"))\n", "X_train = load(os.path.join(mmap_dir, \"X_train\"), mmap_mode='r')\n", "\n", "X_test = np.memmap(os.path.join(mmap_dir, \"X_test\"), \n", " shape=X_test.shape,\n", " mode='w+')\n", "dump(X_test, os.path.join(mmap_dir, \"X_test\"))\n", "X_test = load(os.path.join(mmap_dir, \"X_test\"), mmap_mode='r')\n", "\n", "y_train = np.memmap(os.path.join(mmap_dir, \"y_train\"), \n", " shape=y_train.shape,\n", " mode='w+')\n", "dump(y_train, os.path.join(mmap_dir, \"y_train\"))\n", "y_train = load(os.path.join(mmap_dir, \"y_train\"), mmap_mode='r')\n", "\n", "y_test = np.memmap(os.path.join(mmap_dir, \"y_test\"), \n", " shape=y_train.shape,\n", " mode='w+')\n", "dump(y_test, os.path.join(mmap_dir, \"y_test\"))\n", "y_test = load(os.path.join(mmap_dir, \"y_test\"), mmap_mode='r')\n", "" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Output data." ] }, { "cell_type": "code", "execution_count": 92, "metadata": { "collapsed": false }, "outputs": [], "source": [ "level_1_train = np.memmap(os.path.join(mmap_dir, \"level_1_train\"), \n", " shape=(X_train.shape[0], len(clfs)),\n", " mode='w+')\n", "level_1_test = np.memmap(os.path.join(mmap_dir, \"level_1_test\"),\n", " shape=(X_test.shape[0], len(clfs), len(skf)), \n", " mode='w+')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "cross_validate implements the training of level-0 models and generation of mem-mapped level-1 data." ] }, { "cell_type": "code", "execution_count": 106, "metadata": { "collapsed": true }, "outputs": [], "source": [ "def cross_validate(params):\n", " (level_1_train,\n", " level_1_test,\n", " X_train,\n", " X_test,\n", " y_train,\n", " y_test,\n", " train_index,\n", " test_index,\n", " k,\n", " j,\n", " clf\n", " ) = params\n", " \n", " X_train_cv, X_test_cv = X_train[train_index], X_test[test_index]\n", " y_train_cv, y_test_cv = y_train[train_index], y_test[test_index]\n", "\n", " clf.fit(X_train_cv, y_train_cv)\n", " \n", " level_1_train[test_index, k] = clf.predict_proba(X_test_cv)[:, 0]\n", " level_1_test[:,k,j] = clf.predict_proba(X_test)[:, 0]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can use list comprehension to generate a list of parameters to pass to cross_validate() via delayed(). Each element of the list, is itself a list containing the $k$ model and $j$ fold data.\n", "\n", "Note that we could be passing the $j$-th fold as eg. X_train[train_index] rather that the whole X_train. However, the function is supposed to use a mem-mapped version of the input data, hence we would pass a reference rather than a copy of the object." ] }, { "cell_type": "code", "execution_count": 100, "metadata": { "collapsed": false }, "outputs": [], "source": [ "params = [[level_1_train,\n", " level_1_test,\n", " X_train,\n", " X_test,\n", " y_train,\n", " y_test,\n", " train_index,\n", " test_index,\n", " k,\n", " j,\n", " clf] \n", " for k, clf in enumerate(clfs) \n", " for j, (train_index, test_index) in enumerate(skf)]" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "#n_jobs = max(1, min(cpu_count()-1, len(clfs)*len(skf)))\n", "n_jobs = 4" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "results = Parallel(n_jobs=n_jobs)(delayed(cross_validate)(param) for param in params)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Like in the iterative case, we use logistic regression as the level-1 model and predict unseen instances on the blended level-1 test set." ] }, { "cell_type": "code", "execution_count": 102, "metadata": { "collapsed": false }, "outputs": [], "source": [ "from sklearn.linear_model import LogisticRegression \n", "lr = LogisticRegression()\n", "lr.fit(level_1_train, y_train)\n", "pred = lr.predict(level_1_test.mean(2))" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false }, "source": [ "At last we clean up mmap data" ] }, { "cell_type": "code", "execution_count": 103, "metadata": { "collapsed": false }, "outputs": [], "source": [ "shutil.rmtree(mmap_dir)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Conclusion" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Is stacking a silver bullet that improves classification accuracy in every possible task? No, as it is the case with predictive modeling, performance depends on a number of factors. YMMV." ] } ], "metadata": { "kernelspec": { "display_name": "Python 2", "language": "python", "name": "python2" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 2 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython2", "version": "2.7.11" } }, "nbformat": 4, "nbformat_minor": 0 }