Format: application/octet-stream
1 {
2 "cells": [
3 {
4 "cell_type": "markdown",
5 "metadata": {},
6 "source": [
7 "---\n",
8 "\n",
9 "_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",
10 "\n",
11 "---"
12 ]
13 },
14 {
15 "cell_type": "markdown",
16 "metadata": {},
17 "source": [
18 "# Assignment 2\n",
19 "\n",
20 "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",
21 "\n",
22 "## Part 1 - Regression"
23 ]
24 },
25 {
26 "cell_type": "markdown",
27 "metadata": {},
28 "source": [
29 "First, run the following block to set up the variables needed for later sections."
30 ]
31 },
32 {
33 "cell_type": "code",
34 "execution_count": 1,
35 "metadata": {
36 "collapsed": true
37 },
38 "outputs": [],
39 "source": [
40 "#import matplotlib.pyplot as plt\n",
41 "#%matplotlib notebook"
42 ]
43 },
44 {
45 "cell_type": "code",
46 "execution_count": 2,
47 "metadata": {
48 "scrolled": false
49 },
50 "outputs": [],
51 "source": [
52 "import numpy as np\n",
53 "import pandas as pd\n",
54 "from sklearn.model_selection import train_test_split\n",
55 "\n",
56 "\n",
57 "np.random.seed(0)\n",
58 "n = 15\n",
59 "x = np.linspace(0,10,n) + np.random.randn(n)/5\n",
60 "y = np.sin(x)+x/6 + np.random.randn(n)/10\n",
61 "\n",
62 "\n",
63 "X_train, X_test, y_train, y_test = train_test_split(x, y, random_state=0)\n",
64 "\n",
65 "# You can use this function to help you visualize the dataset by\n",
66 "# plotting a scatterplot of the data points\n",
67 "# in the training and test sets.\n",
68 "def part1_scatter():\n",
69 " plt.figure()\n",
70 " plt.scatter(X_train, y_train, label='training data')\n",
71 " plt.scatter(X_test, y_test, label='test data')\n",
72 " plt.legend(loc=4);\n",
73 " \n",
74 " \n",
75 "# NOTE: Uncomment the function below to visualize the data, but be sure \n",
76 "# to **re-comment it before submitting this assignment to the autograder**. \n",
77 "#part1_scatter()"
78 ]
79 },
80 {
81 "cell_type": "markdown",
82 "metadata": {},
83 "source": [
84 "### Question 1\n",
85 "\n",
86 "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",
87 "\n",
88 "<img src=\"readonly/polynomialreg1.png\" style=\"width: 1000px;\"/>\n",
89 "\n",
90 "The figure above shows the fitted models plotted on top of the original data (using `plot_one()`).\n",
91 "\n",
92 "<br>\n",
93 "*This function should return a numpy array with shape `(4, 100)`*"
94 ]
95 },
96 {
97 "cell_type": "code",
98 "execution_count": 5,
99 "metadata": {},
100 "outputs": [
101 {
102 "name": "stdout",
103 "output_type": "stream",
104 "text": [
105 "1\n",
106 "[[ 1. 10.08877265]\n",
107 " [ 1. 3.23065446]\n",
108 " [ 1. 1.62431903]\n",
109 " [ 1. 9.31004929]\n",
110 " [ 1. 7.17166586]\n",
111 " [ 1. 4.96972856]\n",
112 " [ 1. 8.14799756]\n",
113 " [ 1. 2.59103578]\n",
114 " [ 1. 0.35281047]\n",
115 " [ 1. 3.375973 ]\n",
116 " [ 1. 8.72363612]]\n",
117 "3\n",
118 "[[1.00000000e+00 1.00887726e+01 1.01783334e+02 1.02686891e+03]\n",
119 " [1.00000000e+00 3.23065446e+00 1.04371282e+01 3.37187547e+01]\n",
120 " [1.00000000e+00 1.62431903e+00 2.63841230e+00 4.28562329e+00]\n",
121 " [1.00000000e+00 9.31004929e+00 8.66770178e+01 8.06967308e+02]\n",
122 " [1.00000000e+00 7.17166586e+00 5.14327912e+01 3.68858792e+02]\n",
123 " [1.00000000e+00 4.96972856e+00 2.46982019e+01 1.22743360e+02]\n",
124 " [1.00000000e+00 8.14799756e+00 6.63898642e+01 5.40944452e+02]\n",
125 " [1.00000000e+00 2.59103578e+00 6.71346643e+00 1.73948317e+01]\n",
126 " [1.00000000e+00 3.52810469e-01 1.24475227e-01 4.39161633e-02]\n",
127 " [1.00000000e+00 3.37597300e+00 1.13971937e+01 3.84766180e+01]\n",
128 " [1.00000000e+00 8.72363612e+00 7.61018271e+01 6.63884647e+02]]\n",
129 "6\n",
130 "[[1.00000000e+00 1.00887726e+01 1.01783334e+02 1.02686891e+03\n",
131 " 1.03598470e+04 1.04518141e+05 1.05445976e+06]\n",
132 " [1.00000000e+00 3.23065446e+00 1.04371282e+01 3.37187547e+01\n",
133 " 1.08933645e+02 3.51926966e+02 1.13695442e+03]\n",
134 " [1.00000000e+00 1.62431903e+00 2.63841230e+00 4.28562329e+00\n",
135 " 6.96121945e+00 1.13072412e+01 1.83665670e+01]\n",
136 " [1.00000000e+00 9.31004929e+00 8.66770178e+01 8.06967308e+02\n",
137 " 7.51290541e+03 6.99455197e+04 6.51196236e+05]\n",
138 " [1.00000000e+00 7.17166586e+00 5.14327912e+01 3.68858792e+02\n",
139 " 2.64533201e+03 1.89714372e+04 1.36056809e+05]\n",
140 " [1.00000000e+00 4.96972856e+00 2.46982019e+01 1.22743360e+02\n",
141 " 6.10001179e+02 3.03154028e+03 1.50659323e+04]\n",
142 " [1.00000000e+00 8.14799756e+00 6.63898642e+01 5.40944452e+02\n",
143 " 4.40761407e+03 3.59132287e+04 2.92620900e+05]\n",
144 " [1.00000000e+00 2.59103578e+00 6.71346643e+00 1.73948317e+01\n",
145 " 4.50706315e+01 1.16779619e+02 3.02580171e+02]\n",
146 " [1.00000000e+00 3.52810469e-01 1.24475227e-01 4.39161633e-02\n",
147 " 1.54940822e-02 5.46647440e-03 1.92862940e-03]\n",
148 " [1.00000000e+00 3.37597300e+00 1.13971937e+01 3.84766180e+01\n",
149 " 1.29896023e+02 4.38525467e+02 1.48045014e+03]\n",
150 " [1.00000000e+00 8.72363612e+00 7.61018271e+01 6.63884647e+02\n",
151 " 5.79148809e+03 5.05228346e+04 4.40742825e+05]]\n",
152 "9\n",
153 "[[1.00000000e+00 1.00887726e+01 1.01783334e+02 1.02686891e+03\n",
154 " 1.03598470e+04 1.04518141e+05 1.05445976e+06 1.06382048e+07\n",
155 " 1.07326429e+08 1.08279195e+09]\n",
156 " [1.00000000e+00 3.23065446e+00 1.04371282e+01 3.37187547e+01\n",
157 " 1.08933645e+02 3.51926966e+02 1.13695442e+03 3.67310687e+03\n",
158 " 1.18665391e+04 3.83366873e+04]\n",
159 " [1.00000000e+00 1.62431903e+00 2.63841230e+00 4.28562329e+00\n",
160 " 6.96121945e+00 1.13072412e+01 1.83665670e+01 2.98331642e+01\n",
161 " 4.84585762e+01 7.87121872e+01]\n",
162 " [1.00000000e+00 9.31004929e+00 8.66770178e+01 8.06967308e+02\n",
163 " 7.51290541e+03 6.99455197e+04 6.51196236e+05 6.06266905e+06\n",
164 " 5.64437477e+07 5.25494073e+08]\n",
165 " [1.00000000e+00 7.17166586e+00 5.14327912e+01 3.68858792e+02\n",
166 " 2.64533201e+03 1.89714372e+04 1.36056809e+05 9.75753969e+05\n",
167 " 6.99778143e+06 5.01857501e+07]\n",
168 " [1.00000000e+00 4.96972856e+00 2.46982019e+01 1.22743360e+02\n",
169 " 6.10001179e+02 3.03154028e+03 1.50659323e+04 7.48735941e+04\n",
170 " 3.72101439e+05 1.84924315e+06]\n",
171 " [1.00000000e+00 8.14799756e+00 6.63898642e+01 5.40944452e+02\n",
172 " 4.40761407e+03 3.59132287e+04 2.92620900e+05 2.38427438e+06\n",
173 " 1.94270618e+07 1.58291652e+08]\n",
174 " [1.00000000e+00 2.59103578e+00 6.71346643e+00 1.73948317e+01\n",
175 " 4.50706315e+01 1.16779619e+02 3.02580171e+02 7.83996051e+02\n",
176 " 2.03136182e+03 5.26333117e+03]\n",
177 " [1.00000000e+00 3.52810469e-01 1.24475227e-01 4.39161633e-02\n",
178 " 1.54940822e-02 5.46647440e-03 1.92862940e-03 6.80440643e-04\n",
179 " 2.40066583e-04 8.46980036e-05]\n",
180 " [1.00000000e+00 3.37597300e+00 1.13971937e+01 3.84766180e+01\n",
181 " 1.29896023e+02 4.38525467e+02 1.48045014e+03 4.99795968e+03\n",
182 " 1.68729769e+04 5.69627144e+04]\n",
183 " [1.00000000e+00 8.72363612e+00 7.61018271e+01 6.63884647e+02\n",
184 " 5.79148809e+03 5.05228346e+04 4.40742825e+05 3.84488003e+06\n",
185 " 3.35413343e+07 2.92602395e+08]]\n"
186 ]
187 },
188 {
189 "data": {
190 "text/plain": [
191 "9"
192 ]
193 },
194 "execution_count": 5,
195 "metadata": {},
196 "output_type": "execute_result"
197 }
198 ],
199 "source": [
200 "def answer_one():\n",
201 " from sklearn.linear_model import LinearRegression\n",
202 " from sklearn.preprocessing import PolynomialFeatures\n",
203 " # To capture interactions between the original features by adding them as features to the linear model.\n",
204 " \n",
205 " clf = LinearRegression() # Initialize linear classifier\n",
206 " preds = np.zeros((4,100)) # Final tuple with predictions for all orders.\n",
207 " X_input = np.linspace(0,10,100) # Given requirement\n",
208 " orders = [1,3,6,9] # Given requirement\n",
209 " \n",
210 " for i in range(len(orders)):\n",
211 " poly = PolynomialFeatures(orders[i]) # Object to add polynomial features.\n",
212 " \n",
213 " # Add polynomial features to training data and input data:\n",
214 " # Need to transpose X_train and X_input for poly_fit to work.\n",
215 " X_train_poly = poly.fit_transform(X_train[None].T)\n",
216 " X_input_poly = poly.fit_transform(X_input[None].T)\n",
217 " print(orders[i])\n",
218 " print(X_train_poly)\n",
219 " # Train linear regression classifier with training data:\n",
220 " clf.fit(X_train_poly, y_train)\n",
221 " \n",
222 " # Get predictions from linear classifier using transformed input data:\n",
223 " # This is still a weighted linear combination of features, so it's still a linear model, and can use same least-squares estimation method for w and b.\n",
224 " preds[i,:] = clf.predict(X_input_poly)\n",
225 " \n",
226 " return orders[i]\n",
227 "\n",
228 "answer_one()"
229 ]
230 },
231 {
232 "cell_type": "code",
233 "execution_count": 4,
234 "metadata": {},
235 "outputs": [],
236 "source": [
237 "# feel free to use the function plot_one() to replicate the figure \n",
238 "# from the prompt once you have completed question one\n",
239 "def plot_one(degree_predictions):\n",
240 " plt.figure(figsize=(10,5))\n",
241 " plt.plot(X_train, y_train, 'o', label='training data', markersize=10)\n",
242 " plt.plot(X_test, y_test, 'o', label='test data', markersize=10)\n",
243 " for i,degree in enumerate([1,3,6,9]): # i is the index of the content (used for iteration in the for loop), degree is the content.\n",
244 " plt.plot(np.linspace(0,10,100), degree_predictions[i], alpha=0.8, lw=2, label='degree={}'.format(degree))\n",
245 " plt.ylim(-1,2.5)\n",
246 " plt.legend(loc=4)\n",
247 "\n",
248 "#plot_one(answer_one())"
249 ]
250 },
251 {
252 "cell_type": "markdown",
253 "metadata": {},
254 "source": [
255 "### Question 2\n",
256 "\n",
257 "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",
258 "\n",
259 "*This function should return one tuple of numpy arrays `(r2_train, r2_test)`. Both arrays should have shape `(10,)`*"
260 ]
261 },
262 {
263 "cell_type": "code",
264 "execution_count": 5,
265 "metadata": {},
266 "outputs": [
267 {
268 "data": {
269 "text/plain": [
270 "([0.0,\n",
271 " 0.42924577812346632,\n",
272 " 0.4510998044408247,\n",
273 " 0.58719953687798465,\n",
274 " 0.91941944717693436,\n",
275 " 0.97578641430682345,\n",
276 " 0.99018233247950815,\n",
277 " 0.99352509278403633,\n",
278 " 0.99637545387765036,\n",
279 " 0.99803706256653058],\n",
280 " [-0.47808641737141788,\n",
281 " -0.45237104233936676,\n",
282 " -0.068569841499158901,\n",
283 " 0.0053310529457363254,\n",
284 " 0.73004942818707141,\n",
285 " 0.87708300916999382,\n",
286 " 0.92140939814150025,\n",
287 " 0.92021504127165776,\n",
288 " 0.63247950833243671,\n",
289 " -0.64525377099038894])"
290 ]
291 },
292 "execution_count": 5,
293 "metadata": {},
294 "output_type": "execute_result"
295 }
296 ],
297 "source": [
298 "def answer_two():\n",
299 " from sklearn.linear_model import LinearRegression\n",
300 " from sklearn.preprocessing import PolynomialFeatures\n",
301 " from sklearn.metrics.regression import r2_score\n",
302 " \n",
303 " r2_test, r2_train = [],[]\n",
304 " \n",
305 " for i in range (10):\n",
306 " poly = PolynomialFeatures(i)\n",
307 " X_train_poly = poly.fit_transform(X_train[None].T)\n",
308 " X_test_poly = poly.fit_transform(X_test[None].T)\n",
309 " linreg = LinearRegression().fit(X_train_poly,y_train)\n",
310 " r2_train.append(linreg.score(X_train_poly,y_train))\n",
311 " r2_test.append(linreg.score(X_test_poly,y_test))\n",
312 " \n",
313 " return (r2_train, r2_test)\n",
314 "\n",
315 "answer_two()"
316 ]
317 },
318 {
319 "cell_type": "markdown",
320 "metadata": {},
321 "source": [
322 "### Question 3\n",
323 "\n",
324 "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",
325 "\n",
326 "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",
327 "\n",
328 "*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).* "
329 ]
330 },
331 {
332 "cell_type": "code",
333 "execution_count": 6,
334 "metadata": {},
335 "outputs": [
336 {
337 "data": {
338 "text/plain": [
339 "(0, 9, 6)"
340 ]
341 },
342 "execution_count": 6,
343 "metadata": {},
344 "output_type": "execute_result"
345 }
346 ],
347 "source": [
348 "def answer_three():\n",
349 " \n",
350 " #(result_train, result_test) = answer_two()\n",
351 " #plt.figure(figsize=(10,5))\n",
352 " #plt.plot(range(0,10,1),result_train,'r',label='training data')\n",
353 " #plt.plot(range(0,10,1),result_test,'b',label='test data')\n",
354 " #plt.xlabel('Order')\n",
355 " #plt.ylabel('Score')\n",
356 " #plt.legend()\n",
357 " \n",
358 " return (0,9,6) \n",
359 "\n",
360 "answer_three()"
361 ]
362 },
363 {
364 "cell_type": "markdown",
365 "metadata": {},
366 "source": [
367 "### Question 4\n",
368 "\n",
369 "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",
370 "\n",
371 "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",
372 "\n",
373 "*This function should return one tuple `(LinearRegression_R2_test_score, Lasso_R2_test_score)`*"
374 ]
375 },
376 {
377 "cell_type": "code",
378 "execution_count": 13,
379 "metadata": {},
380 "outputs": [
381 {
382 "name": "stderr",
383 "output_type": "stream",
384 "text": [
385 "/opt/conda/lib/python3.6/site-packages/sklearn/linear_model/coordinate_descent.py:484: ConvergenceWarning: Objective did not converge. You might want to increase the number of iterations. Fitting data with very small alpha may cause precision problems.\n",
386 " ConvergenceWarning)\n"
387 ]
388 },
389 {
390 "data": {
391 "text/plain": [
392 "(-4.3120017974975458, 0.8406625614750235)"
393 ]
394 },
395 "execution_count": 13,
396 "metadata": {},
397 "output_type": "execute_result"
398 }
399 ],
400 "source": [
401 "def answer_four():\n",
402 " \n",
403 " from sklearn.preprocessing import PolynomialFeatures\n",
404 " from sklearn.linear_model import Lasso, LinearRegression\n",
405 " from sklearn.metrics.regression import r2_score\n",
406 "\n",
407 " poly = PolynomialFeatures(12)\n",
408 " X_train_poly = poly.fit_transform(X_train[None].T)\n",
409 " X_test_poly = poly.fit_transform(X_test[None].T)\n",
410 " \n",
411 " linreg = LinearRegression().fit(X_train_poly,y_train)\n",
412 " linlasso = Lasso(alpha=0.01,max_iter=10000).fit(X_train_poly,y_train)\n",
413 " \n",
414 " # Asked to find score for TEST SET!\n",
415 " return (linreg.score(X_test_poly,y_test),linlasso.score(X_test_poly,y_test))\n",
416 "\n",
417 "answer_four()"
418 ]
419 },
420 {
421 "cell_type": "markdown",
422 "metadata": {},
423 "source": [
424 "## Part 2 - Classification\n",
425 "\n",
426 "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 `readonly/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",
427 "\n",
428 "*Attribute Information:*\n",
429 "\n",
430 "1. cap-shape: bell=b, conical=c, convex=x, flat=f, knobbed=k, sunken=s \n",
431 "2. cap-surface: fibrous=f, grooves=g, scaly=y, smooth=s \n",
432 "3. cap-color: brown=n, buff=b, cinnamon=c, gray=g, green=r, pink=p, purple=u, red=e, white=w, yellow=y \n",
433 "4. bruises?: bruises=t, no=f \n",
434 "5. odor: almond=a, anise=l, creosote=c, fishy=y, foul=f, musty=m, none=n, pungent=p, spicy=s \n",
435 "6. gill-attachment: attached=a, descending=d, free=f, notched=n \n",
436 "7. gill-spacing: close=c, crowded=w, distant=d \n",
437 "8. gill-size: broad=b, narrow=n \n",
438 "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",
439 "10. stalk-shape: enlarging=e, tapering=t \n",
440 "11. stalk-root: bulbous=b, club=c, cup=u, equal=e, rhizomorphs=z, rooted=r, missing=? \n",
441 "12. stalk-surface-above-ring: fibrous=f, scaly=y, silky=k, smooth=s \n",
442 "13. stalk-surface-below-ring: fibrous=f, scaly=y, silky=k, smooth=s \n",
443 "14. stalk-color-above-ring: brown=n, buff=b, cinnamon=c, gray=g, orange=o, pink=p, red=e, white=w, yellow=y \n",
444 "15. stalk-color-below-ring: brown=n, buff=b, cinnamon=c, gray=g, orange=o, pink=p, red=e, white=w, yellow=y \n",
445 "16. veil-type: partial=p, universal=u \n",
446 "17. veil-color: brown=n, orange=o, white=w, yellow=y \n",
447 "18. ring-number: none=n, one=o, two=t \n",
448 "19. ring-type: cobwebby=c, evanescent=e, flaring=f, large=l, none=n, pendant=p, sheathing=s, zone=z \n",
449 "20. spore-print-color: black=k, brown=n, buff=b, chocolate=h, green=r, orange=o, purple=u, white=w, yellow=y \n",
450 "21. population: abundant=a, clustered=c, numerous=n, scattered=s, several=v, solitary=y \n",
451 "22. habitat: grasses=g, leaves=l, meadows=m, paths=p, urban=u, waste=w, woods=d\n",
452 "\n",
453 "<br>\n",
454 "\n",
455 "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. "
456 ]
457 },
458 {
459 "cell_type": "code",
460 "execution_count": 9,
461 "metadata": {},
462 "outputs": [],
463 "source": [
464 "import pandas as pd\n",
465 "import numpy as np\n",
466 "from sklearn.model_selection import train_test_split\n",
467 "\n",
468 "mush_df = pd.read_csv('mushrooms.csv')\n",
469 "mush_df2 = pd.get_dummies(mush_df)\n",
470 "\n",
471 "X_mush = mush_df2.iloc[:,2:]\n",
472 "y_mush = mush_df2.iloc[:,1]\n",
473 "\n",
474 "# use the variables X_train2, y_train2 for Question 5\n",
475 "X_train2, X_test2, y_train2, y_test2 = train_test_split(X_mush, y_mush, random_state=0)\n",
476 "\n",
477 "# For performance reasons in Questions 6 and 7, we will create a smaller version of the\n",
478 "# entire mushroom dataset for use in those questions. For simplicity we'll just re-use\n",
479 "# the 25% test split created above as the representative subset.\n",
480 "#\n",
481 "# Use the variables X_subset, y_subset for Questions 6 and 7.\n",
482 "X_subset = X_test2\n",
483 "y_subset = y_test2\n",
484 "\n",
485 "#mush_df"
486 ]
487 },
488 {
489 "cell_type": "markdown",
490 "metadata": {},
491 "source": [
492 "### Question 5\n",
493 "\n",
494 "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",
495 "\n",
496 "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",
497 "\n",
498 "*This function should return a list of length 5 containing the feature names in descending order of importance.*\n",
499 "\n",
500 "*Note: remember that you also need to set random_state in the DecisionTreeClassifier.*"
501 ]
502 },
503 {
504 "cell_type": "code",
505 "execution_count": 10,
506 "metadata": {},
507 "outputs": [
508 {
509 "ename": "AttributeError",
510 "evalue": "'DataFrame' object has no attribute 'sort'",
511 "output_type": "error",
512 "traceback": [
513 "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
514 "\u001b[1;31mAttributeError\u001b[0m Traceback (most recent call last)",
515 "\u001b[1;32m<ipython-input-10-5ffb92d7848b>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m\u001b[0m\n\u001b[0;32m 9\u001b[0m \u001b[1;32mreturn\u001b[0m \u001b[0mdf\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0msort\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m[\u001b[0m\u001b[1;34m'feature importance'\u001b[0m\u001b[1;33m]\u001b[0m\u001b[1;33m,\u001b[0m\u001b[0mascending\u001b[0m\u001b[1;33m=\u001b[0m\u001b[1;36m0\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m[\u001b[0m\u001b[1;34m'feature'\u001b[0m\u001b[1;33m]\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mhead\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;36m5\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mtolist\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 10\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m---> 11\u001b[1;33m \u001b[0manswer_five\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m",
516 "\u001b[1;32m<ipython-input-10-5ffb92d7848b>\u001b[0m in \u001b[0;36manswer_five\u001b[1;34m()\u001b[0m\n\u001b[0;32m 7\u001b[0m \u001b[0mclf\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mDecisionTreeClassifier\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mrandom_state\u001b[0m\u001b[1;33m=\u001b[0m\u001b[1;36m0\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mfit\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mX_train2\u001b[0m\u001b[1;33m,\u001b[0m\u001b[0my_train2\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 8\u001b[0m \u001b[0mdf\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mpd\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mDataFrame\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m{\u001b[0m\u001b[1;34m'feature'\u001b[0m\u001b[1;33m:\u001b[0m\u001b[0mX_train2\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mcolumns\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mvalues\u001b[0m\u001b[1;33m,\u001b[0m \u001b[1;34m'feature importance'\u001b[0m\u001b[1;33m:\u001b[0m \u001b[0mclf\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mfeature_importances_\u001b[0m\u001b[1;33m}\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 9\u001b[1;33m \u001b[1;32mreturn\u001b[0m \u001b[0mdf\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0msort\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m[\u001b[0m\u001b[1;34m'feature importance'\u001b[0m\u001b[1;33m]\u001b[0m\u001b[1;33m,\u001b[0m\u001b[0mascending\u001b[0m\u001b[1;33m=\u001b[0m\u001b[1;36m0\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m[\u001b[0m\u001b[1;34m'feature'\u001b[0m\u001b[1;33m]\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mhead\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;36m5\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mtolist\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m 10\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 11\u001b[0m \u001b[0manswer_five\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n",
517 "\u001b[1;32m~\\anaconda3\\lib\\site-packages\\pandas\\core\\generic.py\u001b[0m in \u001b[0;36m__getattr__\u001b[1;34m(self, name)\u001b[0m\n\u001b[0;32m 5463\u001b[0m \u001b[1;32mif\u001b[0m \u001b[0mself\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0m_info_axis\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0m_can_hold_identifiers_and_holds_name\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mname\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 5464\u001b[0m \u001b[1;32mreturn\u001b[0m \u001b[0mself\u001b[0m\u001b[1;33m[\u001b[0m\u001b[0mname\u001b[0m\u001b[1;33m]\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m-> 5465\u001b[1;33m \u001b[1;32mreturn\u001b[0m \u001b[0mobject\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0m__getattribute__\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mself\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mname\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m 5466\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 5467\u001b[0m \u001b[1;32mdef\u001b[0m \u001b[0m__setattr__\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mself\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mname\u001b[0m\u001b[1;33m:\u001b[0m \u001b[0mstr\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mvalue\u001b[0m\u001b[1;33m)\u001b[0m \u001b[1;33m->\u001b[0m \u001b[1;32mNone\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n",
518 "\u001b[1;31mAttributeError\u001b[0m: 'DataFrame' object has no attribute 'sort'"
519 ]
520 }
521 ],
522 "source": [
523 "# Feature names in X_train2.columns and feature_importances_ are in the same order. NOT SORTED!!\n",
524 "# Sort feature names by feature_importances_ !!\n",
525 "\n",
526 "def answer_five():\n",
527 " \n",
528 " from sklearn.tree import DecisionTreeClassifier\n",
529 " clf = DecisionTreeClassifier(random_state=0).fit(X_train2,y_train2)\n",
530 " df = pd.DataFrame({'feature':X_train2.columns.values, 'feature importance': clf.feature_importances_})\n",
531 " return df.sort(['feature importance'],ascending=0)['feature'].head(5).tolist()\n",
532 "\n",
533 "answer_five()"
534 ]
535 },
536 {
537 "cell_type": "markdown",
538 "metadata": {},
539 "source": [
540 "### Question 6\n",
541 "\n",
542 "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",
543 "\n",
544 "**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",
545 "\n",
546 "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",
547 "\n",
548 "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",
549 "\n",
550 "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",
551 "\n",
552 "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",
553 "\n",
554 "e.g.\n",
555 "\n",
556 "if one of your array of scores is\n",
557 "\n",
558 " array([[ 0.5, 0.4, 0.6],\n",
559 " [ 0.7, 0.8, 0.7],\n",
560 " [ 0.9, 0.8, 0.8],\n",
561 " [ 0.8, 0.7, 0.8],\n",
562 " [ 0.7, 0.6, 0.6],\n",
563 " [ 0.4, 0.6, 0.5]])\n",
564 " \n",
565 "it should then become\n",
566 "\n",
567 " array([ 0.5, 0.73333333, 0.83333333, 0.76666667, 0.63333333, 0.5])\n",
568 "\n",
569 "*This function should return one tuple of numpy arrays `(training_scores, test_scores)` where each array in the tuple has shape `(6,)`.*"
570 ]
571 },
572 {
573 "cell_type": "code",
574 "execution_count": 11,
575 "metadata": {},
576 "outputs": [
577 {
578 "data": {
579 "text/plain": [
580 "(array([0.83370474, 0.93943926, 0.99101417, 1. , 1. ,\n",
581 " 1. ]),\n",
582 " array([0.83160092, 0.93747958, 0.9901502 , 1. , 0.99852459,\n",
583 " 0.52240229]))"
584 ]
585 },
586 "execution_count": 11,
587 "metadata": {},
588 "output_type": "execute_result"
589 }
590 ],
591 "source": [
592 "def answer_six():\n",
593 " \n",
594 " from sklearn.svm import SVC\n",
595 " from sklearn.model_selection import validation_curve\n",
596 " \n",
597 " # RBF kernel and C=1 are default anyway.\n",
598 " param_range = np.logspace(-4,1,6)\n",
599 " train_scores, test_scores = validation_curve(SVC(random_state=0),X_subset,y_subset,param_name='gamma',param_range=param_range)\n",
600 " \n",
601 " # Finds row-wise mean (i.e mean across column values).\n",
602 " return np.array(list(map(np.mean,train_scores))),np.array(list(map(np.mean,test_scores)))\n",
603 "\n",
604 "answer_six()"
605 ]
606 },
607 {
608 "cell_type": "markdown",
609 "metadata": {},
610 "source": [
611 "### Question 7\n",
612 "\n",
613 "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",
614 "\n",
615 "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",
616 "\n",
617 "*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.*"
618 ]
619 },
620 {
621 "cell_type": "code",
622 "execution_count": 11,
623 "metadata": {},
624 "outputs": [
625 {
626 "data": {
627 "text/plain": [
628 "(0.0001, 10, 0.1)"
629 ]
630 },
631 "execution_count": 11,
632 "metadata": {},
633 "output_type": "execute_result"
634 }
635 ],
636 "source": [
637 "def answer_seven():\n",
638 " \n",
639 " #train_scores, test_scores = answer_six()\n",
640 " #plt.figure()\n",
641 " #plt.plot(np.logspace(-4,1,6),train_scores,'b',label='Training scores')\n",
642 " #plt.plot(np.logspace(-4,1,6),test_scores,'r',label='Test scores')\n",
643 " #plt.xscale('log') # Sets x axis to a log scale.\n",
644 " #plt.xlabel('Gamma')\n",
645 " #plt.ylabel('Scores')\n",
646 " #plt.legend()\n",
647 " \n",
648 " return (0.0001,10,0.1) \n",
649 "\n",
650 "answer_seven()"
651 ]
652 },
653 {
654 "cell_type": "code",
655 "execution_count": null,
656 "metadata": {},
657 "outputs": [],
658 "source": []
659 },
660 {
661 "cell_type": "code",
662 "execution_count": null,
663 "metadata": {},
664 "outputs": [],
665 "source": []
666 }
667 ],
668 "metadata": {
669 "coursera": {
670 "course_slug": "python-machine-learning",
671 "graded_item_id": "eWYHL",
672 "launcher_item_id": "BAqef",
673 "part_id": "fXXRp"
674 },
675 "kernelspec": {
676 "display_name": "Python 3",
677 "language": "python",
678 "name": "python3"
679 },
680 "language_info": {
681 "codemirror_mode": {
682 "name": "ipython",
683 "version": 3
684 },
685 "file_extension": ".py",
686 "mimetype": "text/x-python",
687 "name": "python",
688 "nbconvert_exporter": "python",
689 "pygments_lexer": "ipython3",
690 "version": "3.8.8"
691 }
692 },
693 "nbformat": 4,
694 "nbformat_minor": 2
695 }
696