Praktikum_Machine_Learning/Regresi.machine_learning/Aryo Saputro-202310715049-Multiple Linear Regression.ipynb

1 line
12 KiB
Plaintext
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

{"cells":[{"cell_type":"markdown","id":"8bce3099-03e1-483b-a739-b6fd4a4641a1","metadata":{},"outputs":[],"source":["<p style=\"text-align:center\">\n"," <a href=\"https://skills.network\" target=\"_blank\">\n"," <img src=\"https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/assets/logos/SN_web_lightmode.png\" width=\"200\" alt=\"Skills Network Logo\">\n"," </a>\n","</p>\n","\n","\n","# Multiple Linear 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 Multiple Linear Regression\n","* Create a model, train it, test it and use the model\n"]},{"cell_type":"markdown","id":"d17ffc46-1ae1-415b-8b99-dc821caea88c","metadata":{},"outputs":[],"source":["<h1>Table of contents</h1>\n","\n","<div class=\"alert alert-block alert-info\" style=\"margin-top: 20px\">\n"," <ol>\n"," <li><a href=\"#understanding-data\">Understanding the Data</a></li>\n"," <li><a href=\"#reading_data\">Reading the Data in</a></li>\n"," <li><a href=\"#multiple_regression_model\">Multiple Regression Model</a></li>\n"," <li><a href=\"#prediction\">Prediction</a></li>\n"," <li><a href=\"#practice\">Practice</a></li>\n"," </ol>\n","</div>\n","<br>\n","<hr>\n"]},{"cell_type":"markdown","id":"858bb4d5-d752-4f8b-b76d-bfceb3e72218","metadata":{},"outputs":[],"source":["### Importing Needed packages\n"]},{"cell_type":"code","id":"e05ef94a-2dc3-4d2c-89a6-2f8884e4ce1e","metadata":{},"outputs":[],"source":["import matplotlib.pyplot as plt\nimport pandas as pd\nimport pylab as pl\nimport numpy as np\n%matplotlib inline"]},{"cell_type":"markdown","id":"d2b035fe-ec1e-4095-9900-9ad9be9b2474","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":"c3d2fb99-a884-4dcf-9c01-30598945b60a","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":"e294be91-c42d-4b39-aac6-6a3f87fa4e63","metadata":{},"outputs":[],"source":["\n","<h2 id=\"understanding_data\">Understanding the Data</h2>\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","- **FUELTYPE** e.g. z\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":"44b30cef-a664-4f35-90b3-1204bd1d3436","metadata":{},"outputs":[],"source":["<h2 id=\"reading_data\">Reading the data in</h2>\n"]},{"cell_type":"code","id":"df4516c8-735a-4d8a-ace3-63d77d460f68","metadata":{},"outputs":[],"source":["df = pd.read_csv(\"FuelConsumption.csv\")\n\n# take a look at the dataset\ndf.head()"]},{"cell_type":"markdown","id":"8b62ca92-f920-4b47-b187-17a46c6fc2a2","metadata":{},"outputs":[],"source":["Let's select some features that we want to use for regression.\n"]},{"cell_type":"code","id":"0f8f2471-4d7c-4d9e-8ef8-370b1f3cbf0d","metadata":{},"outputs":[],"source":["cdf = df[['ENGINESIZE','CYLINDERS','FUELCONSUMPTION_CITY','FUELCONSUMPTION_HWY','FUELCONSUMPTION_COMB','CO2EMISSIONS']]\ncdf.head(9)"]},{"cell_type":"markdown","id":"a8795f9b-6e42-41c0-b43f-e2e267587793","metadata":{},"outputs":[],"source":["Let's plot Emission values with respect to Engine size:\n"]},{"cell_type":"code","id":"d0b68243-f269-4ca3-b646-59083d0c857e","metadata":{},"outputs":[],"source":["plt.scatter(cdf.ENGINESIZE, cdf.CO2EMISSIONS, color='blue')\nplt.xlabel(\"Engine size\")\nplt.ylabel(\"Emission\")\nplt.show()"]},{"cell_type":"markdown","id":"99acc3b8-151c-4ac8-b0c0-e19e3e80f051","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","This will provide a more accurate evaluation on out-of-sample accuracy because the testing dataset is not part of the dataset that have been used to train the model. Therefore, it gives us a better understanding of how well our model generalizes on new data.\n","\n","We know the outcome of each data point in the testing dataset, making it great to test with! Since this data has not been used to train the model, the model has no knowledge of the outcome of these data points. So, in essence, it is truly an out-of-sample testing.\n","\n","Let's split our dataset into train and test sets. Around 80% of the entire dataset will be used for training and 20% for testing. We create a mask to select random rows using the __np.random.rand()__ function: \n"]},{"cell_type":"code","id":"211d7935-ba34-4335-bade-f57057abdca2","metadata":{},"outputs":[],"source":["msk = np.random.rand(len(df)) < 0.8\ntrain = cdf[msk]\ntest = cdf[~msk]"]},{"cell_type":"markdown","id":"fb7b100e-fd1b-4d72-a67b-402507407e30","metadata":{},"outputs":[],"source":["#### Train data distribution\n"]},{"cell_type":"code","id":"a76455a7-e115-461a-b1a0-bf8521b237b6","metadata":{},"outputs":[],"source":["plt.scatter(train.ENGINESIZE, train.CO2EMISSIONS, color='blue')\nplt.xlabel(\"Engine size\")\nplt.ylabel(\"Emission\")\nplt.show()"]},{"cell_type":"markdown","id":"a6a3c826-bb47-4b58-972c-5da37ef553ab","metadata":{},"outputs":[],"source":["<h2 id=\"multiple_regression_model\">Multiple Regression Model</h2>\n"]},{"cell_type":"markdown","id":"139832c0-9ce0-44ca-8cf6-10d365e164c7","metadata":{},"outputs":[],"source":["In reality, there are multiple variables that impact the co2emission. When more than one independent variable is present, the process is called multiple linear regression. An example of multiple linear regression is predicting co2emission using the features FUELCONSUMPTION_COMB, EngineSize and Cylinders of cars. The good thing here is that multiple linear regression model is the extension of the simple linear regression model.\n"]},{"cell_type":"code","id":"3e64de0a-b876-4590-8ada-2afbc7783b03","metadata":{},"outputs":[],"source":["from sklearn import linear_model\nregr = linear_model.LinearRegression()\nx = np.asanyarray(train[['ENGINESIZE','CYLINDERS','FUELCONSUMPTION_COMB']])\ny = np.asanyarray(train[['CO2EMISSIONS']])\nregr.fit (x, y)\n# The coefficients\nprint ('Coefficients: ', regr.coef_)"]},{"cell_type":"markdown","id":"132e9ef1-d13e-43af-b52d-31de017438fc","metadata":{},"outputs":[],"source":["As mentioned before, __Coefficient__ and __Intercept__ are the parameters of the fitted line. \n","Given that it is a multiple linear regression model with 3 parameters and that the parameters are the intercept and coefficients of the hyperplane, sklearn can estimate them from our data. Scikit-learn uses plain Ordinary Least Squares method to solve this problem.\n","\n","#### Ordinary Least Squares (OLS)\n","OLS is a method for estimating the unknown parameters in a linear regression model. OLS chooses the parameters of a linear function of a set of explanatory variables by minimizing the sum of the squares of the differences between the target dependent variable and those predicted by the linear function. In other words, it tries to minimizes the sum of squared errors (SSE) or mean squared error (MSE) between the target variable (y) and our predicted output ($\\hat{y}$) over all samples in the dataset.\n","\n","OLS can find the best parameters using of the following methods:\n","* Solving the model parameters analytically using closed-form equations\n","* Using an optimization algorithm (Gradient Descent, Stochastic Gradient Descent, Newtons Method, etc.)\n"]},{"cell_type":"markdown","id":"93100117-7dd1-45ed-a99f-b13790aed707","metadata":{},"outputs":[],"source":["<h2 id=\"prediction\">Prediction</h2>\n"]},{"cell_type":"code","id":"33390fdd-2f81-401f-b2a2-1ed6299ccd6a","metadata":{},"outputs":[],"source":["y_hat= regr.predict(test[['ENGINESIZE','CYLINDERS','FUELCONSUMPTION_COMB']])\nx = np.asanyarray(test[['ENGINESIZE','CYLINDERS','FUELCONSUMPTION_COMB']])\ny = np.asanyarray(test[['CO2EMISSIONS']])\nprint(\"Mean Squared Error (MSE) : %.2f\"\n % np.mean((y_hat - y) ** 2))\n\n# Explained variance score: 1 is perfect prediction\nprint('Variance score: %.2f' % regr.score(x, y))"]},{"cell_type":"markdown","id":"12bd64a0-5c70-485e-821e-906cc730f914","metadata":{},"outputs":[],"source":["__Explained variance regression score:__ \n","Let $\\hat{y}$ be the estimated target output, y the corresponding (correct) target output, and Var be the Variance (the square of the standard deviation). Then the explained variance is estimated as follows:\n","\n","$\\texttt{explainedVariance}(y, \\hat{y}) = 1 - \\frac{Var\\{ y - \\hat{y}\\}}{Var\\{y\\}}$ \n","The best possible score is 1.0, the lower values are worse.\n"]},{"cell_type":"markdown","id":"9f81be90-78a1-4748-849b-19729af21c25","metadata":{},"outputs":[],"source":["<h2 id=\"practice\">Practice</h2>\n","Try to use a multiple linear regression with the same dataset, but this time use FUELCONSUMPTION_CITY and FUELCONSUMPTION_HWY instead of FUELCONSUMPTION_COMB. Does it result in better accuracy?\n"]},{"cell_type":"code","id":"2345a604-c847-40f8-8218-dbfc087e89a8","metadata":{},"outputs":[],"source":["# write your code here\n\n"]},{"cell_type":"markdown","id":"846eb454-bbf7-454d-a8e0-d40e1ad040fa","metadata":{},"outputs":[],"source":["<details><summary>Click here for the solution</summary>\n","\n","```python\n","regr = linear_model.LinearRegression()\n","x = np.asanyarray(train[['ENGINESIZE','CYLINDERS','FUELCONSUMPTION_CITY','FUELCONSUMPTION_HWY']])\n","y = np.asanyarray(train[['CO2EMISSIONS']])\n","regr.fit (x, y)\n","print ('Coefficients: ', regr.coef_)\n","y_= regr.predict(test[['ENGINESIZE','CYLINDERS','FUELCONSUMPTION_CITY','FUELCONSUMPTION_HWY']])\n","x = np.asanyarray(test[['ENGINESIZE','CYLINDERS','FUELCONSUMPTION_CITY','FUELCONSUMPTION_HWY']])\n","y = np.asanyarray(test[['CO2EMISSIONS']])\n","print(\"Residual sum of squares: %.2f\"% np.mean((y_ - y) ** 2))\n","print('Variance score: %.2f' % regr.score(x, y))\n","\n","```\n","\n","</details>\n"]},{"cell_type":"markdown","id":"9db6d66b-df07-4dc3-9b80-6a4dd574d646","metadata":{},"outputs":[],"source":["### Thank you for completing this lab!\n","\n","\n","## Author\n","\n","Saeed Aghabozorgi\n","\n","\n","### Other Contributors\n","\n","<a href=\"https://www.linkedin.com/in/joseph-s-50398b136/\" target=\"_blank\">Joseph Santarcangelo</a>\n","\n","## <h3 align=\"center\"> © IBM Corporation 2020. All rights reserved. <h3/>\n"," \n","<!--\n","\n","## Change Log\n","\n","\n","| Date (YYYY-MM-DD) | Version | Changed By | Change Description |\n","|---|---|---|---|\n","| 2020-11-03 | 2.1 | Lakshmi | Made changes in URL |\n","| 2020-08-27 | 2.0 | Lavanya | Moved lab to course repo in GitLab |\n","| | | | |\n","| | | | |\n","\n","\n","\n","\n","--!>\n"]}],"metadata":{"kernelspec":{"display_name":"Python","language":"python","name":"conda-env-python-py"},"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.7.12"},"prev_pub_hash":"c1170d4cb1c9bbce7dbbef74b645fc6b265a5aaf4ce89c4ac861feed8769ed99"},"nbformat":4,"nbformat_minor":4}