{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "![ML Logo](http://spark-mooc.github.io/web-assets/images/CS190.1x_Banner_300.png)\n", "# **Linear Regression Lab**\n", "#### This lab covers a common supervised learning pipeline, using a subset of the [Million Song Dataset](http://labrosa.ee.columbia.edu/millionsong/) from the [UCI Machine Learning Repository](https://archive.ics.uci.edu/ml/datasets/YearPredictionMSD). Our goal is to train a linear regression model to predict the release year of a song given a set of audio features.\n", "#### ** This lab will cover: **\n", "+ ####*Part 1:* Read and parse the initial dataset\n", " + #### *Visualization 1:* Features\n", " + #### *Visualization 2:* Shifting labels\n", "+ ####*Part 2:* Create and evaluate a baseline model\n", " + #### *Visualization 3:* Predicted vs. actual\n", "+ ####*Part 3:* Train (via gradient descent) and evaluate a linear regression model\n", " + #### *Visualization 4:* Training error\n", "+ ####*Part 4:* Train using MLlib and tune hyperparameters via grid search\n", " + #### *Visualization 5:* Best model's predictions\n", " + #### *Visualization 6:* Hyperparameter heat map\n", "+ ####*Part 5:* Add interactions between features\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_week3_v_1_3'" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### ** Part 1: Read and parse the initial dataset **" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### ** (1a) Load and check the data **\n", "#### The raw data is currently stored in text file. We will start by storing this raw data in as an RDD, with each element of the RDD representing a data point as a comma-delimited string. Each string starts with the label (a year) followed by numerical audio features. Use the [count method](https://spark.apache.org/docs/latest/api/python/pyspark.html#pyspark.RDD.count) to check how many data points we have. Then use the [take method](https://spark.apache.org/docs/latest/api/python/pyspark.html#pyspark.RDD.take) to create and print out a list of the first 5 data points in their initial string format." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# load testing library\n", "from test_helper import Test\n", "import os.path\n", "baseDir = os.path.join('data')\n", "inputPath = os.path.join('cs190', 'millionsong.txt')\n", "fileName = os.path.join(baseDir, inputPath)\n", "\n", "numPartitions = 2\n", "rawData = sc.textFile(fileName, numPartitions)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# TODO: Replace with appropriate code\n", "numPoints = \n", "print numPoints\n", "samplePoints = \n", "print samplePoints" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# TEST Load and check the data (1a)\n", "Test.assertEquals(numPoints, 6724, 'incorrect value for numPoints')\n", "Test.assertEquals(len(samplePoints), 5, 'incorrect length for samplePoints')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### ** (1b) Using `LabeledPoint` **\n", "#### In MLlib, labeled training instances are stored using the [LabeledPoint](https://spark.apache.org/docs/latest/api/python/pyspark.mllib.html#pyspark.mllib.regression.LabeledPoint) object. Write the parsePoint function that takes as input a raw data point, parses it using Python's [unicode.split](https://docs.python.org/2/library/string.html#string.split) method, and returns a `LabeledPoint`. Use this function to parse samplePoints (from the previous question). Then print out the features and label for the first training point, using the `LabeledPoint.features` and `LabeledPoint.label` attributes. Finally, calculate the number features for this dataset.\n", "#### Note that `split()` can be called directly on a `unicode` or `str` object. For example, `u'split,me'.split(',')` returns `[u'split', u'me']`." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "from pyspark.mllib.regression import LabeledPoint\n", "import numpy as np\n", "\n", "# Here is a sample raw data point:\n", "# '2001.0,0.884,0.610,0.600,0.474,0.247,0.357,0.344,0.33,0.600,0.425,0.60,0.419'\n", "# In this raw data point, 2001.0 is the label, and the remaining values are features" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# TODO: Replace with appropriate code\n", "def parsePoint(line):\n", " \"\"\"Converts a comma separated unicode string into a `LabeledPoint`.\n", "\n", " Args:\n", " line (unicode): Comma separated unicode string where the first element is the label and the\n", " remaining elements are features.\n", "\n", " Returns:\n", " LabeledPoint: The line is converted into a `LabeledPoint`, which consists of a label and\n", " features.\n", " \"\"\"\n", " \n", "\n", "parsedSamplePoints = \n", "firstPointFeatures = \n", "firstPointLabel = \n", "print firstPointFeatures, firstPointLabel\n", "\n", "d = len(firstPointFeatures)\n", "print d" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# TEST Using LabeledPoint (1b)\n", "Test.assertTrue(isinstance(firstPointLabel, float), 'label must be a float')\n", "expectedX0 = [0.8841,0.6105,0.6005,0.4747,0.2472,0.3573,0.3441,0.3396,0.6009,0.4257,0.6049,0.4192]\n", "Test.assertTrue(np.allclose(expectedX0, firstPointFeatures, 1e-4, 1e-4),\n", " 'incorrect features for firstPointFeatures')\n", "Test.assertTrue(np.allclose(2001.0, firstPointLabel), 'incorrect label for firstPointLabel')\n", "Test.assertTrue(d == 12, 'incorrect number of features')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### **Visualization 1: Features**\n", "#### First we will load and setup the visualization library. Then we will look at the raw features for 50 data points by generating a heatmap that visualizes each feature on a grey-scale and shows the variation of each feature across the 50 sample data points. The features are all between 0 and 1, with values closer to 1 represented via darker shades of grey." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import matplotlib.pyplot as plt\n", "import matplotlib.cm as cm\n", "\n", "sampleMorePoints = rawData.take(50)\n", "# You can uncomment the line below to see randomly selected features. These will be randomly\n", "# selected each time you run the cell. Note that you should run this cell with the line commented\n", "# out when answering the lab quiz questions.\n", "# sampleMorePoints = rawData.takeSample(False, 50)\n", "\n", "parsedSampleMorePoints = map(parsePoint, sampleMorePoints)\n", "dataValues = map(lambda lp: lp.features.toArray(), parsedSampleMorePoints)\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\n", "fig, ax = preparePlot(np.arange(.5, 11, 1), np.arange(.5, 49, 1), figsize=(8,7), hideLabels=True,\n", " gridColor='#eeeeee', gridWidth=1.1)\n", "image = plt.imshow(dataValues,interpolation='nearest', aspect='auto', cmap=cm.Greys)\n", "for x, y, s in zip(np.arange(-.125, 12, 1), np.repeat(-.75, 12), [str(x) for x in range(12)]):\n", " plt.text(x, y, s, color='#999999', size='10')\n", "plt.text(4.7, -3, 'Feature', color='#999999', size='11'), ax.set_ylabel('Observation')\n", "pass" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### **(1c) Find the range **\n", "#### Now let's examine the labels to find the range of song years. To do this, first parse each element of the `rawData` RDD, and then find the smallest and largest labels." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# TODO: Replace with appropriate code\n", "parsedDataInit = rawData.map()\n", "onlyLabels = parsedDataInit.map()\n", "minYear = \n", "maxYear = \n", "print maxYear, minYear" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# TEST Find the range (1c)\n", "Test.assertEquals(len(parsedDataInit.take(1)[0].features), 12,\n", " 'unexpected number of features in sample point')\n", "sumFeatTwo = parsedDataInit.map(lambda lp: lp.features[2]).sum()\n", "Test.assertTrue(np.allclose(sumFeatTwo, 3158.96224351), 'parsedDataInit has unexpected values')\n", "yearRange = maxYear - minYear\n", "Test.assertTrue(yearRange == 89, 'incorrect range for minYear to maxYear')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### **(1d) Shift labels **\n", "#### As we just saw, the labels are years in the 1900s and 2000s. In learning problems, it is often natural to shift labels such that they start from zero. Starting with `parsedDataInit`, create a new RDD consisting of `LabeledPoint` objects in which the labels are shifted such that smallest label equals zero." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# TODO: Replace with appropriate code\n", "parsedData = parsedDataInit.\n", "\n", "# Should be a LabeledPoint\n", "print type(parsedData.take(1)[0])\n", "# View the first point\n", "print '\\n{0}'.format(parsedData.take(1))" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# TEST Shift labels (1d)\n", "oldSampleFeatures = parsedDataInit.take(1)[0].features\n", "newSampleFeatures = parsedData.take(1)[0].features\n", "Test.assertTrue(np.allclose(oldSampleFeatures, newSampleFeatures),\n", " 'new features do not match old features')\n", "sumFeatTwo = parsedData.map(lambda lp: lp.features[2]).sum()\n", "Test.assertTrue(np.allclose(sumFeatTwo, 3158.96224351), 'parsedData has unexpected values')\n", "minYearNew = parsedData.map(lambda lp: lp.label).min()\n", "maxYearNew = parsedData.map(lambda lp: lp.label).max()\n", "Test.assertTrue(minYearNew == 0, 'incorrect min year in shifted data')\n", "Test.assertTrue(maxYearNew == 89, 'incorrect max year in shifted data')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### ** Visualization 2: Shifting labels **\n", "#### We will look at the labels before and after shifting them. Both scatter plots below visualize tuples storing i) a label value and ii) the number of training points with this label. The first scatter plot uses the initial labels, while the second one uses the shifted labels. Note that the two plots look the same except for the labels on the x-axis." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# get data for plot\n", "oldData = (parsedDataInit\n", " .map(lambda lp: (lp.label, 1))\n", " .reduceByKey(lambda x, y: x + y)\n", " .collect())\n", "x, y = zip(*oldData)\n", "\n", "# generate layout and plot data\n", "fig, ax = preparePlot(np.arange(1920, 2050, 20), np.arange(0, 150, 20))\n", "plt.scatter(x, y, s=14**2, c='#d6ebf2', edgecolors='#8cbfd0', alpha=0.75)\n", "ax.set_xlabel('Year'), ax.set_ylabel('Count')\n", "pass" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# get data for plot\n", "newData = (parsedData\n", " .map(lambda lp: (lp.label, 1))\n", " .reduceByKey(lambda x, y: x + y)\n", " .collect())\n", "x, y = zip(*newData)\n", "\n", "# generate layout and plot data\n", "fig, ax = preparePlot(np.arange(0, 120, 20), np.arange(0, 120, 20))\n", "plt.scatter(x, y, s=14**2, c='#d6ebf2', edgecolors='#8cbfd0', alpha=0.75)\n", "ax.set_xlabel('Year (shifted)'), ax.set_ylabel('Count')\n", "pass" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### ** (1e) Training, validation, and test sets **\n", "#### We're almost done parsing our dataset, and our final task involves split 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. Next, 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 and verify that the sum of their sizes equals the value computed in Part (1a)." ] }, { "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", "parsedTrainData, parsedValData, parsedTestData = parsedData.\n", "parsedTrainData.\n", "parsedValData.\n", "parsedTestData.\n", "nTrain = parsedTrainData.\n", "nVal = parsedValData.\n", "nTest = parsedTestData.\n", "\n", "print nTrain, nVal, nTest, nTrain + nVal + nTest\n", "print parsedData.count()" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# TEST Training, validation, and test sets (1e)\n", "Test.assertEquals(parsedTrainData.getNumPartitions(), numPartitions,\n", " 'parsedTrainData has wrong number of partitions')\n", "Test.assertEquals(parsedValData.getNumPartitions(), numPartitions,\n", " 'parsedValData has wrong number of partitions')\n", "Test.assertEquals(parsedTestData.getNumPartitions(), numPartitions,\n", " 'parsedTestData has wrong number of partitions')\n", "Test.assertEquals(len(parsedTrainData.take(1)[0].features), 12,\n", " 'parsedTrainData has wrong number of features')\n", "sumFeatTwo = (parsedTrainData\n", " .map(lambda lp: lp.features[2])\n", " .sum())\n", "sumFeatThree = (parsedValData\n", " .map(lambda lp: lp.features[3])\n", " .reduce(lambda x, y: x + y))\n", "sumFeatFour = (parsedTestData\n", " .map(lambda lp: lp.features[4])\n", " .reduce(lambda x, y: x + y))\n", "Test.assertTrue(np.allclose([sumFeatTwo, sumFeatThree, sumFeatFour],\n", " 2526.87757656, 297.340394298, 184.235876654),\n", " 'parsed Train, Val, Test data has unexpected values')\n", "Test.assertTrue(nTrain + nVal + nTest == 6724, 'unexpected Train, Val, Test data set size')\n", "Test.assertEquals(nTrain, 5371, 'unexpected value for nTrain')\n", "Test.assertEquals(nVal, 682, 'unexpected value for nVal')\n", "Test.assertEquals(nTest, 671, 'unexpected value for nTest')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### ** Part 2: Create and evaluate a baseline model **" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### **(2a) Average label **\n", "#### A very simple yet natural baseline model is one where we always make the same prediction independent of the given data point, using the average label in the training set as the constant prediction value. Compute this value, which is the average (shifted) song year for the training set. Use an appropriate method in the [RDD API](https://spark.apache.org/docs/latest/api/python/pyspark.html#pyspark.RDD)." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# TODO: Replace with appropriate code\n", "averageTrainYear = (parsedTrainData\n", " )\n", "print averageTrainYear" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# TEST Average label (2a)\n", "Test.assertTrue(np.allclose(averageTrainYear, 53.9316700801),\n", " 'incorrect value for averageTrainYear')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### **(2b) Root mean squared error **\n", "#### We naturally would like to see how well this naive baseline performs. We will use root mean squared error ([RMSE](http://en.wikipedia.org/wiki/Root-mean-square_deviation)) for evaluation purposes. Implement a function to compute RMSE given an RDD of (label, prediction) tuples, and test out this function on an example." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# TODO: Replace with appropriate code\n", "def squaredError(label, prediction):\n", " \"\"\"Calculates the the squared error for a single prediction.\n", "\n", " Args:\n", " label (float): The correct value for this observation.\n", " prediction (float): The predicted value for this observation.\n", "\n", " Returns:\n", " float: The difference between the `label` and `prediction` squared.\n", " \"\"\"\n", " \n", "\n", "def calcRMSE(labelsAndPreds):\n", " \"\"\"Calculates the root mean squared error for an `RDD` of (label, prediction) tuples.\n", "\n", " Args:\n", " labelsAndPred (RDD of (float, float)): An `RDD` consisting of (label, prediction) tuples.\n", "\n", " Returns:\n", " float: The square root of the mean of the squared errors.\n", " \"\"\"\n", " \n", "\n", "labelsAndPreds = sc.parallelize([(3., 1.), (1., 2.), (2., 2.)])\n", "# RMSE = sqrt[((3-1)^2 + (1-2)^2 + (2-2)^2) / 3] = 1.291\n", "exampleRMSE = calcRMSE(labelsAndPreds)\n", "print exampleRMSE" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# TEST Root mean squared error (2b)\n", "Test.assertTrue(np.allclose(squaredError(3, 1), 4.), 'incorrect definition of squaredError')\n", "Test.assertTrue(np.allclose(exampleRMSE, 1.29099444874), 'incorrect value for exampleRMSE')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### **(2c) Training, validation and test RMSE **\n", "#### Now let's calculate the training, validation and test RMSE of our baseline model. To do this, first create RDDs of (label, prediction) tuples for each dataset, and then call calcRMSE. Note that each RMSE can be interpreted as the average prediction error for the given dataset (in terms of number of years)." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# TODO: Replace with appropriate code\n", "labelsAndPredsTrain = parsedTrainData.\n", "rmseTrainBase = \n", "\n", "labelsAndPredsVal = parsedValData.\n", "rmseValBase = \n", "\n", "labelsAndPredsTest = parsedTestData.\n", "rmseTestBase = \n", "\n", "print 'Baseline Train RMSE = {0:.3f}'.format(rmseTrainBase)\n", "print 'Baseline Validation RMSE = {0:.3f}'.format(rmseValBase)\n", "print 'Baseline Test RMSE = {0:.3f}'.format(rmseTestBase)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# TEST Training, validation and test RMSE (2c)\n", "Test.assertTrue(np.allclose([rmseTrainBase, rmseValBase, rmseTestBase],\n", " [21.305869, 21.586452, 22.136957]), 'incorrect RMSE value')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### ** Visualization 3: Predicted vs. actual **\n", "#### We will visualize predictions on the validation dataset. The scatter plots below visualize tuples storing i) the predicted value and ii) true label. The first scatter plot represents the ideal situation where the predicted value exactly equals the true label, while the second plot uses the baseline predictor (i.e., `averageTrainYear`) for all predicted values. Further note that the points in the scatter plots are color-coded, ranging from light yellow when the true and predicted values are equal to bright red when they drastically differ." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "from matplotlib.colors import ListedColormap, Normalize\n", "from matplotlib.cm import get_cmap\n", "cmap = get_cmap('YlOrRd')\n", "norm = Normalize()\n", "\n", "actual = np.asarray(parsedValData\n", " .map(lambda lp: lp.label)\n", " .collect())\n", "error = np.asarray(parsedValData\n", " .map(lambda lp: (lp.label, lp.label))\n", " .map(lambda (l, p): squaredError(l, p))\n", " .collect())\n", "clrs = cmap(np.asarray(norm(error)))[:,0:3]\n", "\n", "fig, ax = preparePlot(np.arange(0, 100, 20), np.arange(0, 100, 20))\n", "plt.scatter(actual, actual, s=14**2, c=clrs, edgecolors='#888888', alpha=0.75, linewidths=0.5)\n", "ax.set_xlabel('Predicted'), ax.set_ylabel('Actual')\n", "pass" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "predictions = np.asarray(parsedValData\n", " .map(lambda lp: averageTrainYear)\n", " .collect())\n", "error = np.asarray(parsedValData\n", " .map(lambda lp: (lp.label, averageTrainYear))\n", " .map(lambda (l, p): squaredError(l, p))\n", " .collect())\n", "norm = Normalize()\n", "clrs = cmap(np.asarray(norm(error)))[:,0:3]\n", "\n", "fig, ax = preparePlot(np.arange(53.0, 55.0, 0.5), np.arange(0, 100, 20))\n", "ax.set_xlim(53, 55)\n", "plt.scatter(predictions, actual, s=14**2, c=clrs, edgecolors='#888888', alpha=0.75, linewidths=0.3)\n", "ax.set_xlabel('Predicted'), ax.set_ylabel('Actual')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### ** Part 3: Train (via gradient descent) and evaluate a linear regression model **" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### ** (3a) Gradient summand **\n", "#### Now let's see if we can do better via linear regression, training a model via gradient descent (we'll omit the intercept for now). Recall that the gradient descent update for linear regression is: $$ \\scriptsize \\mathbf{w}_{i+1} = \\mathbf{w}_i - \\alpha_i \\sum_j (\\mathbf{w}_i^\\top\\mathbf{x}_j - y_j) \\mathbf{x}_j \\,.$$ where $ \\scriptsize i $ is the iteration number of the gradient descent algorithm, and $ \\scriptsize j $ identifies the observation.\n", "#### First, implement a function that computes the summand for this update, i.e., the summand equals $ \\scriptsize (\\mathbf{w}^\\top \\mathbf{x} - y) \\mathbf{x} \\, ,$ and test out this function on two examples. Use the `DenseVector` [dot](http://spark.apache.org/docs/latest/api/python/pyspark.mllib.html#pyspark.mllib.linalg.DenseVector.dot) method." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "from pyspark.mllib.linalg import DenseVector" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# TODO: Replace with appropriate code\n", "def gradientSummand(weights, lp):\n", " \"\"\"Calculates the gradient summand for a given weight and `LabeledPoint`.\n", "\n", " Note:\n", " `DenseVector` behaves similarly to a `numpy.ndarray` and they can be used interchangably\n", " within this function. For example, they both implement the `dot` method.\n", "\n", " Args:\n", " weights (DenseVector): An array of model weights (betas).\n", " lp (LabeledPoint): The `LabeledPoint` for a single observation.\n", "\n", " Returns:\n", " DenseVector: An array of values the same length as `weights`. The gradient summand.\n", " \"\"\"\n", " \n", "\n", "exampleW = DenseVector([1, 1, 1])\n", "exampleLP = LabeledPoint(2.0, [3, 1, 4])\n", "# gradientSummand = (dot([1 1 1], [3 1 4]) - 2) * [3 1 4] = (8 - 2) * [3 1 4] = [18 6 24]\n", "summandOne = gradientSummand(exampleW, exampleLP)\n", "print summandOne\n", "\n", "exampleW = DenseVector([.24, 1.2, -1.4])\n", "exampleLP = LabeledPoint(3.0, [-1.4, 4.2, 2.1])\n", "summandTwo = gradientSummand(exampleW, exampleLP)\n", "print summandTwo" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# TEST Gradient summand (3a)\n", "Test.assertTrue(np.allclose(summandOne, [18., 6., 24.]), 'incorrect value for summandOne')\n", "Test.assertTrue(np.allclose(summandTwo, [1.7304,-5.1912,-2.5956]), 'incorrect value for summandTwo')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### ** (3b) Use weights to make predictions **\n", "#### Next, implement a `getLabeledPredictions` function that takes in weights and an observation's `LabeledPoint` and returns a (label, prediction) tuple. Note that we can predict by computing the dot product between weights and an observation's features." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# TODO: Replace with appropriate code\n", "def getLabeledPrediction(weights, observation):\n", " \"\"\"Calculates predictions and returns a (label, prediction) tuple.\n", "\n", " Note:\n", " The labels should remain unchanged as we'll use this information to calculate prediction\n", " error later.\n", "\n", " Args:\n", " weights (np.ndarray): An array with one weight for each features in `trainData`.\n", " observation (LabeledPoint): A `LabeledPoint` that contain the correct label and the\n", " features for the data point.\n", "\n", " Returns:\n", " tuple: A (label, prediction) tuple.\n", " \"\"\"\n", " return \n", "\n", "weights = np.array([1.0, 1.5])\n", "predictionExample = sc.parallelize([LabeledPoint(2, np.array([1.0, .5])),\n", " LabeledPoint(1.5, np.array([.5, .5]))])\n", "labelsAndPredsExample = predictionExample.map(lambda lp: getLabeledPrediction(weights, lp))\n", "print labelsAndPredsExample.collect()" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# TEST Use weights to make predictions (3b)\n", "Test.assertEquals(labelsAndPredsExample.collect(), [(2.0, 1.75), (1.5, 1.25)],\n", " 'incorrect definition for getLabeledPredictions')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### ** (3c) Gradient descent **\n", "#### Next, implement a gradient descent function for linear regression and test out this function on an example." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# TODO: Replace with appropriate code\n", "def linregGradientDescent(trainData, numIters):\n", " \"\"\"Calculates the weights and error for a linear regression model trained with gradient descent.\n", "\n", " Note:\n", " `DenseVector` behaves similarly to a `numpy.ndarray` and they can be used interchangably\n", " within this function. For example, they both implement the `dot` method.\n", "\n", " Args:\n", " trainData (RDD of LabeledPoint): The labeled data for use in training the model.\n", " numIters (int): The number of iterations of gradient descent to perform.\n", "\n", " Returns:\n", " (np.ndarray, np.ndarray): A tuple of (weights, training errors). Weights will be the\n", " final weights (one weight per feature) for the model, and training errors will contain\n", " an error (RMSE) for each iteration of the algorithm.\n", " \"\"\"\n", " # The length of the training data\n", " n = trainData.count()\n", " # The number of features in the training data\n", " d = len(trainData.take(1)[0].features)\n", " w = np.zeros(d)\n", " alpha = 1.0\n", " # We will compute and store the training error after each iteration\n", " errorTrain = np.zeros(numIters)\n", " for i in range(numIters):\n", " # Use getLabeledPrediction from (3b) with trainData to obtain an RDD of (label, prediction)\n", " # tuples. Note that the weights all equal 0 for the first iteration, so the predictions will\n", " # have large errors to start.\n", " labelsAndPredsTrain = trainData.\n", " errorTrain[i] = calcRMSE(labelsAndPredsTrain)\n", "\n", " # Calculate the `gradient`. Make use of the `gradientSummand` function you wrote in (3a).\n", " # Note that `gradient` sould be a `DenseVector` of length `d`.\n", " gradient = \n", "\n", " # Update the weights\n", " alpha_i = alpha / (n * np.sqrt(i+1))\n", " w -= \n", " return w, errorTrain\n", "\n", "# create a toy dataset with n = 10, d = 3, and then run 5 iterations of gradient descent\n", "# note: the resulting model will not be useful; the goal here is to verify that\n", "# linregGradientDescent is working properly\n", "exampleN = 10\n", "exampleD = 3\n", "exampleData = (sc\n", " .parallelize(parsedTrainData.take(exampleN))\n", " .map(lambda lp: LabeledPoint(lp.label, lp.features[0:exampleD])))\n", "print exampleData.take(2)\n", "exampleNumIters = 5\n", "exampleWeights, exampleErrorTrain = linregGradientDescent(exampleData, exampleNumIters)\n", "print exampleWeights" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# TEST Gradient descent (3c)\n", "expectedOutput = [48.88110449, 36.01144093, 30.25350092]\n", "Test.assertTrue(np.allclose(exampleWeights, expectedOutput), 'value of exampleWeights is incorrect')\n", "expectedError = [79.72013547, 30.27835699, 9.27842641, 9.20967856, 9.19446483]\n", "Test.assertTrue(np.allclose(exampleErrorTrain, expectedError),\n", " 'value of exampleErrorTrain is incorrect')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### ** (3d) Train the model **\n", "#### Now let's train a linear regression model on all of our training data and evaluate its accuracy on the validation set. Note that the test set will not be used here. If we evaluated the model on the test set, we would bias our final results.\n", "#### We've already done much of the required work: we computed the number of features in Part (1b); we created the training and validation datasets and computed their sizes in Part (1e); and, we wrote a function to compute RMSE in Part (2b)." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# TODO: Replace with appropriate code\n", "numIters = 50\n", "weightsLR0, errorTrainLR0 = linregGradientDescent()\n", "\n", "labelsAndPreds = parsedValData.\n", "rmseValLR0 = calcRMSE(labelsAndPreds)\n", "\n", "print 'Validation RMSE:\\n\\tBaseline = {0:.3f}\\n\\tLR0 = {1:.3f}'.format(rmseValBase,\n", " rmseValLR0)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# TEST Train the model (3d)\n", "expectedOutput = [22.64535883, 20.064699, -0.05341901, 8.2931319, 5.79155768, -4.51008084,\n", " 15.23075467, 3.8465554, 9.91992022, 5.97465933, 11.36849033, 3.86452361]\n", "Test.assertTrue(np.allclose(weightsLR0, expectedOutput), 'incorrect value for weightsLR0')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### ** Visualization 4: Training error **\n", "#### We will look at the log of the training error as a function of iteration. The first scatter plot visualizes the logarithm of the training error for all 50 iterations. The second plot shows the training error itself, focusing on the final 44 iterations." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "norm = Normalize()\n", "clrs = cmap(np.asarray(norm(np.log(errorTrainLR0))))[:,0:3]\n", "\n", "fig, ax = preparePlot(np.arange(0, 60, 10), np.arange(2, 6, 1))\n", "ax.set_ylim(2, 6)\n", "plt.scatter(range(0, numIters), np.log(errorTrainLR0), s=14**2, c=clrs, edgecolors='#888888', alpha=0.75)\n", "ax.set_xlabel('Iteration'), ax.set_ylabel(r'$\\log_e(errorTrainLR0)$')\n", "pass" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "norm = Normalize()\n", "clrs = cmap(np.asarray(norm(errorTrainLR0[6:])))[:,0:3]\n", "\n", "fig, ax = preparePlot(np.arange(0, 60, 10), np.arange(17, 22, 1))\n", "ax.set_ylim(17.8, 21.2)\n", "plt.scatter(range(0, numIters-6), errorTrainLR0[6:], s=14**2, c=clrs, edgecolors='#888888', alpha=0.75)\n", "ax.set_xticklabels(map(str, range(6, 66, 10)))\n", "ax.set_xlabel('Iteration'), ax.set_ylabel(r'Training Error')\n", "pass" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### ** Part 4: Train using MLlib and perform grid search **" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### **(4a) `LinearRegressionWithSGD` **\n", "#### We're already doing better than the baseline model, but let's see if we can do better by adding an intercept, using regularization, and (based on the previous visualization) training for more iterations. MLlib's [LinearRegressionWithSGD](https://spark.apache.org/docs/latest/api/python/pyspark.mllib.html#pyspark.mllib.regression.LinearRegressionWithSGD) essentially implements the same algorithm that we implemented in Part (3b), albeit more efficiently and with various additional functionality, such as stochastic gradient approximation, including an intercept in the model and also allowing L1 or L2 regularization. First use LinearRegressionWithSGD to train a model with L2 regularization and with an intercept. This method returns a [LinearRegressionModel](https://spark.apache.org/docs/latest/api/python/pyspark.mllib.html#pyspark.mllib.regression.LinearRegressionModel). Next, use the model's [weights](http://spark.apache.org/docs/latest/api/python/pyspark.mllib.html#pyspark.mllib.regression.LinearRegressionModel.weights) and [intercept](http://spark.apache.org/docs/latest/api/python/pyspark.mllib.html#pyspark.mllib.regression.LinearRegressionModel.intercept) attributes to print out the model's parameters." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "from pyspark.mllib.regression import LinearRegressionWithSGD\n", "# Values to use when training the linear regression model\n", "numIters = 500 # iterations\n", "alpha = 1.0 # step\n", "miniBatchFrac = 1.0 # miniBatchFraction\n", "reg = 1e-1 # regParam\n", "regType = 'l2' # regType\n", "useIntercept = True # intercept" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# TODO: Replace with appropriate code\n", "firstModel = LinearRegressionWithSGD.\n", "\n", "# weightsLR1 stores the model weights; interceptLR1 stores the model intercept\n", "weightsLR1 = \n", "interceptLR1 = \n", "print weightsLR1, interceptLR1" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# TEST LinearRegressionWithSGD (4a)\n", "expectedIntercept = 13.3335907631\n", "expectedWeights = [16.682292427, 14.7439059559, -0.0935105608897, 6.22080088829, 4.01454261926, -3.30214858535,\n", " 11.0403027232, 2.67190962854, 7.18925791279, 4.46093254586, 8.14950409475, 2.75135810882]\n", "Test.assertTrue(np.allclose(interceptLR1, expectedIntercept), 'incorrect value for interceptLR1')\n", "Test.assertTrue(np.allclose(weightsLR1, expectedWeights), 'incorrect value for weightsLR1')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### **(4b) Predict**\n", "#### Now use the [LinearRegressionModel.predict()](http://spark.apache.org/docs/latest/api/python/pyspark.mllib.html#pyspark.mllib.regression.LinearRegressionModel.predict) method to make a prediction on a sample point. Pass the `features` from a `LabeledPoint` into the `predict()` method." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# TODO: Replace with appropriate code\n", "samplePoint = parsedTrainData.take(1)[0]\n", "samplePrediction = \n", "print samplePrediction" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# TEST Predict (4b)\n", "Test.assertTrue(np.allclose(samplePrediction, 56.8013380112),\n", " 'incorrect value for samplePrediction')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### ** (4c) Evaluate RMSE **\n", "#### Next evaluate the accuracy of this model on the validation set. Use the `predict()` method to create a `labelsAndPreds` RDD, and then use the `calcRMSE()` function from Part (2b)." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# TODO: Replace with appropriate code\n", "labelsAndPreds = \n", "rmseValLR1 = \n", "\n", "print ('Validation RMSE:\\n\\tBaseline = {0:.3f}\\n\\tLR0 = {1:.3f}' +\n", " '\\n\\tLR1 = {2:.3f}').format(rmseValBase, rmseValLR0, rmseValLR1)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# TEST Evaluate RMSE (4c)\n", "Test.assertTrue(np.allclose(rmseValLR1, 19.691247), 'incorrect value for rmseValLR1')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### ** (4d) Grid search **\n", "#### We're already outperforming the baseline on the validation set by almost 2 years on average, but let's see if we can do better. Perform grid search to find a good regularization parameter. Try `regParam` values `1e-10`, `1e-5`, and `1`." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# TODO: Replace with appropriate code\n", "bestRMSE = rmseValLR1\n", "bestRegParam = reg\n", "bestModel = firstModel\n", "\n", "numIters = 500\n", "alpha = 1.0\n", "miniBatchFrac = 1.0\n", "for reg in :\n", " model = LinearRegressionWithSGD.train(parsedTrainData, numIters, alpha,\n", " miniBatchFrac, regParam=reg,\n", " regType='l2', intercept=True)\n", " labelsAndPreds = parsedValData.map(lambda lp: (lp.label, model.predict(lp.features)))\n", " rmseValGrid = calcRMSE(labelsAndPreds)\n", " print rmseValGrid\n", "\n", " if rmseValGrid < bestRMSE:\n", " bestRMSE = rmseValGrid\n", " bestRegParam = reg\n", " bestModel = model\n", "rmseValLRGrid = bestRMSE\n", "\n", "print ('Validation RMSE:\\n\\tBaseline = {0:.3f}\\n\\tLR0 = {1:.3f}\\n\\tLR1 = {2:.3f}\\n' +\n", " '\\tLRGrid = {3:.3f}').format(rmseValBase, rmseValLR0, rmseValLR1, rmseValLRGrid)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# TEST Grid search (4d)\n", "Test.assertTrue(np.allclose(17.017170, rmseValLRGrid), 'incorrect value for rmseValLRGrid')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### ** Visualization 5: Best model's predictions**\n", "#### Next, we create a visualization similar to 'Visualization 3: Predicted vs. actual' from Part 2 using the predictions from the best model from Part (4d) on the validation dataset. Specifically, we create a color-coded scatter plot visualizing tuples storing i) the predicted value from this model and ii) true label." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "predictions = np.asarray(parsedValData\n", " .map(lambda lp: bestModel.predict(lp.features))\n", " .collect())\n", "actual = np.asarray(parsedValData\n", " .map(lambda lp: lp.label)\n", " .collect())\n", "error = np.asarray(parsedValData\n", " .map(lambda lp: (lp.label, bestModel.predict(lp.features)))\n", " .map(lambda (l, p): squaredError(l, p))\n", " .collect())\n", "\n", "norm = Normalize()\n", "clrs = cmap(np.asarray(norm(error)))[:,0:3]\n", "\n", "fig, ax = preparePlot(np.arange(0, 120, 20), np.arange(0, 120, 20))\n", "ax.set_xlim(15, 82), ax.set_ylim(-5, 105)\n", "plt.scatter(predictions, actual, s=14**2, c=clrs, edgecolors='#888888', alpha=0.75, linewidths=.5)\n", "ax.set_xlabel('Predicted'), ax.set_ylabel(r'Actual')\n", "pass" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### ** (4e) Vary alpha and the number of iterations **\n", "#### In the previous grid search, we set `alpha = 1` for all experiments. Now let's see what happens when we vary `alpha`. Specifically, try `1e-5` and `10` as values for `alpha` and also try training models for 500 iterations (as before) but also for 5 iterations. Evaluate all models on the validation set. Note that if we set `alpha` too small the gradient descent will require a huge number of steps to converge to the solution, and if we use too large of an `alpha` it can cause numerical problems, like you'll see below for `alpha = 10`." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# TODO: Replace with appropriate code\n", "reg = bestRegParam\n", "modelRMSEs = []\n", "\n", "for alpha in :\n", " for numIters in :\n", " model = LinearRegressionWithSGD.train(parsedTrainData, numIters, alpha,\n", " miniBatchFrac, regParam=reg,\n", " regType='l2', intercept=True)\n", " labelsAndPreds = parsedValData.map(lambda lp: (lp.label, model.predict(lp.features)))\n", " rmseVal = calcRMSE(labelsAndPreds)\n", " print 'alpha = {0:.0e}, numIters = {1}, RMSE = {2:.3f}'.format(alpha, numIters, rmseVal)\n", " modelRMSEs.append(rmseVal)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# TEST Vary alpha and the number of iterations (4e)\n", "expectedResults = sorted([56.969705, 56.892949, 355124752.221221])\n", "Test.assertTrue(np.allclose(sorted(modelRMSEs)[:3], expectedResults), 'incorrect value for modelRMSEs')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### **Visualization 6: Hyperparameter heat map **\n", "#### Next, we perform a visualization of hyperparameter search using a larger set of hyperparameters (with precomputed results). Specifically, we create a heat map where the brighter colors correspond to lower RMSE values. The first plot has a large area with brighter colors. In order to differentiate within the bright region, we generate a second plot corresponding to the hyperparameters found within that region." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "from matplotlib.colors import LinearSegmentedColormap\n", "\n", "# Saved parameters and results, to save the time required to run 36 models\n", "numItersParams = [10, 50, 100, 250, 500, 1000]\n", "regParams = [1e-8, 1e-6, 1e-4, 1e-2, 1e-1, 1]\n", "rmseVal = np.array([[ 20.36769649, 20.36770128, 20.36818057, 20.41795354, 21.09778437, 301.54258421],\n", " [ 19.04948826, 19.0495 , 19.05067418, 19.16517726, 19.97967727, 23.80077467],\n", " [ 18.40149024, 18.40150998, 18.40348326, 18.59457491, 19.82155716, 23.80077467],\n", " [ 17.5609346 , 17.56096749, 17.56425511, 17.88442127, 19.71577117, 23.80077467],\n", " [ 17.0171705 , 17.01721288, 17.02145207, 17.44510574, 19.69124734, 23.80077467],\n", " [ 16.58074813, 16.58079874, 16.58586512, 17.11466904, 19.6860931 , 23.80077467]])\n", "\n", "numRows, numCols = len(numItersParams), len(regParams)\n", "rmseVal = np.array(rmseVal)\n", "rmseVal.shape = (numRows, numCols)\n", "\n", "fig, ax = preparePlot(np.arange(0, numCols, 1), np.arange(0, numRows, 1), figsize=(8, 7), hideLabels=True,\n", " gridWidth=0.)\n", "ax.set_xticklabels(regParams), ax.set_yticklabels(numItersParams)\n", "ax.set_xlabel('Regularization Parameter'), ax.set_ylabel('Number of Iterations')\n", "\n", "colors = LinearSegmentedColormap.from_list('blue', ['#0022ff', '#000055'], gamma=.2)\n", "image = plt.imshow(rmseVal,interpolation='nearest', aspect='auto',\n", " cmap = colors)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# Zoom into the bottom left\n", "numItersParamsZoom, regParamsZoom = numItersParams[-3:], regParams[:4]\n", "rmseValZoom = rmseVal[-3:, :4]\n", "\n", "numRows, numCols = len(numItersParamsZoom), len(regParamsZoom)\n", "\n", "fig, ax = preparePlot(np.arange(0, numCols, 1), np.arange(0, numRows, 1), figsize=(8, 7), hideLabels=True,\n", " gridWidth=0.)\n", "ax.set_xticklabels(regParamsZoom), ax.set_yticklabels(numItersParamsZoom)\n", "ax.set_xlabel('Regularization Parameter'), ax.set_ylabel('Number of Iterations')\n", "\n", "colors = LinearSegmentedColormap.from_list('blue', ['#0022ff', '#000055'], gamma=.2)\n", "image = plt.imshow(rmseValZoom,interpolation='nearest', aspect='auto',\n", " cmap = colors)\n", "pass" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### ** Part 5: Add interactions between features **" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### ** (5a) Add 2-way interactions **\n", "#### So far, we've used the features as they were provided. Now, we will add features that capture the two-way interactions between our existing features. Write a function `twoWayInteractions` that takes in a `LabeledPoint` and generates a new `LabeledPoint` that contains the old features and the two-way interactions between them. Note that a dataset with three features would have nine ( $ \\scriptsize 3^2 $ ) two-way interactions.\n", "#### You might want to use [itertools.product](https://docs.python.org/2/library/itertools.html#itertools.product) to generate tuples for each of the possible 2-way interactions. Remember that you can combine two `DenseVector` or `ndarray` objects using [np.hstack](http://docs.scipy.org/doc/numpy/reference/generated/numpy.hstack.html#numpy.hstack)." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# TODO: Replace with appropriate code\n", "import itertools\n", "\n", "def twoWayInteractions(lp):\n", " \"\"\"Creates a new `LabeledPoint` that includes two-way interactions.\n", "\n", " Note:\n", " For features [x, y] the two-way interactions would be [x^2, x*y, y*x, y^2] and these\n", " would be appended to the original [x, y] feature list.\n", "\n", " Args:\n", " lp (LabeledPoint): The label and features for this observation.\n", "\n", " Returns:\n", " LabeledPoint: The new `LabeledPoint` should have the same label as `lp`. Its features\n", " should include the features from `lp` followed by the two-way interaction features.\n", " \"\"\"\n", " \n", "\n", "print twoWayInteractions(LabeledPoint(0.0, [2, 3]))\n", "\n", "# Transform the existing train, validation, and test sets to include two-way interactions.\n", "trainDataInteract = \n", "valDataInteract = \n", "testDataInteract = " ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# TEST Add two-way interactions (5a)\n", "twoWayExample = twoWayInteractions(LabeledPoint(0.0, [2, 3]))\n", "Test.assertTrue(np.allclose(sorted(twoWayExample.features),\n", " sorted([2.0, 3.0, 4.0, 6.0, 6.0, 9.0])),\n", " 'incorrect features generatedBy twoWayInteractions')\n", "twoWayPoint = twoWayInteractions(LabeledPoint(1.0, [1, 2, 3]))\n", "Test.assertTrue(np.allclose(sorted(twoWayPoint.features),\n", " sorted([1.0,2.0,3.0,1.0,2.0,3.0,2.0,4.0,6.0,3.0,6.0,9.0])),\n", " 'incorrect features generated by twoWayInteractions')\n", "Test.assertEquals(twoWayPoint.label, 1.0, 'incorrect label generated by twoWayInteractions')\n", "Test.assertTrue(np.allclose(sum(trainDataInteract.take(1)[0].features), 40.821870576035529),\n", " 'incorrect features in trainDataInteract')\n", "Test.assertTrue(np.allclose(sum(valDataInteract.take(1)[0].features), 45.457719932695696),\n", " 'incorrect features in valDataInteract')\n", "Test.assertTrue(np.allclose(sum(testDataInteract.take(1)[0].features), 35.109111632783168),\n", " 'incorrect features in testDataInteract')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### ** (5b) Build interaction model **\n", "#### Now, let's build the new model. We've done this several times now. To implement this for the new features, we need to change a few variable names. Remember that we should build our model from the training data and evaluate it on the validation data.\n", "#### Note that you should re-run your hyperparameter search after changing features, as using the best hyperparameters from your prior model will not necessary lead to the best model. For this exercise, we have already preset the hyperparameters to reasonable values." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# TODO: Replace with appropriate code\n", "numIters = 500\n", "alpha = 1.0\n", "miniBatchFrac = 1.0\n", "reg = 1e-10\n", "\n", "modelInteract = LinearRegressionWithSGD.train(, numIters, alpha,\n", " miniBatchFrac, regParam=reg,\n", " regType='l2', intercept=True)\n", "labelsAndPredsInteract = .map(lambda lp: (lp.label, .predict(lp.features)))\n", "rmseValInteract = calcRMSE(labelsAndPredsInteract)\n", "\n", "print ('Validation RMSE:\\n\\tBaseline = {0:.3f}\\n\\tLR0 = {1:.3f}\\n\\tLR1 = {2:.3f}\\n\\tLRGrid = ' +\n", " '{3:.3f}\\n\\tLRInteract = {4:.3f}').format(rmseValBase, rmseValLR0, rmseValLR1,\n", " rmseValLRGrid, rmseValInteract)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# TEST Build interaction model (5b)\n", "Test.assertTrue(np.allclose(rmseValInteract, 15.6894664683), 'incorrect value for rmseValInteract')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### ** (5c) Evaluate interaction model on test data **\n", "#### Our final step is to evaluate the new model on the test dataset. Note that we haven't used the test set to evaluate any of our models. Because of this, our evaluation provides us with an unbiased estimate for how our model will perform on new data. If we had changed our model based on viewing its performance on the test set, our estimate of RMSE would likely be overly optimistic.\n", "#### We'll also print the RMSE for both the baseline model and our new model. With this information, we can see how much better our model performs than the baseline model." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# TODO: Replace with appropriate code\n", "labelsAndPredsTest = \n", "rmseTestInteract = \n", "\n", "print ('Test RMSE:\\n\\tBaseline = {0:.3f}\\n\\tLRInteract = {1:.3f}'\n", " .format(rmseTestBase, rmseTestInteract))" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# TEST Evaluate interaction model on test data (5c)\n", "Test.assertTrue(np.allclose(rmseTestInteract, 16.3272040537),\n", " 'incorrect value for rmseTestInteract')" ] } ], "metadata": {}, "nbformat": 4, "nbformat_minor": 0 }