{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "\n",
    "_You are currently looking at **version 1.5** of this notebook. To download notebooks and datafiles, as well as get help on Jupyter notebooks in the Coursera platform, visit the [Jupyter Notebook FAQ](https://www.coursera.org/learn/python-machine-learning/resources/bANLa) course resource._\n",
    "\n",
    "---"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Assignment 2\n",
    "\n",
    "In this assignment you'll explore the relationship between model complexity and generalization performance, by adjusting key parameters of various supervised learning models. Part 1 of this assignment will look at regression and Part 2 will look at classification.\n",
    "\n",
    "## Part 1 - Regression"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "First, run the following block to set up the variables needed for later sections."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true,
    "scrolled": false
   },
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import pandas as pd\n",
    "from sklearn.model_selection import train_test_split\n",
    "\n",
    "\n",
    "np.random.seed(0)\n",
    "n = 15\n",
    "x = np.linspace(0,10,n) + np.random.randn(n)/5\n",
    "y = np.sin(x)+x/6 + np.random.randn(n)/10\n",
    "\n",
    "\n",
    "X_train, X_test, y_train, y_test = train_test_split(x, y, random_state=0)\n",
    "\n",
    "# You can use this function to help you visualize the dataset by\n",
    "# plotting a scatterplot of the data points\n",
    "# in the training and test sets.\n",
    "def part1_scatter():\n",
    "    import matplotlib.pyplot as plt\n",
    "    %matplotlib notebook\n",
    "    plt.figure()\n",
    "    plt.scatter(X_train, y_train, label='training data')\n",
    "    plt.scatter(X_test, y_test, label='test data')\n",
    "    plt.legend(loc=4);\n",
    "    \n",
    "    \n",
    "# NOTE: Uncomment the function below to visualize the data, but be sure \n",
    "# to **re-comment it before submitting this assignment to the autograder**.   \n",
    "#part1_scatter()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Question 1\n",
    "\n",
    "Write a function that fits a polynomial LinearRegression model on the *training data* `X_train` for degrees 1, 3, 6, and 9. (Use PolynomialFeatures in sklearn.preprocessing to create the polynomial features and then fit a linear regression model) For each model, find 100 predicted values over the interval x = 0 to 10 (e.g. `np.linspace(0,10,100)`) and store this in a numpy array. The first row of this array should correspond to the output from the model trained on degree 1, the second row degree 3, the third row degree 6, and the fourth row degree 9.\n",
    "\n",
    "<img src=\"readonly/polynomialreg1.png\" style=\"width: 1000px;\"/>\n",
    "\n",
    "The figure above shows the fitted models plotted on top of the original data (using `plot_one()`).\n",
    "\n",
    "<br>\n",
    "*This function should return a numpy array with shape `(4, 100)`*"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def answer_one():\n",
    "    from sklearn.linear_model import LinearRegression\n",
    "    from sklearn.preprocessing import PolynomialFeatures\n",
    "\n",
    "    # Your code here\n",
    "    \n",
    "    return # Return your answer"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# feel free to use the function plot_one() to replicate the figure \n",
    "# from the prompt once you have completed question one\n",
    "def plot_one(degree_predictions):\n",
    "    import matplotlib.pyplot as plt\n",
    "    %matplotlib notebook\n",
    "    plt.figure(figsize=(10,5))\n",
    "    plt.plot(X_train, y_train, 'o', label='training data', markersize=10)\n",
    "    plt.plot(X_test, y_test, 'o', label='test data', markersize=10)\n",
    "    for i,degree in enumerate([1,3,6,9]):\n",
    "        plt.plot(np.linspace(0,10,100), degree_predictions[i], alpha=0.8, lw=2, label='degree={}'.format(degree))\n",
    "    plt.ylim(-1,2.5)\n",
    "    plt.legend(loc=4)\n",
    "\n",
    "#plot_one(answer_one())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Question 2\n",
    "\n",
    "Write a function that fits a polynomial LinearRegression model on the training data `X_train` for degrees 0 through 9. For each model compute the $R^2$ (coefficient of determination) regression score on the training data as well as the the test data, and return both of these arrays in a tuple.\n",
    "\n",
    "*This function should return one tuple of numpy arrays `(r2_train, r2_test)`. Both arrays should have shape `(10,)`*"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def answer_two():\n",
    "    from sklearn.linear_model import LinearRegression\n",
    "    from sklearn.preprocessing import PolynomialFeatures\n",
    "    from sklearn.metrics.regression import r2_score\n",
    "\n",
    "    # Your code here\n",
    "\n",
    "    return # Your answer here"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Question 3\n",
    "\n",
    "Based on the $R^2$ scores from question 2 (degree levels 0 through 9), what degree level corresponds to a model that is underfitting? What degree level corresponds to a model that is overfitting? What choice of degree level would provide a model with good generalization performance on this dataset? \n",
    "\n",
    "Hint: Try plotting the $R^2$ scores from question 2 to visualize the relationship between degree level and $R^2$. Remember to comment out the import matplotlib line before submission.\n",
    "\n",
    "*This function should return one tuple with the degree values in this order: `(Underfitting, Overfitting, Good_Generalization)`. There might be multiple correct solutions, however, you only need to return one possible solution, for example, (1,2,3).* "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def answer_three():\n",
    "    \n",
    "    # Your code here\n",
    "    \n",
    "    return # Return your answer"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Question 4\n",
    "\n",
    "Training models on high degree polynomial features can result in overly complex models that overfit, so we often use regularized versions of the model to constrain model complexity, as we saw with Ridge and Lasso linear regression.\n",
    "\n",
    "For this question, train two models: a non-regularized LinearRegression model (default parameters) and a regularized Lasso Regression model (with parameters `alpha=0.01`, `max_iter=10000`) both on polynomial features of degree 12. Return the $R^2$ score for both the LinearRegression and Lasso model's test sets.\n",
    "\n",
    "*This function should return one tuple `(LinearRegression_R2_test_score, Lasso_R2_test_score)`*"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def answer_four():\n",
    "    from sklearn.preprocessing import PolynomialFeatures\n",
    "    from sklearn.linear_model import Lasso, LinearRegression\n",
    "    from sklearn.metrics.regression import r2_score\n",
    "\n",
    "    # Your code here\n",
    "\n",
    "    return # Your answer here"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Part 2 - Classification\n",
    "\n",
    "Here's an application of machine learning that could save your life! For this section of the assignment we will be working with the [UCI Mushroom Data Set](http://archive.ics.uci.edu/ml/datasets/Mushroom?ref=datanews.io) stored in `mushrooms.csv`. The data will be used to train a model to predict whether or not a mushroom is poisonous. The following attributes are provided:\n",
    "\n",
    "*Attribute Information:*\n",
    "\n",
    "1. cap-shape: bell=b, conical=c, convex=x, flat=f, knobbed=k, sunken=s \n",
    "2. cap-surface: fibrous=f, grooves=g, scaly=y, smooth=s \n",
    "3. cap-color: brown=n, buff=b, cinnamon=c, gray=g, green=r, pink=p, purple=u, red=e, white=w, yellow=y \n",
    "4. bruises?: bruises=t, no=f \n",
    "5. odor: almond=a, anise=l, creosote=c, fishy=y, foul=f, musty=m, none=n, pungent=p, spicy=s \n",
    "6. gill-attachment: attached=a, descending=d, free=f, notched=n \n",
    "7. gill-spacing: close=c, crowded=w, distant=d \n",
    "8. gill-size: broad=b, narrow=n \n",
    "9. gill-color: black=k, brown=n, buff=b, chocolate=h, gray=g, green=r, orange=o, pink=p, purple=u, red=e, white=w, yellow=y \n",
    "10. stalk-shape: enlarging=e, tapering=t \n",
    "11. stalk-root: bulbous=b, club=c, cup=u, equal=e, rhizomorphs=z, rooted=r, missing=? \n",
    "12. stalk-surface-above-ring: fibrous=f, scaly=y, silky=k, smooth=s \n",
    "13. stalk-surface-below-ring: fibrous=f, scaly=y, silky=k, smooth=s \n",
    "14. stalk-color-above-ring: brown=n, buff=b, cinnamon=c, gray=g, orange=o, pink=p, red=e, white=w, yellow=y \n",
    "15. stalk-color-below-ring: brown=n, buff=b, cinnamon=c, gray=g, orange=o, pink=p, red=e, white=w, yellow=y \n",
    "16. veil-type: partial=p, universal=u \n",
    "17. veil-color: brown=n, orange=o, white=w, yellow=y \n",
    "18. ring-number: none=n, one=o, two=t \n",
    "19. ring-type: cobwebby=c, evanescent=e, flaring=f, large=l, none=n, pendant=p, sheathing=s, zone=z \n",
    "20. spore-print-color: black=k, brown=n, buff=b, chocolate=h, green=r, orange=o, purple=u, white=w, yellow=y \n",
    "21. population: abundant=a, clustered=c, numerous=n, scattered=s, several=v, solitary=y \n",
    "22. habitat: grasses=g, leaves=l, meadows=m, paths=p, urban=u, waste=w, woods=d\n",
    "\n",
    "<br>\n",
    "\n",
    "The data in the mushrooms dataset is currently encoded with strings. These values will need to be encoded to numeric to work with sklearn. We'll use pd.get_dummies to convert the categorical variables into indicator variables. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import numpy as np\n",
    "from sklearn.model_selection import train_test_split\n",
    "\n",
    "\n",
    "mush_df = pd.read_csv('mushrooms.csv')\n",
    "mush_df2 = pd.get_dummies(mush_df)\n",
    "\n",
    "X_mush = mush_df2.iloc[:,2:]\n",
    "y_mush = mush_df2.iloc[:,1]\n",
    "\n",
    "# use the variables X_train2, y_train2 for Question 5\n",
    "X_train2, X_test2, y_train2, y_test2 = train_test_split(X_mush, y_mush, random_state=0)\n",
    "\n",
    "# For performance reasons in Questions 6 and 7, we will create a smaller version of the\n",
    "# entire mushroom dataset for use in those questions.  For simplicity we'll just re-use\n",
    "# the 25% test split created above as the representative subset.\n",
    "#\n",
    "# Use the variables X_subset, y_subset for Questions 6 and 7.\n",
    "X_subset = X_test2\n",
    "y_subset = y_test2"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Question 5\n",
    "\n",
    "Using `X_train2` and `y_train2` from the preceeding cell, train a DecisionTreeClassifier with default parameters and random_state=0. What are the 5 most important features found by the decision tree?\n",
    "\n",
    "As a reminder, the feature names are available in the `X_train2.columns` property, and the order of the features in `X_train2.columns` matches the order of the feature importance values in the classifier's `feature_importances_` property. \n",
    "\n",
    "*This function should return a list of length 5 containing the feature names in descending order of importance.*\n",
    "\n",
    "*Note: remember that you also need to set random_state in the DecisionTreeClassifier.*"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def answer_five():\n",
    "    from sklearn.tree import DecisionTreeClassifier\n",
    "\n",
    "    # Your code here\n",
    "\n",
    "    return # Your answer here"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Question 6\n",
    "\n",
    "For this question, we're going to use the `validation_curve` function in `sklearn.model_selection` to determine training and test scores for a Support Vector Classifier (`SVC`) with varying parameter values.  Recall that the validation_curve function, in addition to taking an initialized unfitted classifier object, takes a dataset as input and does its own internal train-test splits to compute results.\n",
    "\n",
    "**Because creating a validation curve requires fitting multiple models, for performance reasons this question will use just a subset of the original mushroom dataset: please use the variables X_subset and y_subset as input to the validation curve function (instead of X_mush and y_mush) to reduce computation time.**\n",
    "\n",
    "The initialized unfitted classifier object we'll be using is a Support Vector Classifier with radial basis kernel.  So your first step is to create an `SVC` object with default parameters (i.e. `kernel='rbf', C=1`) and `random_state=0`. Recall that the kernel width of the RBF kernel is controlled using the `gamma` parameter.  \n",
    "\n",
    "With this classifier, and the dataset in X_subset, y_subset, explore the effect of `gamma` on classifier accuracy by using the `validation_curve` function to find the training and test scores for 6 values of `gamma` from `0.0001` to `10` (i.e. `np.logspace(-4,1,6)`). Recall that you can specify what scoring metric you want validation_curve to use by setting the \"scoring\" parameter.  In this case, we want to use \"accuracy\" as the scoring metric.\n",
    "\n",
    "For each level of `gamma`, `validation_curve` will fit 3 models on different subsets of the data, returning two 6x3 (6 levels of gamma x 3 fits per level) arrays of the scores for the training and test sets.\n",
    "\n",
    "Find the mean score across the three models for each level of `gamma` for both arrays, creating two arrays of length 6, and return a tuple with the two arrays.\n",
    "\n",
    "e.g.\n",
    "\n",
    "if one of your array of scores is\n",
    "\n",
    "    array([[ 0.5,  0.4,  0.6],\n",
    "           [ 0.7,  0.8,  0.7],\n",
    "           [ 0.9,  0.8,  0.8],\n",
    "           [ 0.8,  0.7,  0.8],\n",
    "           [ 0.7,  0.6,  0.6],\n",
    "           [ 0.4,  0.6,  0.5]])\n",
    "       \n",
    "it should then become\n",
    "\n",
    "    array([ 0.5,  0.73333333,  0.83333333,  0.76666667,  0.63333333, 0.5])\n",
    "\n",
    "*This function should return one tuple of numpy arrays `(training_scores, test_scores)` where each array in the tuple has shape `(6,)`.*"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def answer_six():\n",
    "    from sklearn.svm import SVC\n",
    "    from sklearn.model_selection import validation_curve\n",
    "\n",
    "    # Your code here\n",
    "\n",
    "    return # Your answer here"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Question 7\n",
    "\n",
    "Based on the scores from question 6, what gamma value corresponds to a model that is underfitting (and has the worst test set accuracy)? What gamma value corresponds to a model that is overfitting (and has the worst test set accuracy)? What choice of gamma would be the best choice for a model with good generalization performance on this dataset (high accuracy on both training and test set)? \n",
    "\n",
    "Hint: Try plotting the scores from question 6 to visualize the relationship between gamma and accuracy. Remember to comment out the import matplotlib line before submission.\n",
    "\n",
    "*This function should return one tuple with the degree values in this order: `(Underfitting, Overfitting, Good_Generalization)` Please note there is only one correct solution.*"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def answer_seven():\n",
    "    \n",
    "    # Your code here\n",
    "    \n",
    "    return # Return your answer"
   ]
  }
 ],
 "metadata": {
  "coursera": {
   "course_slug": "python-machine-learning",
   "graded_item_id": "eWYHL",
   "launcher_item_id": "BAqef",
   "part_id": "fXXRp"
  },
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.5.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
