{"cells":[{"cell_type":"markdown","id":"2e6762b5-6b8c-4ce9-ad41-92e4bcb6d8df","metadata":{},"outputs":[],"source":["

\n"," \n"," \"Skills\n"," \n","

\n","\n","\n","# Polynomial Regression\n","\n","\n","Estimated time needed: **15** minutes\n"," \n","\n","## Objectives\n","\n","After completing this lab you will be able to:\n","\n","* Use scikit-learn to implement Polynomial Regression\n","* Create a model, train it, test it and use the model\n"]},{"cell_type":"markdown","id":"e618a869-5310-4ba0-b490-c8e579f93c1c","metadata":{},"outputs":[],"source":["

Table of contents

\n","\n","
\n","
    \n","
  1. Downloading Data
  2. \n","
  3. Polynomial regression
  4. \n","
  5. Evaluation
  6. \n","
  7. Practice
  8. \n","
\n","
\n","
\n","
\n"]},{"cell_type":"markdown","id":"392f7014-a344-431e-9b8d-64cc6f1b0ade","metadata":{},"outputs":[],"source":["### Importing Needed packages\n"]},{"cell_type":"code","id":"bf6caec0-6da0-4325-b416-fe9c29afd1cb","metadata":{},"outputs":[],"source":["import matplotlib.pyplot as plt\nimport pandas as pd\nimport pylab as pl\nimport numpy as np\n%matplotlib inline\n"]},{"cell_type":"markdown","id":"f6af5655-0d6a-408f-8120-6b173d4e9bc1","metadata":{},"outputs":[],"source":["

Downloading Data

\n","To download the data, we will use !wget to download it from IBM Object Storage.\n"]},{"cell_type":"code","id":"e1931ff3-e73f-4816-8dfb-e8ac5aac8c34","metadata":{},"outputs":[],"source":["!wget -O FuelConsumption.csv https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-ML0101EN-SkillsNetwork/labs/Module%202/data/FuelConsumptionCo2.csv"]},{"cell_type":"markdown","id":"f748b822-0e87-485b-91bc-bf4eaebe65da","metadata":{},"outputs":[],"source":["__Did you know?__ When it comes to Machine Learning, you will likely be working with large datasets. As a business, where can you host your data? IBM is offering a unique opportunity for businesses, with 10 Tb of IBM Cloud Object Storage: [Sign up now for free](https://www.ibm.com/us-en/cloud/object-storage?utm_source=skills_network&utm_content=in_lab_content_link&utm_id=Lab-IBMDeveloperSkillsNetwork-ML0101EN-SkillsNetwork)\n"]},{"cell_type":"markdown","id":"8e80841b-77f9-4bb2-b8b1-3497973e5e13","metadata":{},"outputs":[],"source":["\n","## Understanding the Data\n","\n","### `FuelConsumption.csv`:\n","We have downloaded a fuel consumption dataset, **`FuelConsumption.csv`**, which contains model-specific fuel consumption ratings and estimated carbon dioxide emissions for new light-duty vehicles for retail sale in Canada. [Dataset source](http://open.canada.ca/data/en/dataset/98f1a129-f628-4ce4-b24d-6f16bf24dd64)\n","\n","- **MODELYEAR** e.g. 2014\n","- **MAKE** e.g. Acura\n","- **MODEL** e.g. ILX\n","- **VEHICLE CLASS** e.g. SUV\n","- **ENGINE SIZE** e.g. 4.7\n","- **CYLINDERS** e.g 6\n","- **TRANSMISSION** e.g. A6\n","- **FUEL CONSUMPTION in CITY(L/100 km)** e.g. 9.9\n","- **FUEL CONSUMPTION in HWY (L/100 km)** e.g. 8.9\n","- **FUEL CONSUMPTION COMB (L/100 km)** e.g. 9.2\n","- **CO2 EMISSIONS (g/km)** e.g. 182 --> low --> 0\n"]},{"cell_type":"markdown","id":"01d4769f-560a-4fa4-98ed-1d3745686717","metadata":{},"outputs":[],"source":["## Reading the data in\n"]},{"cell_type":"code","id":"3f105bf0-8870-4df8-9cc7-a6e33c0d5383","metadata":{},"outputs":[],"source":["df = pd.read_csv(\"FuelConsumption.csv\")\n\n# take a look at the dataset\ndf.head()"]},{"cell_type":"markdown","id":"93280331-49b0-42a2-b311-6b249758130b","metadata":{},"outputs":[],"source":["Let's select some features that we want to use for regression.\n"]},{"cell_type":"code","id":"2c5f0bc6-c86f-4009-bf7b-bf2f20873e6a","metadata":{},"outputs":[],"source":["cdf = df[['ENGINESIZE','CYLINDERS','FUELCONSUMPTION_COMB','CO2EMISSIONS']]\ncdf.head(9)"]},{"cell_type":"markdown","id":"55ec7be8-812d-42d7-8dd7-c59aa947ac67","metadata":{},"outputs":[],"source":["Let's plot Emission values with respect to Engine size:\n"]},{"cell_type":"code","id":"d1f7a5f2-859c-4d08-b9ec-139174e33618","metadata":{},"outputs":[],"source":["plt.scatter(cdf.ENGINESIZE, cdf.CO2EMISSIONS, color='blue')\nplt.xlabel(\"Engine size\")\nplt.ylabel(\"Emission\")\nplt.show()"]},{"cell_type":"markdown","id":"aa3dbb2a-b254-495a-9c32-c25318dbf259","metadata":{},"outputs":[],"source":["#### Creating train and test dataset\n","Train/Test Split involves splitting the dataset into training and testing sets respectively, which are mutually exclusive. After which, you train with the training set and test with the testing set.\n"]},{"cell_type":"code","id":"041baf27-177d-43ac-86e8-aa8da671de60","metadata":{},"outputs":[],"source":["msk = np.random.rand(len(df)) < 0.8\ntrain = cdf[msk]\ntest = cdf[~msk]"]},{"cell_type":"markdown","id":"4aba329a-721c-4191-b33d-d23f7c35e096","metadata":{},"outputs":[],"source":["

Polynomial regression

\n"]},{"cell_type":"markdown","id":"650dc952-826f-4585-961d-c3ecf3fc0973","metadata":{},"outputs":[],"source":["Sometimes, the trend of data is not really linear, and looks curvy. In this case we can use Polynomial regression methods. In fact, many different regressions exist that can be used to fit whatever the dataset looks like, such as quadratic, cubic, and so on, and it can go on and on to infinite degrees.\n","\n","In essence, we can call all of these, polynomial regression, where the relationship between the independent variable x and the dependent variable y is modeled as an nth degree polynomial in x. Lets say you want to have a polynomial regression (let's make 2 degree polynomial):\n","\n","\n","$$y = b + \\theta_1 x + \\theta_2 x^2$$\n","\n","\n","\n","Now, the question is: how we can fit our data on this equation while we have only x values, such as __Engine Size__? \n","Well, we can create a few additional features: 1, $x$, and $x^2$.\n","\n","\n","\n","__PolynomialFeatures()__ function in Scikit-learn library, drives a new feature sets from the original feature set. That is, a matrix will be generated consisting of all polynomial combinations of the features with degree less than or equal to the specified degree. For example, lets say the original feature set has only one feature, _ENGINESIZE_. Now, if we select the degree of the polynomial to be 2, then it generates 3 features, degree=0, degree=1 and degree=2: \n"]},{"cell_type":"code","id":"be8fb5a0-3b0b-4dd2-b38d-215c43d1da8b","metadata":{},"outputs":[],"source":["from sklearn.preprocessing import PolynomialFeatures\nfrom sklearn import linear_model\ntrain_x = np.asanyarray(train[['ENGINESIZE']])\ntrain_y = np.asanyarray(train[['CO2EMISSIONS']])\n\ntest_x = np.asanyarray(test[['ENGINESIZE']])\ntest_y = np.asanyarray(test[['CO2EMISSIONS']])\n\n\npoly = PolynomialFeatures(degree=2)\ntrain_x_poly = poly.fit_transform(train_x)\ntrain_x_poly"]},{"cell_type":"markdown","id":"3487a10a-f2d0-4a17-93da-5b8397b03af9","metadata":{},"outputs":[],"source":["**fit_transform** takes our x values, and output a list of our data raised from power of 0 to power of 2 (since we set the degree of our polynomial to 2). \n","\n","The equation and the sample example is displayed below. \n","\n","\n","$$\n","\\begin{bmatrix}\n"," v_1\\\\\\\\\\\\\n"," v_2\\\\\\\\\n"," \\vdots\\\\\\\\\n"," v_n\n","\\end{bmatrix}\\longrightarrow \\begin{bmatrix}\n"," [ 1 & v_1 & v_1^2]\\\\\\\\\n"," [ 1 & v_2 & v_2^2]\\\\\\\\\n"," \\vdots & \\vdots & \\vdots\\\\\\\\\n"," [ 1 & v_n & v_n^2]\n","\\end{bmatrix}\n","$$\n","\n","\n","\n","\n","$$\n","\\begin{bmatrix}\n"," 2.\\\\\\\\\n"," 2.4\\\\\\\\\n"," 1.5\\\\\\\\\n"," \\vdots\n","\\end{bmatrix} \\longrightarrow \\begin{bmatrix}\n"," [ 1 & 2. & 4.]\\\\\\\\\n"," [ 1 & 2.4 & 5.76]\\\\\\\\\n"," [ 1 & 1.5 & 2.25]\\\\\\\\\n"," \\vdots & \\vdots & \\vdots\\\\\\\\\n","\\end{bmatrix}\n","$$\n","\n","\n","\n","\n","\n"]},{"cell_type":"markdown","id":"7e8aea33-3093-43ec-b672-d87876c1934d","metadata":{},"outputs":[],"source":["It looks like feature sets for multiple linear regression analysis, right? Yes. It Does. \n","Indeed, Polynomial regression is a special case of linear regression, with the main idea of how do you select your features. Just consider replacing the $x$ with $x_1$, $x_1^2$ with $x_2$, and so on. Then the 2nd degree equation would be turn into:\n","\n","$$y = b + \\theta_1 x_1 + \\theta_2 x_2$$\n","\n","Now, we can deal with it as a 'linear regression' problem. Therefore, this polynomial regression is considered to be a special case of traditional multiple linear regression. So, you can use the same mechanism as linear regression to solve such problems. \n","\n","\n","\n","so we can use __LinearRegression()__ function to solve it:\n"]},{"cell_type":"code","id":"c791a9c5-c04d-42c6-a969-2733b7e7efb5","metadata":{},"outputs":[],"source":["clf = linear_model.LinearRegression()\ntrain_y_ = clf.fit(train_x_poly, train_y)\n# The coefficients\nprint ('Coefficients: ', clf.coef_)\nprint ('Intercept: ',clf.intercept_)"]},{"cell_type":"markdown","id":"2fc70f08-4833-4909-b248-1bca75dd98aa","metadata":{},"outputs":[],"source":["As mentioned before, __Coefficient__ and __Intercept__ , are the parameters of the fit curvy line. \n","Given that it is a typical multiple linear regression, with 3 parameters, and knowing that the parameters are the intercept and coefficients of hyperplane, sklearn has estimated them from our new set of feature sets. Lets plot it:\n"]},{"cell_type":"code","id":"024baf01-2cc6-4c84-aea6-eac7878503ee","metadata":{},"outputs":[],"source":["plt.scatter(train.ENGINESIZE, train.CO2EMISSIONS, color='blue')\nXX = np.arange(0.0, 10.0, 0.1)\nyy = clf.intercept_[0]+ clf.coef_[0][1]*XX+ clf.coef_[0][2]*np.power(XX, 2)\nplt.plot(XX, yy, '-r' )\nplt.xlabel(\"Engine size\")\nplt.ylabel(\"Emission\")"]},{"cell_type":"markdown","id":"a34efe55-de31-4429-8a29-22ea5e53dfc7","metadata":{},"outputs":[],"source":["

Evaluation

\n"]},{"cell_type":"code","id":"147f62a3-ef21-4232-bcf3-06895af65885","metadata":{},"outputs":[],"source":["from sklearn.metrics import r2_score\n\ntest_x_poly = poly.transform(test_x)\ntest_y_ = clf.predict(test_x_poly)\n\nprint(\"Mean absolute error: %.2f\" % np.mean(np.absolute(test_y_ - test_y)))\nprint(\"Residual sum of squares (MSE): %.2f\" % np.mean((test_y_ - test_y) ** 2))\nprint(\"R2-score: %.2f\" % r2_score(test_y,test_y_ ) )"]},{"cell_type":"markdown","id":"ed1a2376-423d-4865-a162-adfa3aa6c300","metadata":{},"outputs":[],"source":["

Practice

\n","Try to use a polynomial regression with the dataset but this time with degree three (cubic). Does it result in better accuracy?\n"]},{"cell_type":"code","id":"44e40472-db2b-40b8-9154-9ca9c86665f6","metadata":{},"outputs":[],"source":["# write your code here\n"]},{"cell_type":"markdown","id":"52a5872c-4f67-4520-83d2-69dcace137c8","metadata":{},"outputs":[],"source":["
Click here for the solution\n","\n","```python \n","poly3 = PolynomialFeatures(degree=3)\n","train_x_poly3 = poly3.fit_transform(train_x)\n","clf3 = linear_model.LinearRegression()\n","train_y3_ = clf3.fit(train_x_poly3, train_y)\n","\n","# The coefficients\n","print ('Coefficients: ', clf3.coef_)\n","print ('Intercept: ',clf3.intercept_)\n","plt.scatter(train.ENGINESIZE, train.CO2EMISSIONS, color='blue')\n","XX = np.arange(0.0, 10.0, 0.1)\n","yy = clf3.intercept_[0]+ clf3.coef_[0][1]*XX + clf3.coef_[0][2]*np.power(XX, 2) + clf3.coef_[0][3]*np.power(XX, 3)\n","plt.plot(XX, yy, '-r' )\n","plt.xlabel(\"Engine size\")\n","plt.ylabel(\"Emission\")\n","test_x_poly3 = poly3.transform(test_x)\n","test_y3_ = clf3.predict(test_x_poly3)\n","print(\"Mean absolute error: %.2f\" % np.mean(np.absolute(test_y3_ - test_y)))\n","print(\"Residual sum of squares (MSE): %.2f\" % np.mean((test_y3_ - test_y) ** 2))\n","print(\"R2-score: %.2f\" % r2_score(test_y,test_y3_ ) )\n","\n","```\n","\n","
\n"]},{"cell_type":"code","id":"587e67ef-13d6-4074-b453-a9cec18a1c7a","metadata":{},"outputs":[],"source":[""]},{"cell_type":"markdown","id":"8c8879bf-1012-49a8-89b3-7f26e6eaa711","metadata":{},"outputs":[],"source":["

Want to learn more?

\n","\n","IBM SPSS Modeler is a comprehensive analytics platform that has many machine learning algorithms. It has been designed to bring predictive intelligence to decisions made by individuals, by groups, by systems – by your enterprise as a whole. A free trial is available through this course, available here: SPSS Modeler\n","\n","Also, you can use Watson Studio to run these notebooks faster with bigger datasets. Watson Studio is IBM's leading cloud solution for data scientists, built by data scientists. With Jupyter notebooks, RStudio, Apache Spark and popular libraries pre-packaged in the cloud, Watson Studio enables data scientists to collaborate on their projects without having to install anything. Join the fast-growing community of Watson Studio users today with a free account at Watson Studio\n","\n"]},{"cell_type":"markdown","id":"a944585d-72ba-4f20-a2d9-d0b1cbdc1970","metadata":{},"outputs":[],"source":["### Thank you for completing this lab!\n","\n","\n","## Author\n","\n","Saeed Aghabozorgi\n","\n","\n","### Other Contributors\n","\n","Joseph Santarcangelo\n","\n","\n","##

© IBM Corporation 2020. All rights reserved.

\n","\n","\n","\n","\n","\n"]},{"cell_type":"code","id":"6720e322-2f87-4db4-a31c-380f8048b35d","metadata":{},"outputs":[],"source":[""]}],"metadata":{"kernelspec":{"display_name":"Python","language":"python","name":"conda-env-python-py"},"language_info":{"name":"python","version":"3.7.12","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"prev_pub_hash":"4dc110debac287dfd374a575573c16e62a80a935b3bbe2b2f6d5a0598e6e33f6"},"nbformat":4,"nbformat_minor":4}