{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "![ML Logo](http://spark-mooc.github.io/web-assets/images/CS190.1x_Banner_300.png)\n", "# **Click-Through Rate Prediction Lab**\n", "#### This lab covers the steps for creating a click-through rate (CTR) prediction pipeline. You will work with the [Criteo Labs](http://labs.criteo.com/) dataset that was used for a recent [Kaggle competition](https://www.kaggle.com/c/criteo-display-ad-challenge).\n", "#### ** This lab will cover: **\n", "+ ####*Part 1:* Featurize categorical data using one-hot-encoding (OHE)\n", "+ ####*Part 2:* Construct an OHE dictionary\n", "+ ####*Part 3:* Parse CTR data and generate OHE features\n", " + #### *Visualization 1:* Feature frequency\n", "+ ####*Part 4:* CTR prediction and logloss evaluation\n", " + #### *Visualization 2:* ROC curve\n", "+ ####*Part 5:* Reduce feature dimension via feature hashing\n", " + #### *Visualization 3:* Hyperparameter heat map\n", " \n", "#### Note that, for reference, you can look up the details of the relevant Spark methods in [Spark's Python API](https://spark.apache.org/docs/latest/api/python/pyspark.html#pyspark.RDD) and the relevant NumPy methods in the [NumPy Reference](http://docs.scipy.org/doc/numpy/reference/index.html)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "labVersion = 'cs190_week4_v_1_3'" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### ** Part 1: Featurize categorical data using one-hot-encoding **" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### ** (1a) One-hot-encoding **\n", "#### We would like to develop code to convert categorical features to numerical ones, and to build intuition, we will work with a sample unlabeled dataset with three data points, with each data point representing an animal. The first feature indicates the type of animal (bear, cat, mouse); the second feature describes the animal's color (black, tabby); and the third (optional) feature describes what the animal eats (mouse, salmon).\n", "#### In a one-hot-encoding (OHE) scheme, we want to represent each tuple of `(featureID, category)` via its own binary feature. We can do this in Python by creating a dictionary that maps each tuple to a distinct integer, where the integer corresponds to a binary feature. To start, manually enter the entries in the OHE dictionary associated with the sample dataset by mapping the tuples to consecutive integers starting from zero, ordering the tuples first by featureID and next by category.\n", "#### Later in this lab, we'll use OHE dictionaries to transform data points into compact lists of features that can be used in machine learning algorithms." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# Data for manual OHE\n", "# Note: the first data point does not include any value for the optional third feature\n", "sampleOne = [(0, 'mouse'), (1, 'black')]\n", "sampleTwo = [(0, 'cat'), (1, 'tabby'), (2, 'mouse')]\n", "sampleThree = [(0, 'bear'), (1, 'black'), (2, 'salmon')]\n", "sampleDataRDD = sc.parallelize([sampleOne, sampleTwo, sampleThree])" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# TODO: Replace with appropriate code\n", "sampleOHEDictManual = {}\n", "sampleOHEDictManual[(0,'bear')] = \n", "sampleOHEDictManual[(0,'cat')] = \n", "sampleOHEDictManual[(0,'mouse')] = \n", "sampleOHEDictManual\n", "sampleOHEDictManual\n", "sampleOHEDictManual\n", "sampleOHEDictManual" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# TEST One-hot-encoding (1a)\n", "from test_helper import Test\n", "\n", "Test.assertEqualsHashed(sampleOHEDictManual[(0,'bear')],\n", " 'b6589fc6ab0dc82cf12099d1c2d40ab994e8410c',\n", " \"incorrect value for sampleOHEDictManual[(0,'bear')]\")\n", "Test.assertEqualsHashed(sampleOHEDictManual[(0,'cat')],\n", " '356a192b7913b04c54574d18c28d46e6395428ab',\n", " \"incorrect value for sampleOHEDictManual[(0,'cat')]\")\n", "Test.assertEqualsHashed(sampleOHEDictManual[(0,'mouse')],\n", " 'da4b9237bacccdf19c0760cab7aec4a8359010b0',\n", " \"incorrect value for sampleOHEDictManual[(0,'mouse')]\")\n", "Test.assertEqualsHashed(sampleOHEDictManual[(1,'black')],\n", " '77de68daecd823babbb58edb1c8e14d7106e83bb',\n", " \"incorrect value for sampleOHEDictManual[(1,'black')]\")\n", "Test.assertEqualsHashed(sampleOHEDictManual[(1,'tabby')],\n", " '1b6453892473a467d07372d45eb05abc2031647a',\n", " \"incorrect value for sampleOHEDictManual[(1,'tabby')]\")\n", "Test.assertEqualsHashed(sampleOHEDictManual[(2,'mouse')],\n", " 'ac3478d69a3c81fa62e60f5c3696165a4e5e6ac4',\n", " \"incorrect value for sampleOHEDictManual[(2,'mouse')]\")\n", "Test.assertEqualsHashed(sampleOHEDictManual[(2,'salmon')],\n", " 'c1dfd96eea8cc2b62785275bca38ac261256e278',\n", " \"incorrect value for sampleOHEDictManual[(2,'salmon')]\")\n", "Test.assertEquals(len(sampleOHEDictManual.keys()), 7,\n", " 'incorrect number of keys in sampleOHEDictManual')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### ** (1b) Sparse vectors **\n", "#### Data points can typically be represented with a small number of non-zero OHE features relative to the total number of features that occur in the dataset. By leveraging this sparsity and using sparse vector representations of OHE data, we can reduce storage and computational burdens. Below are a few sample vectors represented as dense numpy arrays. Use [SparseVector](https://spark.apache.org/docs/latest/api/python/pyspark.mllib.html#pyspark.mllib.linalg.SparseVector) to represent them in a sparse fashion, and verify that both the sparse and dense representations yield the same results when computing [dot products](http://en.wikipedia.org/wiki/Dot_product) (we will later use MLlib to train classifiers via gradient descent, and MLlib will need to compute dot products between SparseVectors and dense parameter vectors).\n", "#### Use `SparseVector(size, *args)` to create a new sparse vector where size is the length of the vector and args is either a dictionary, a list of (index, value) pairs, or two separate arrays of indices and values (sorted by index). You'll need to create a sparse vector representation of each dense vector `aDense` and `bDense`." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import numpy as np\n", "from pyspark.mllib.linalg import SparseVector" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# TODO: Replace with appropriate code\n", "aDense = np.array([0., 3., 0., 4.])\n", "aSparse = \n", "\n", "bDense = np.array([0., 0., 0., 1.])\n", "bSparse = \n", "\n", "w = np.array([0.4, 3.1, -1.4, -.5])\n", "print aDense.dot(w)\n", "print aSparse.dot(w)\n", "print bDense.dot(w)\n", "print bSparse.dot(w)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# TEST Sparse Vectors (1b)\n", "Test.assertTrue(isinstance(aSparse, SparseVector), 'aSparse needs to be an instance of SparseVector')\n", "Test.assertTrue(isinstance(bSparse, SparseVector), 'aSparse needs to be an instance of SparseVector')\n", "Test.assertTrue(aDense.dot(w) == aSparse.dot(w),\n", " 'dot product of aDense and w should equal dot product of aSparse and w')\n", "Test.assertTrue(bDense.dot(w) == bSparse.dot(w),\n", " 'dot product of bDense and w should equal dot product of bSparse and w')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### **(1c) OHE features as sparse vectors **\n", "#### Now let's see how we can represent the OHE features for points in our sample dataset. Using the mapping defined by the OHE dictionary from Part (1a), manually define OHE features for the three sample data points using SparseVector format. Any feature that occurs in a point should have the value 1.0. For example, the `DenseVector` for a point with features 2 and 4 would be `[0.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0]`." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# Reminder of the sample features\n", "# sampleOne = [(0, 'mouse'), (1, 'black')]\n", "# sampleTwo = [(0, 'cat'), (1, 'tabby'), (2, 'mouse')]\n", "# sampleThree = [(0, 'bear'), (1, 'black'), (2, 'salmon')]" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# TODO: Replace with appropriate code\n", "sampleOneOHEFeatManual = \n", "sampleTwoOHEFeatManual = \n", "sampleThreeOHEFeatManual = " ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# TEST OHE Features as sparse vectors (1c)\n", "Test.assertTrue(isinstance(sampleOneOHEFeatManual, SparseVector),\n", " 'sampleOneOHEFeatManual needs to be a SparseVector')\n", "Test.assertTrue(isinstance(sampleTwoOHEFeatManual, SparseVector),\n", " 'sampleTwoOHEFeatManual needs to be a SparseVector')\n", "Test.assertTrue(isinstance(sampleThreeOHEFeatManual, SparseVector),\n", " 'sampleThreeOHEFeatManual needs to be a SparseVector')\n", "Test.assertEqualsHashed(sampleOneOHEFeatManual,\n", " 'ecc00223d141b7bd0913d52377cee2cf5783abd6',\n", " 'incorrect value for sampleOneOHEFeatManual')\n", "Test.assertEqualsHashed(sampleTwoOHEFeatManual,\n", " '26b023f4109e3b8ab32241938e2e9b9e9d62720a',\n", " 'incorrect value for sampleTwoOHEFeatManual')\n", "Test.assertEqualsHashed(sampleThreeOHEFeatManual,\n", " 'c04134fd603ae115395b29dcabe9d0c66fbdc8a7',\n", " 'incorrect value for sampleThreeOHEFeatManual')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### **(1d) Define a OHE function **\n", "#### Next we will use the OHE dictionary from Part (1a) to programatically generate OHE features from the original categorical data. First write a function called `oneHotEncoding` that creates OHE feature vectors in `SparseVector` format. Then use this function to create OHE features for the first sample data point and verify that the result matches the result from Part (1c)." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# TODO: Replace with appropriate code\n", "def oneHotEncoding(rawFeats, OHEDict, numOHEFeats):\n", " \"\"\"Produce a one-hot-encoding from a list of features and an OHE dictionary.\n", "\n", " Note:\n", " You should ensure that the indices used to create a SparseVector are sorted.\n", "\n", " Args:\n", " rawFeats (list of (int, str)): The features corresponding to a single observation. Each\n", " feature consists of a tuple of featureID and the feature's value. (e.g. sampleOne)\n", " OHEDict (dict): A mapping of (featureID, value) to unique integer.\n", " numOHEFeats (int): The total number of unique OHE features (combinations of featureID and\n", " value).\n", "\n", " Returns:\n", " SparseVector: A SparseVector of length numOHEFeats with indicies equal to the unique\n", " identifiers for the (featureID, value) combinations that occur in the observation and\n", " with values equal to 1.0.\n", " \"\"\"\n", " \n", "\n", "# Calculate the number of features in sampleOHEDictManual\n", "numSampleOHEFeats = \n", "\n", "# Run oneHotEnoding on sampleOne\n", "sampleOneOHEFeat = \n", "\n", "print sampleOneOHEFeat" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# TEST Define an OHE Function (1d)\n", "Test.assertTrue(sampleOneOHEFeat == sampleOneOHEFeatManual,\n", " 'sampleOneOHEFeat should equal sampleOneOHEFeatManual')\n", "Test.assertEquals(sampleOneOHEFeat, SparseVector(7, [2,3], [1.0,1.0]),\n", " 'incorrect value for sampleOneOHEFeat')\n", "Test.assertEquals(oneHotEncoding([(1, 'black'), (0, 'mouse')], sampleOHEDictManual,\n", " numSampleOHEFeats), SparseVector(7, [2,3], [1.0,1.0]),\n", " 'incorrect definition for oneHotEncoding')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### **(1e) Apply OHE to a dataset **\n", "#### Finally, use the function from Part (1d) to create OHE features for all 3 data points in the sample dataset." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# TODO: Replace with appropriate code\n", "sampleOHEData = sampleDataRDD.\n", "print sampleOHEData.collect()" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# TEST Apply OHE to a dataset (1e)\n", "sampleOHEDataValues = sampleOHEData.collect()\n", "Test.assertTrue(len(sampleOHEDataValues) == 3, 'sampleOHEData should have three elements')\n", "Test.assertEquals(sampleOHEDataValues[0], SparseVector(7, {2: 1.0, 3: 1.0}),\n", " 'incorrect OHE for first sample')\n", "Test.assertEquals(sampleOHEDataValues[1], SparseVector(7, {1: 1.0, 4: 1.0, 5: 1.0}),\n", " 'incorrect OHE for second sample')\n", "Test.assertEquals(sampleOHEDataValues[2], SparseVector(7, {0: 1.0, 3: 1.0, 6: 1.0}),\n", " 'incorrect OHE for third sample')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### ** Part 2: Construct an OHE dictionary **" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### **(2a) Pair RDD of `(featureID, category)` **\n", "#### To start, create an RDD of distinct `(featureID, category)` tuples. In our sample dataset, the 7 items in the resulting RDD are `(0, 'bear')`, `(0, 'cat')`, `(0, 'mouse')`, `(1, 'black')`, `(1, 'tabby')`, `(2, 'mouse')`, `(2, 'salmon')`. Notably `'black'` appears twice in the dataset but only contributes one item to the RDD: `(1, 'black')`, while `'mouse'` also appears twice and contributes two items: `(0, 'mouse')` and `(2, 'mouse')`. Use [flatMap](https://spark.apache.org/docs/latest/api/python/pyspark.html#pyspark.RDD.flatMap) and [distinct](https://spark.apache.org/docs/latest/api/python/pyspark.html#pyspark.RDD.distinct)." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# TODO: Replace with appropriate code\n", "sampleDistinctFeats = (sampleDataRDD\n", " )" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# TEST Pair RDD of (featureID, category) (2a)\n", "Test.assertEquals(sorted(sampleDistinctFeats.collect()),\n", " [(0, 'bear'), (0, 'cat'), (0, 'mouse'), (1, 'black'),\n", " (1, 'tabby'), (2, 'mouse'), (2, 'salmon')],\n", " 'incorrect value for sampleDistinctFeats')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### ** (2b) OHE Dictionary from distinct features **\n", "#### Next, create an `RDD` of key-value tuples, where each `(featureID, category)` tuple in `sampleDistinctFeats` is a key and the values are distinct integers ranging from 0 to (number of keys - 1). Then convert this `RDD` into a dictionary, which can be done using the `collectAsMap` action. Note that there is no unique mapping from keys to values, as all we require is that each `(featureID, category)` key be mapped to a unique integer between 0 and the number of keys. In this exercise, any valid mapping is acceptable. Use [zipWithIndex](https://spark.apache.org/docs/latest/api/python/pyspark.html#pyspark.RDD.zipWithIndex) followed by [collectAsMap](https://spark.apache.org/docs/latest/api/python/pyspark.html#pyspark.RDD.collectAsMap).\n", "#### In our sample dataset, one valid list of key-value tuples is: `[((0, 'bear'), 0), ((2, 'salmon'), 1), ((1, 'tabby'), 2), ((2, 'mouse'), 3), ((0, 'mouse'), 4), ((0, 'cat'), 5), ((1, 'black'), 6)]`. The dictionary defined in Part (1a) illustrates another valid mapping between keys and integers." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# TODO: Replace with appropriate code\n", "sampleOHEDict = (sampleDistinctFeats\n", " )\n", "print sampleOHEDict" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# TEST OHE Dictionary from distinct features (2b)\n", "Test.assertEquals(sorted(sampleOHEDict.keys()),\n", " [(0, 'bear'), (0, 'cat'), (0, 'mouse'), (1, 'black'),\n", " (1, 'tabby'), (2, 'mouse'), (2, 'salmon')],\n", " 'sampleOHEDict has unexpected keys')\n", "Test.assertEquals(sorted(sampleOHEDict.values()), range(7), 'sampleOHEDict has unexpected values')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### **(2c) Automated creation of an OHE dictionary **\n", "#### Now use the code from Parts (2a) and (2b) to write a function that takes an input dataset and outputs an OHE dictionary. Then use this function to create an OHE dictionary for the sample dataset, and verify that it matches the dictionary from Part (2b)." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# TODO: Replace with appropriate code\n", "def createOneHotDict(inputData):\n", " \"\"\"Creates a one-hot-encoder dictionary based on the input data.\n", "\n", " Args:\n", " inputData (RDD of lists of (int, str)): An RDD of observations where each observation is\n", " made up of a list of (featureID, value) tuples.\n", "\n", " Returns:\n", " dict: A dictionary where the keys are (featureID, value) tuples and map to values that are\n", " unique integers.\n", " \"\"\"\n", " \n", "\n", "sampleOHEDictAuto = \n", "print sampleOHEDictAuto" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# TEST Automated creation of an OHE dictionary (2c)\n", "Test.assertEquals(sorted(sampleOHEDictAuto.keys()),\n", " [(0, 'bear'), (0, 'cat'), (0, 'mouse'), (1, 'black'),\n", " (1, 'tabby'), (2, 'mouse'), (2, 'salmon')],\n", " 'sampleOHEDictAuto has unexpected keys')\n", "Test.assertEquals(sorted(sampleOHEDictAuto.values()), range(7),\n", " 'sampleOHEDictAuto has unexpected values')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### **Part 3: Parse CTR data and generate OHE features**" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Before we can proceed, you'll first need to obtain the data from Criteo. If you have already completed this step in the setup lab, just run the cells below and the data will be loaded into the `rawData` variable.\n", "#### Below is Criteo's data sharing agreement. After you accept the agreement, you can obtain the download URL by right-clicking on the \"Download Sample\" button and clicking \"Copy link address\" or \"Copy Link Location\", depending on your browser. Paste the URL into the `# TODO` cell below. The file is 8.4 MB compressed. The script below will download the file to the virtual machine (VM) and then extract the data.\n", "#### If running the cell below does not render a webpage, open the [Criteo agreement](http://labs.criteo.com/downloads/2014-kaggle-display-advertising-challenge-dataset/) in a separate browser tab. After you accept the agreement, you can obtain the download URL by right-clicking on the \"Download Sample\" button and clicking \"Copy link address\" or \"Copy Link Location\", depending on your browser. Paste the URL into the `# TODO` cell below.\n", "#### Note that the download could take a few minutes, depending upon your connection speed." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# Run this code to view Criteo's agreement\n", "from IPython.lib.display import IFrame\n", "\n", "IFrame(\"http://labs.criteo.com/downloads/2014-kaggle-display-advertising-challenge-dataset/\",\n", " 600, 350)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# TODO: Replace with appropriate code\n", "# Just replace with the url for dac_sample.tar.gz\n", "import glob\n", "import os.path\n", "import tarfile\n", "import urllib\n", "import urlparse\n", "\n", "# Paste url, url should end with: dac_sample.tar.gz\n", "url = ''\n", "\n", "url = url.strip()\n", "baseDir = os.path.join('data')\n", "inputPath = os.path.join('cs190', 'dac_sample.txt')\n", "fileName = os.path.join(baseDir, inputPath)\n", "inputDir = os.path.split(fileName)[0]\n", "\n", "def extractTar(check = False):\n", " # Find the zipped archive and extract the dataset\n", " tars = glob.glob('dac_sample*.tar.gz*')\n", " if check and len(tars) == 0:\n", " return False\n", "\n", " if len(tars) > 0:\n", " try:\n", " tarFile = tarfile.open(tars[0])\n", " except tarfile.ReadError:\n", " if not check:\n", " print 'Unable to open tar.gz file. Check your URL.'\n", " return False\n", "\n", " tarFile.extract('dac_sample.txt', path=inputDir)\n", " print 'Successfully extracted: dac_sample.txt'\n", " return True\n", " else:\n", " print 'You need to retry the download with the correct url.'\n", " print ('Alternatively, you can upload the dac_sample.tar.gz file to your Jupyter root ' +\n", " 'directory')\n", " return False\n", "\n", "\n", "if os.path.isfile(fileName):\n", " print 'File is already available. Nothing to do.'\n", "elif extractTar(check = True):\n", " print 'tar.gz file was already available.'\n", "elif not url.endswith('dac_sample.tar.gz'):\n", " print 'Check your download url. Are you downloading the Sample dataset?'\n", "else:\n", " # Download the file and store it in the same directory as this notebook\n", " try:\n", " urllib.urlretrieve(url, os.path.basename(urlparse.urlsplit(url).path))\n", " except IOError:\n", " print 'Unable to download and store: {0}'.format(url)\n", "\n", " extractTar()" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import os.path\n", "baseDir = os.path.join('data')\n", "inputPath = os.path.join('cs190', 'dac_sample.txt')\n", "fileName = os.path.join(baseDir, inputPath)\n", "\n", "if os.path.isfile(fileName):\n", " rawData = (sc\n", " .textFile(fileName, 2)\n", " .map(lambda x: x.replace('\\t', ','))) # work with either ',' or '\\t' separated data\n", " print rawData.take(1)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### **(3a) Loading and splitting the data **\n", "#### We are now ready to start working with the actual CTR data, and our first task involves splitting it into training, validation, and test sets. Use the [randomSplit method](https://spark.apache.org/docs/latest/api/python/pyspark.html#pyspark.RDD.randomSplit) with the specified weights and seed to create RDDs storing each of these datasets, and then [cache](https://spark.apache.org/docs/latest/api/python/pyspark.html#pyspark.RDD.cache) each of these RDDs, as we will be accessing them multiple times in the remainder of this lab. Finally, compute the size of each dataset." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# TODO: Replace with appropriate code\n", "weights = [.8, .1, .1]\n", "seed = 42\n", "# Use randomSplit with weights and seed\n", "rawTrainData, rawValidationData, rawTestData = rawData.\n", "# Cache the data\n", "\n", "\n", "nTrain = \n", "nVal = \n", "nTest = \n", "print nTrain, nVal, nTest, nTrain + nVal + nTest\n", "print rawData.take(1)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# TEST Loading and splitting the data (3a)\n", "Test.assertTrue(all([rawTrainData.is_cached, rawValidationData.is_cached, rawTestData.is_cached]),\n", " 'you must cache the split data')\n", "Test.assertEquals(nTrain, 79911, 'incorrect value for nTrain')\n", "Test.assertEquals(nVal, 10075, 'incorrect value for nVal')\n", "Test.assertEquals(nTest, 10014, 'incorrect value for nTest')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### ** (3b) Extract features **\n", "#### We will now parse the raw training data to create an RDD that we can subsequently use to create an OHE dictionary. Note from the `take()` command in Part (3a) that each raw data point is a string containing several fields separated by some delimiter. For now, we will ignore the first field (which is the 0-1 label), and parse the remaining fields (or raw features). To do this, complete the implemention of the `parsePoint` function." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# TODO: Replace with appropriate code\n", "def parsePoint(point):\n", " \"\"\"Converts a comma separated string into a list of (featureID, value) tuples.\n", "\n", " Note:\n", " featureIDs should start at 0 and increase to the number of features - 1.\n", "\n", " Args:\n", " point (str): A comma separated string where the first value is the label and the rest\n", " are features.\n", "\n", " Returns:\n", " list: A list of (featureID, value) tuples.\n", " \"\"\"\n", " \n", "\n", "parsedTrainFeat = rawTrainData.map(parsePoint)\n", "\n", "numCategories = (parsedTrainFeat\n", " .flatMap(lambda x: x)\n", " .distinct()\n", " .map(lambda x: (x[0], 1))\n", " .reduceByKey(lambda x, y: x + y)\n", " .sortByKey()\n", " .collect())\n", "\n", "print numCategories[2][1]" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# TEST Extract features (3b)\n", "Test.assertEquals(numCategories[2][1], 855, 'incorrect implementation of parsePoint')\n", "Test.assertEquals(numCategories[32][1], 4, 'incorrect implementation of parsePoint')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### **(3c) Create an OHE dictionary from the dataset **\n", "#### Note that parsePoint returns a data point as a list of `(featureID, category)` tuples, which is the same format as the sample dataset studied in Parts 1 and 2 of this lab. Using this observation, create an OHE dictionary using the function implemented in Part (2c). Note that we will assume for simplicity that all features in our CTR dataset are categorical." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# TODO: Replace with appropriate code\n", "ctrOHEDict = \n", "numCtrOHEFeats = len(ctrOHEDict.keys())\n", "print numCtrOHEFeats\n", "print ctrOHEDict[(0, '')]" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# TEST Create an OHE dictionary from the dataset (3c)\n", "Test.assertEquals(numCtrOHEFeats, 233286, 'incorrect number of features in ctrOHEDict')\n", "Test.assertTrue((0, '') in ctrOHEDict, 'incorrect features in ctrOHEDict')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### ** (3d) Apply OHE to the dataset **\n", "#### Now let's use this OHE dictionary by starting with the raw training data and creating an RDD of [LabeledPoint](http://spark.apache.org/docs/1.3.1/api/python/pyspark.mllib.html#pyspark.mllib.regression.LabeledPoint) objects using OHE features. To do this, complete the implementation of the `parseOHEPoint` function. Hint: `parseOHEPoint` is an extension of the `parsePoint` function from Part (3b) and it uses the `oneHotEncoding` function from Part (1d)." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "from pyspark.mllib.regression import LabeledPoint" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# TODO: Replace with appropriate code\n", "def parseOHEPoint(point, OHEDict, numOHEFeats):\n", " \"\"\"Obtain the label and feature vector for this raw observation.\n", "\n", " Note:\n", " You must use the function `oneHotEncoding` in this implementation or later portions\n", " of this lab may not function as expected.\n", "\n", " Args:\n", " point (str): A comma separated string where the first value is the label and the rest\n", " are features.\n", " OHEDict (dict of (int, str) to int): Mapping of (featureID, value) to unique integer.\n", " numOHEFeats (int): The number of unique features in the training dataset.\n", "\n", " Returns:\n", " LabeledPoint: Contains the label for the observation and the one-hot-encoding of the\n", " raw features based on the provided OHE dictionary.\n", " \"\"\"\n", " \n", "\n", "OHETrainData = rawTrainData.map(lambda point: parseOHEPoint(point, ctrOHEDict, numCtrOHEFeats))\n", "OHETrainData.cache()\n", "print OHETrainData.take(1)\n", "\n", "# Check that oneHotEncoding function was used in parseOHEPoint\n", "backupOneHot = oneHotEncoding\n", "oneHotEncoding = None\n", "withOneHot = False\n", "try: parseOHEPoint(rawTrainData.take(1)[0], ctrOHEDict, numCtrOHEFeats)\n", "except TypeError: withOneHot = True\n", "oneHotEncoding = backupOneHot" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# TEST Apply OHE to the dataset (3d)\n", "numNZ = sum(parsedTrainFeat.map(lambda x: len(x)).take(5))\n", "numNZAlt = sum(OHETrainData.map(lambda lp: len(lp.features.indices)).take(5))\n", "Test.assertEquals(numNZ, numNZAlt, 'incorrect implementation of parseOHEPoint')\n", "Test.assertTrue(withOneHot, 'oneHotEncoding not present in parseOHEPoint')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### **Visualization 1: Feature frequency **\n", "#### We will now visualize the number of times each of the 233,286 OHE features appears in the training data. We first compute the number of times each feature appears, then bucket the features by these counts. The buckets are sized by powers of 2, so the first bucket corresponds to features that appear exactly once ( $ \\scriptsize 2^0 $ ), the second to features that appear twice ( $ \\scriptsize 2^1 $ ), the third to features that occur between three and four ( $ \\scriptsize 2^2 $ ) times, the fifth bucket is five to eight ( $ \\scriptsize 2^3 $ ) times and so on. The scatter plot below shows the logarithm of the bucket thresholds versus the logarithm of the number of features that have counts that fall in the buckets." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "def bucketFeatByCount(featCount):\n", " \"\"\"Bucket the counts by powers of two.\"\"\"\n", " for i in range(11):\n", " size = 2 ** i\n", " if featCount <= size:\n", " return size\n", " return -1\n", "\n", "featCounts = (OHETrainData\n", " .flatMap(lambda lp: lp.features.indices)\n", " .map(lambda x: (x, 1))\n", " .reduceByKey(lambda x, y: x + y))\n", "featCountsBuckets = (featCounts\n", " .map(lambda x: (bucketFeatByCount(x[1]), 1))\n", " .filter(lambda (k, v): k != -1)\n", " .reduceByKey(lambda x, y: x + y)\n", " .collect())\n", "print featCountsBuckets" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import matplotlib.pyplot as plt\n", "\n", "x, y = zip(*featCountsBuckets)\n", "x, y = np.log(x), np.log(y)\n", "\n", "def preparePlot(xticks, yticks, figsize=(10.5, 6), hideLabels=False, gridColor='#999999',\n", " gridWidth=1.0):\n", " \"\"\"Template for generating the plot layout.\"\"\"\n", " plt.close()\n", " fig, ax = plt.subplots(figsize=figsize, facecolor='white', edgecolor='white')\n", " ax.axes.tick_params(labelcolor='#999999', labelsize='10')\n", " for axis, ticks in [(ax.get_xaxis(), xticks), (ax.get_yaxis(), yticks)]:\n", " axis.set_ticks_position('none')\n", " axis.set_ticks(ticks)\n", " axis.label.set_color('#999999')\n", " if hideLabels: axis.set_ticklabels([])\n", " plt.grid(color=gridColor, linewidth=gridWidth, linestyle='-')\n", " map(lambda position: ax.spines[position].set_visible(False), ['bottom', 'top', 'left', 'right'])\n", " return fig, ax\n", "\n", "# generate layout and plot data\n", "fig, ax = preparePlot(np.arange(0, 10, 1), np.arange(4, 14, 2))\n", "ax.set_xlabel(r'$\\log_e(bucketSize)$'), ax.set_ylabel(r'$\\log_e(countInBucket)$')\n", "plt.scatter(x, y, s=14**2, c='#d6ebf2', edgecolors='#8cbfd0', alpha=0.75)\n", "pass" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### **(3e) Handling unseen features **\n", "#### We naturally would like to repeat the process from Part (3d), e.g., to compute OHE features for the validation and test datasets. However, we must be careful, as some categorical values will likely appear in new data that did not exist in the training data. To deal with this situation, update the `oneHotEncoding()` function from Part (1d) to ignore previously unseen categories, and then compute OHE features for the validation data." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# TODO: Replace with appropriate code\n", "def oneHotEncoding(rawFeats, OHEDict, numOHEFeats):\n", " \"\"\"Produce a one-hot-encoding from a list of features and an OHE dictionary.\n", "\n", " Note:\n", " If a (featureID, value) tuple doesn't have a corresponding key in OHEDict it should be\n", " ignored.\n", "\n", " Args:\n", " rawFeats (list of (int, str)): The features corresponding to a single observation. Each\n", " feature consists of a tuple of featureID and the feature's value. (e.g. sampleOne)\n", " OHEDict (dict): A mapping of (featureID, value) to unique integer.\n", " numOHEFeats (int): The total number of unique OHE features (combinations of featureID and\n", " value).\n", "\n", " Returns:\n", " SparseVector: A SparseVector of length numOHEFeats with indicies equal to the unique\n", " identifiers for the (featureID, value) combinations that occur in the observation and\n", " with values equal to 1.0.\n", " \"\"\"\n", " \n", "\n", "OHEValidationData = rawValidationData.map(lambda point: parseOHEPoint(point, ctrOHEDict, numCtrOHEFeats))\n", "OHEValidationData.cache()\n", "print OHEValidationData.take(1)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# TEST Handling unseen features (3e)\n", "numNZVal = (OHEValidationData\n", " .map(lambda lp: len(lp.features.indices))\n", " .sum())\n", "Test.assertEquals(numNZVal, 372080, 'incorrect number of features')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### ** Part 4: CTR prediction and logloss evaluation **" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### ** (4a) Logistic regression **\n", "#### We are now ready to train our first CTR classifier. A natural classifier to use in this setting is logistic regression, since it models the probability of a click-through event rather than returning a binary response, and when working with rare events, probabilistic predictions are useful. First use [LogisticRegressionWithSGD](https://spark.apache.org/docs/latest/api/python/pyspark.mllib.html#pyspark.mllib.classification.LogisticRegressionWithSGD) to train a model using `OHETrainData` with the given hyperparameter configuration. `LogisticRegressionWithSGD` returns a [LogisticRegressionModel](https://spark.apache.org/docs/latest/api/python/pyspark.mllib.html#pyspark.mllib.regression.LogisticRegressionModel). Next, use the `LogisticRegressionModel.weights` and `LogisticRegressionModel.intercept` attributes to print out the model's parameters. Note that these are the names of the object's attributes and should be called using a syntax like `model.weights` for a given `model`." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "from pyspark.mllib.classification import LogisticRegressionWithSGD\n", "\n", "# fixed hyperparameters\n", "numIters = 50\n", "stepSize = 10.\n", "regParam = 1e-6\n", "regType = 'l2'\n", "includeIntercept = True" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# TODO: Replace with appropriate code\n", "model0 = \n", "sortedWeights = sorted(model0.weights)\n", "print sortedWeights[:5], model0.intercept" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# TEST Logistic regression (4a)\n", "Test.assertTrue(np.allclose(model0.intercept, 0.56455084025), 'incorrect value for model0.intercept')\n", "Test.assertTrue(np.allclose(sortedWeights[0:5],\n", " [-0.45899236853575609, -0.37973707648623956, -0.36996558266753304,\n", " -0.36934962879928263, -0.32697945415010637]), 'incorrect value for model0.weights')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### ** (4b) Log loss **\n", "#### Throughout this lab, we will use log loss to evaluate the quality of models. Log loss is defined as: $$ \\begin{align} \\scriptsize \\ell_{log}(p, y) = \\begin{cases} -\\log (p) & \\text{if } y = 1 \\\\\\ -\\log(1-p) & \\text{if } y = 0 \\end{cases} \\end{align} $$ where $ \\scriptsize p$ is a probability between 0 and 1 and $ \\scriptsize y$ is a label of either 0 or 1. Log loss is a standard evaluation criterion when predicting rare-events such as click-through rate prediction (it is also the criterion used in the [Criteo Kaggle competition](https://www.kaggle.com/c/criteo-display-ad-challenge)). Write a function to compute log loss, and evaluate it on some sample inputs." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# TODO: Replace with appropriate code\n", "from math import log\n", "\n", "def computeLogLoss(p, y):\n", " \"\"\"Calculates the value of log loss for a given probabilty and label.\n", "\n", " Note:\n", " log(0) is undefined, so when p is 0 we need to add a small value (epsilon) to it\n", " and when p is 1 we need to subtract a small value (epsilon) from it.\n", "\n", " Args:\n", " p (float): A probabilty between 0 and 1.\n", " y (int): A label. Takes on the values 0 and 1.\n", "\n", " Returns:\n", " float: The log loss value.\n", " \"\"\"\n", " epsilon = 10e-12\n", " \n", "\n", "print computeLogLoss(.5, 1)\n", "print computeLogLoss(.5, 0)\n", "print computeLogLoss(.99, 1)\n", "print computeLogLoss(.99, 0)\n", "print computeLogLoss(.01, 1)\n", "print computeLogLoss(.01, 0)\n", "print computeLogLoss(0, 1)\n", "print computeLogLoss(1, 1)\n", "print computeLogLoss(1, 0)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# TEST Log loss (4b)\n", "Test.assertTrue(np.allclose([computeLogLoss(.5, 1), computeLogLoss(.01, 0), computeLogLoss(.01, 1)],\n", " [0.69314718056, 0.0100503358535, 4.60517018599]),\n", " 'computeLogLoss is not correct')\n", "Test.assertTrue(np.allclose([computeLogLoss(0, 1), computeLogLoss(1, 1), computeLogLoss(1, 0)],\n", " [25.3284360229, 1.00000008275e-11, 25.3284360229]),\n", " 'computeLogLoss needs to bound p away from 0 and 1 by epsilon')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### ** (4c) Baseline log loss **\n", "#### Next we will use the function we wrote in Part (4b) to compute the baseline log loss on the training data. A very simple yet natural baseline model is one where we always make the same prediction independent of the given datapoint, setting the predicted value equal to the fraction of training points that correspond to click-through events (i.e., where the label is one). Compute this value (which is simply the mean of the training labels), and then use it to compute the training log loss for the baseline model. The log loss for multiple observations is the mean of the individual log loss values." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# TODO: Replace with appropriate code\n", "# Note that our dataset has a very high click-through rate by design\n", "# In practice click-through rate can be one to two orders of magnitude lower\n", "classOneFracTrain = \n", "print classOneFracTrain\n", "\n", "logLossTrBase = \n", "print 'Baseline Train Logloss = {0:.3f}\\n'.format(logLossTrBase)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# TEST Baseline log loss (4c)\n", "Test.assertTrue(np.allclose(classOneFracTrain, 0.22717773523), 'incorrect value for classOneFracTrain')\n", "Test.assertTrue(np.allclose(logLossTrBase, 0.535844), 'incorrect value for logLossTrBase')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### ** (4d) Predicted probability **\n", "#### In order to compute the log loss for the model we trained in Part (4a), we need to write code to generate predictions from this model. Write a function that computes the raw linear prediction from this logistic regression model and then passes it through a [sigmoid function](http://en.wikipedia.org/wiki/Sigmoid_function) $ \\scriptsize \\sigma(t) = (1+ e^{-t})^{-1} $ to return the model's probabilistic prediction. Then compute probabilistic predictions on the training data.\n", "#### Note that when incorporating an intercept into our predictions, we simply add the intercept to the value of the prediction obtained from the weights and features. Alternatively, if the intercept was included as the first weight, we would need to add a corresponding feature to our data where the feature has the value one. This is not the case here." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# TODO: Replace with appropriate code\n", "from math import exp # exp(-t) = e^-t\n", "\n", "def getP(x, w, intercept):\n", " \"\"\"Calculate the probability for an observation given a set of weights and intercept.\n", "\n", " Note:\n", " We'll bound our raw prediction between 20 and -20 for numerical purposes.\n", "\n", " Args:\n", " x (SparseVector): A vector with values of 1.0 for features that exist in this\n", " observation and 0.0 otherwise.\n", " w (DenseVector): A vector of weights (betas) for the model.\n", " intercept (float): The model's intercept.\n", "\n", " Returns:\n", " float: A probability between 0 and 1.\n", " \"\"\"\n", " rawPrediction = \n", "\n", " # Bound the raw prediction value\n", " rawPrediction = min(rawPrediction, 20)\n", " rawPrediction = max(rawPrediction, -20)\n", " return \n", "\n", "trainingPredictions = \n", "\n", "print trainingPredictions.take(5)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# TEST Predicted probability (4d)\n", "Test.assertTrue(np.allclose(trainingPredictions.sum(), 18135.4834348),\n", " 'incorrect value for trainingPredictions')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### ** (4e) Evaluate the model **\n", "#### We are now ready to evaluate the quality of the model we trained in Part (4a). To do this, first write a general function that takes as input a model and data, and outputs the log loss. Then run this function on the OHE training data, and compare the result with the baseline log loss." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# TODO: Replace with appropriate code\n", "def evaluateResults(model, data):\n", " \"\"\"Calculates the log loss for the data given the model.\n", "\n", " Args:\n", " model (LogisticRegressionModel): A trained logistic regression model.\n", " data (RDD of LabeledPoint): Labels and features for each observation.\n", "\n", " Returns:\n", " float: Log loss for the data.\n", " \"\"\"\n", " \n", "\n", "logLossTrLR0 = evaluateResults(model0, OHETrainData)\n", "print ('OHE Features Train Logloss:\\n\\tBaseline = {0:.3f}\\n\\tLogReg = {1:.3f}'\n", " .format(logLossTrBase, logLossTrLR0))" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# TEST Evaluate the model (4e)\n", "Test.assertTrue(np.allclose(logLossTrLR0, 0.456903), 'incorrect value for logLossTrLR0')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### ** (4f) Validation log loss **\n", "#### Next, following the same logic as in Parts (4c) and 4(e), compute the validation log loss for both the baseline and logistic regression models. Notably, the baseline model for the validation data should still be based on the label fraction from the training dataset." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# TODO: Replace with appropriate code\n", "logLossValBase = \n", "\n", "logLossValLR0 = \n", "print ('OHE Features Validation Logloss:\\n\\tBaseline = {0:.3f}\\n\\tLogReg = {1:.3f}'\n", " .format(logLossValBase, logLossValLR0))" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# TEST Validation log loss (4f)\n", "Test.assertTrue(np.allclose(logLossValBase, 0.527603), 'incorrect value for logLossValBase')\n", "Test.assertTrue(np.allclose(logLossValLR0, 0.456957), 'incorrect value for logLossValLR0')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### **Visualization 2: ROC curve **\n", "#### We will now visualize how well the model predicts our target. To do this we generate a plot of the ROC curve. The ROC curve shows us the trade-off between the false positive rate and true positive rate, as we liberalize the threshold required to predict a positive outcome. A random model is represented by the dashed line." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "labelsAndScores = OHEValidationData.map(lambda lp:\n", " (lp.label, getP(lp.features, model0.weights, model0.intercept)))\n", "labelsAndWeights = labelsAndScores.collect()\n", "labelsAndWeights.sort(key=lambda (k, v): v, reverse=True)\n", "labelsByWeight = np.array([k for (k, v) in labelsAndWeights])\n", "\n", "length = labelsByWeight.size\n", "truePositives = labelsByWeight.cumsum()\n", "numPositive = truePositives[-1]\n", "falsePositives = np.arange(1.0, length + 1, 1.) - truePositives\n", "\n", "truePositiveRate = truePositives / numPositive\n", "falsePositiveRate = falsePositives / (length - numPositive)\n", "\n", "# Generate layout and plot data\n", "fig, ax = preparePlot(np.arange(0., 1.1, 0.1), np.arange(0., 1.1, 0.1))\n", "ax.set_xlim(-.05, 1.05), ax.set_ylim(-.05, 1.05)\n", "ax.set_ylabel('True Positive Rate (Sensitivity)')\n", "ax.set_xlabel('False Positive Rate (1 - Specificity)')\n", "plt.plot(falsePositiveRate, truePositiveRate, color='#8cbfd0', linestyle='-', linewidth=3.)\n", "plt.plot((0., 1.), (0., 1.), linestyle='--', color='#d6ebf2', linewidth=2.) # Baseline model\n", "pass" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### **Part 5: Reduce feature dimension via feature hashing**" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### ** (5a) Hash function **\n", "#### As we just saw, using a one-hot-encoding featurization can yield a model with good statistical accuracy. However, the number of distinct categories across all features is quite large -- recall that we observed 233K categories in the training data in Part (3c). Moreover, the full Kaggle training dataset includes more than 33M distinct categories, and the Kaggle dataset itself is just a small subset of Criteo's labeled data. Hence, featurizing via a one-hot-encoding representation would lead to a very large feature vector. To reduce the dimensionality of the feature space, we will use feature hashing.\n", "####Below is the hash function that we will use for this part of the lab. We will first use this hash function with the three sample data points from Part (1a) to gain some intuition. Specifically, run code to hash the three sample points using two different values for `numBuckets` and observe the resulting hashed feature dictionaries." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "from collections import defaultdict\n", "import hashlib\n", "\n", "def hashFunction(numBuckets, rawFeats, printMapping=False):\n", " \"\"\"Calculate a feature dictionary for an observation's features based on hashing.\n", "\n", " Note:\n", " Use printMapping=True for debug purposes and to better understand how the hashing works.\n", "\n", " Args:\n", " numBuckets (int): Number of buckets to use as features.\n", " rawFeats (list of (int, str)): A list of features for an observation. Represented as\n", " (featureID, value) tuples.\n", " printMapping (bool, optional): If true, the mappings of featureString to index will be\n", " printed.\n", "\n", " Returns:\n", " dict of int to float: The keys will be integers which represent the buckets that the\n", " features have been hashed to. The value for a given key will contain the count of the\n", " (featureID, value) tuples that have hashed to that key.\n", " \"\"\"\n", " mapping = {}\n", " for ind, category in rawFeats:\n", " featureString = category + str(ind)\n", " mapping[featureString] = int(int(hashlib.md5(featureString).hexdigest(), 16) % numBuckets)\n", " if(printMapping): print mapping\n", " sparseFeatures = defaultdict(float)\n", " for bucket in mapping.values():\n", " sparseFeatures[bucket] += 1.0\n", " return dict(sparseFeatures)\n", "\n", "# Reminder of the sample values:\n", "# sampleOne = [(0, 'mouse'), (1, 'black')]\n", "# sampleTwo = [(0, 'cat'), (1, 'tabby'), (2, 'mouse')]\n", "# sampleThree = [(0, 'bear'), (1, 'black'), (2, 'salmon')]" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# TODO: Replace with appropriate code\n", "# Use four buckets\n", "sampOneFourBuckets = hashFunction(, sampleOne, True)\n", "sampTwoFourBuckets = hashFunction(, sampleTwo, True)\n", "sampThreeFourBuckets = hashFunction(, sampleThree, True)\n", "\n", "# Use one hundred buckets\n", "sampOneHundredBuckets = hashFunction(, sampleOne, True)\n", "sampTwoHundredBuckets = hashFunction(, sampleTwo, True)\n", "sampThreeHundredBuckets = hashFunction(, sampleThree, True)\n", "\n", "print '\\t\\t 4 Buckets \\t\\t\\t 100 Buckets'\n", "print 'SampleOne:\\t {0}\\t\\t {1}'.format(sampOneFourBuckets, sampOneHundredBuckets)\n", "print 'SampleTwo:\\t {0}\\t\\t {1}'.format(sampTwoFourBuckets, sampTwoHundredBuckets)\n", "print 'SampleThree:\\t {0}\\t {1}'.format(sampThreeFourBuckets, sampThreeHundredBuckets)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# TEST Hash function (5a)\n", "Test.assertEquals(sampOneFourBuckets, {2: 1.0, 3: 1.0}, 'incorrect value for sampOneFourBuckets')\n", "Test.assertEquals(sampThreeHundredBuckets, {72: 1.0, 5: 1.0, 14: 1.0},\n", " 'incorrect value for sampThreeHundredBuckets')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### ** (5b) Creating hashed features **\n", "#### Next we will use this hash function to create hashed features for our CTR datasets. First write a function that uses the hash function from Part (5a) with numBuckets = $ \\scriptsize 2^{15} \\approx 33K $ to create a `LabeledPoint` with hashed features stored as a `SparseVector`. Then use this function to create new training, validation and test datasets with hashed features. Hint: `parsedHashPoint` is similar to `parseOHEPoint` from Part (3d)." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# TODO: Replace with appropriate code\n", "def parseHashPoint(point, numBuckets):\n", " \"\"\"Create a LabeledPoint for this observation using hashing.\n", "\n", " Args:\n", " point (str): A comma separated string where the first value is the label and the rest are\n", " features.\n", " numBuckets: The number of buckets to hash to.\n", "\n", " Returns:\n", " LabeledPoint: A LabeledPoint with a label (0.0 or 1.0) and a SparseVector of hashed\n", " features.\n", " \"\"\"\n", " \n", "\n", "numBucketsCTR = 2 ** 15\n", "hashTrainData = \n", "hashTrainData.cache()\n", "hashValidationData = \n", "hashValidationData.cache()\n", "hashTestData = \n", "hashTestData.cache()\n", "\n", "print hashTrainData.take(1)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# TEST Creating hashed features (5b)\n", "hashTrainDataFeatureSum = sum(hashTrainData\n", " .map(lambda lp: len(lp.features.indices))\n", " .take(20))\n", "hashTrainDataLabelSum = sum(hashTrainData\n", " .map(lambda lp: lp.label)\n", " .take(100))\n", "hashValidationDataFeatureSum = sum(hashValidationData\n", " .map(lambda lp: len(lp.features.indices))\n", " .take(20))\n", "hashValidationDataLabelSum = sum(hashValidationData\n", " .map(lambda lp: lp.label)\n", " .take(100))\n", "hashTestDataFeatureSum = sum(hashTestData\n", " .map(lambda lp: len(lp.features.indices))\n", " .take(20))\n", "hashTestDataLabelSum = sum(hashTestData\n", " .map(lambda lp: lp.label)\n", " .take(100))\n", "\n", "Test.assertEquals(hashTrainDataFeatureSum, 772, 'incorrect number of features in hashTrainData')\n", "Test.assertEquals(hashTrainDataLabelSum, 24.0, 'incorrect labels in hashTrainData')\n", "Test.assertEquals(hashValidationDataFeatureSum, 776,\n", " 'incorrect number of features in hashValidationData')\n", "Test.assertEquals(hashValidationDataLabelSum, 16.0, 'incorrect labels in hashValidationData')\n", "Test.assertEquals(hashTestDataFeatureSum, 774, 'incorrect number of features in hashTestData')\n", "Test.assertEquals(hashTestDataLabelSum, 23.0, 'incorrect labels in hashTestData')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### ** (5c) Sparsity **\n", "#### Since we have 33K hashed features versus 233K OHE features, we should expect OHE features to be sparser. Verify this hypothesis by computing the average sparsity of the OHE and the hashed training datasets.\n", "#### Note that if you have a `SparseVector` named `sparse`, calling `len(sparse)` returns the total number of features, not the number features with entries. `SparseVector` objects have the attributes `indices` and `values` that contain information about which features are nonzero. Continuing with our example, these can be accessed using `sparse.indices` and `sparse.values`, respectively." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# TODO: Replace with appropriate code\n", "def computeSparsity(data, d, n):\n", " \"\"\"Calculates the average sparsity for the features in an RDD of LabeledPoints.\n", "\n", " Args:\n", " data (RDD of LabeledPoint): The LabeledPoints to use in the sparsity calculation.\n", " d (int): The total number of features.\n", " n (int): The number of observations in the RDD.\n", "\n", " Returns:\n", " float: The average of the ratio of features in a point to total features.\n", " \"\"\"\n", " \n", "\n", "averageSparsityHash = computeSparsity(hashTrainData, numBucketsCTR, nTrain)\n", "averageSparsityOHE = computeSparsity(OHETrainData, numCtrOHEFeats, nTrain)\n", "\n", "print 'Average OHE Sparsity: {0:.7e}'.format(averageSparsityOHE)\n", "print 'Average Hash Sparsity: {0:.7e}'.format(averageSparsityHash)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# TEST Sparsity (5c)\n", "Test.assertTrue(np.allclose(averageSparsityOHE, 1.6717677e-04),\n", " 'incorrect value for averageSparsityOHE')\n", "Test.assertTrue(np.allclose(averageSparsityHash, 1.1805561e-03),\n", " 'incorrect value for averageSparsityHash')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### ** (5d) Logistic model with hashed features **\n", "#### Now let's train a logistic regression model using the hashed features. Run a grid search to find suitable hyperparameters for the hashed features, evaluating via log loss on the validation data. Note: This may take a few minutes to run. Use `1` and `10` for `stepSizes` and `1e-6` and `1e-3` for `regParams`." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "numIters = 500\n", "regType = 'l2'\n", "includeIntercept = True\n", "\n", "# Initialize variables using values from initial model training\n", "bestModel = None\n", "bestLogLoss = 1e10" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# TODO: Replace with appropriate code\n", "stepSizes = \n", "regParams = \n", "for stepSize in stepSizes:\n", " for regParam in regParams:\n", " model = (LogisticRegressionWithSGD\n", " .train(hashTrainData, numIters, stepSize, regParam=regParam, regType=regType,\n", " intercept=includeIntercept))\n", " logLossVa = evaluateResults(model, hashValidationData)\n", " print ('\\tstepSize = {0:.1f}, regParam = {1:.0e}: logloss = {2:.3f}'\n", " .format(stepSize, regParam, logLossVa))\n", " if (logLossVa < bestLogLoss):\n", " bestModel = model\n", " bestLogLoss = logLossVa\n", "\n", "print ('Hashed Features Validation Logloss:\\n\\tBaseline = {0:.3f}\\n\\tLogReg = {1:.3f}'\n", " .format(logLossValBase, bestLogLoss))" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# TEST Logistic model with hashed features (5d)\n", "Test.assertTrue(np.allclose(bestLogLoss, 0.4481683608), 'incorrect value for bestLogLoss')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### **Visualization 3: Hyperparameter heat map**\n", "#### We will now perform a visualization of an extensive hyperparameter search. Specifically, we will create a heat map where the brighter colors correspond to lower values of `logLoss`.\n", "#### The search was run using six step sizes and six values for regularization, which required the training of thirty-six separate models. We have included the results below, but omitted the actual search to save time." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "from matplotlib.colors import LinearSegmentedColormap\n", "\n", "# Saved parameters and results. Eliminate the time required to run 36 models\n", "stepSizes = [3, 6, 9, 12, 15, 18]\n", "regParams = [1e-7, 1e-6, 1e-5, 1e-4, 1e-3, 1e-2]\n", "logLoss = np.array([[ 0.45808431, 0.45808493, 0.45809113, 0.45815333, 0.45879221, 0.46556321],\n", " [ 0.45188196, 0.45188306, 0.4518941, 0.4520051, 0.45316284, 0.46396068],\n", " [ 0.44886478, 0.44886613, 0.44887974, 0.44902096, 0.4505614, 0.46371153],\n", " [ 0.44706645, 0.4470698, 0.44708102, 0.44724251, 0.44905525, 0.46366507],\n", " [ 0.44588848, 0.44589365, 0.44590568, 0.44606631, 0.44807106, 0.46365589],\n", " [ 0.44508948, 0.44509474, 0.44510274, 0.44525007, 0.44738317, 0.46365405]])\n", "\n", "numRows, numCols = len(stepSizes), len(regParams)\n", "logLoss = np.array(logLoss)\n", "logLoss.shape = (numRows, numCols)\n", "\n", "fig, ax = preparePlot(np.arange(0, numCols, 1), np.arange(0, numRows, 1), figsize=(8, 7),\n", " hideLabels=True, gridWidth=0.)\n", "ax.set_xticklabels(regParams), ax.set_yticklabels(stepSizes)\n", "ax.set_xlabel('Regularization Parameter'), ax.set_ylabel('Step Size')\n", "\n", "colors = LinearSegmentedColormap.from_list('blue', ['#0022ff', '#000055'], gamma=.2)\n", "image = plt.imshow(logLoss,interpolation='nearest', aspect='auto',\n", " cmap = colors)\n", "pass" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### ** (5e) Evaluate on the test set **\n", "#### Finally, evaluate the best model from Part (5d) on the test set. Compare the resulting log loss with the baseline log loss on the test set, which can be computed in the same way that the validation log loss was computed in Part (4f)." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# TODO: Replace with appropriate code\n", "# Log loss for the best model from (5d)\n", "logLossTest = \n", "\n", "# Log loss for the baseline model\n", "logLossTestBaseline = \n", "\n", "print ('Hashed Features Test Log Loss:\\n\\tBaseline = {0:.3f}\\n\\tLogReg = {1:.3f}'\n", " .format(logLossTestBaseline, logLossTest))" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# TEST Evaluate on the test set (5e)\n", "Test.assertTrue(np.allclose(logLossTestBaseline, 0.537438),\n", " 'incorrect value for logLossTestBaseline')\n", "Test.assertTrue(np.allclose(logLossTest, 0.455616931), 'incorrect value for logLossTest')" ] } ], "metadata": {}, "nbformat": 4, "nbformat_minor": 0 }