Created
November 5, 2019 04:11
-
-
Save JoseRFJuniorLLMs/2357f78b9c69c2c2f6979f1f9ed63847 to your computer and use it in GitHub Desktop.
Created on Cognitive Class Labs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"cells": [ | |
{ | |
"cell_type": "markdown", | |
"metadata": { | |
"button": false, | |
"deletable": true, | |
"new_sheet": false, | |
"run_control": { | |
"read_only": false | |
} | |
}, | |
"source": [ | |
"<a href=\"https://www.bigdatauniversity.com\"><img src=\"https://ibm.box.com/shared/static/cw2c7r3o20w9zn8gkecaeyjhgw3xdgbj.png\" width=\"400\" align=\"center\"></a>\n", | |
"\n", | |
"<h1><center>Simple Linear Regression</center></h1>\n", | |
"\n", | |
"\n", | |
"<h4>About this Notebook</h4>\n", | |
"In this notebook, we learn how to use scikit-learn to implement simple linear regression. We download a dataset that is related to fuel consumption and Carbon dioxide emission of cars. Then, we split our data into training and test sets, create a model using training set, evaluate your model using test set, and finally use model to predict unknown value.\n" | |
] | |
}, | |
{ | |
"cell_type": "markdown", | |
"metadata": {}, | |
"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=\"#data_exploration\">Data Exploration</a></li>\n", | |
" <li><a href=\"#simple_regression\">Simple Regression Model</a></li>\n", | |
" </ol>\n", | |
"</div>\n", | |
"<br>\n", | |
"<hr>" | |
] | |
}, | |
{ | |
"cell_type": "markdown", | |
"metadata": { | |
"button": false, | |
"deletable": true, | |
"new_sheet": false, | |
"run_control": { | |
"read_only": false | |
} | |
}, | |
"source": [ | |
"### Importing Needed packages" | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": null, | |
"metadata": { | |
"button": false, | |
"collapsed": true, | |
"deletable": true, | |
"new_sheet": false, | |
"run_control": { | |
"read_only": false | |
} | |
}, | |
"outputs": [], | |
"source": [ | |
"import matplotlib.pyplot as plt\n", | |
"import pandas as pd\n", | |
"import pylab as pl\n", | |
"import numpy as np\n", | |
"%matplotlib inline" | |
] | |
}, | |
{ | |
"cell_type": "markdown", | |
"metadata": { | |
"button": false, | |
"deletable": true, | |
"new_sheet": false, | |
"run_control": { | |
"read_only": false | |
} | |
}, | |
"source": [ | |
"### Downloading Data\n", | |
"To download the data, we will use !wget to download it from IBM Object Storage." | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": null, | |
"metadata": { | |
"button": false, | |
"collapsed": true, | |
"deletable": true, | |
"new_sheet": false, | |
"run_control": { | |
"read_only": false | |
} | |
}, | |
"outputs": [], | |
"source": [ | |
"!wget -O FuelConsumption.csv https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/ML0101ENv3/labs/FuelConsumptionCo2.csv" | |
] | |
}, | |
{ | |
"cell_type": "markdown", | |
"metadata": {}, | |
"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](http://cocl.us/ML0101EN-IBM-Offer-CC)" | |
] | |
}, | |
{ | |
"cell_type": "markdown", | |
"metadata": { | |
"button": false, | |
"deletable": true, | |
"new_sheet": false, | |
"run_control": { | |
"read_only": false | |
} | |
}, | |
"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", | |
"- **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", | |
"metadata": { | |
"button": false, | |
"deletable": true, | |
"new_sheet": false, | |
"run_control": { | |
"read_only": false | |
} | |
}, | |
"source": [ | |
"<h2 id=\"reading_data\">Reading the data in</h2>" | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": null, | |
"metadata": { | |
"button": false, | |
"collapsed": true, | |
"deletable": true, | |
"new_sheet": false, | |
"run_control": { | |
"read_only": false | |
} | |
}, | |
"outputs": [], | |
"source": [ | |
"df = pd.read_csv(\"FuelConsumption.csv\")\n", | |
"\n", | |
"# take a look at the dataset\n", | |
"df.head()\n", | |
"\n" | |
] | |
}, | |
{ | |
"cell_type": "markdown", | |
"metadata": { | |
"button": false, | |
"deletable": true, | |
"new_sheet": false, | |
"run_control": { | |
"read_only": false | |
} | |
}, | |
"source": [ | |
"<h2 id=\"data_exploration\">Data Exploration</h2>\n", | |
"Lets first have a descriptive exploration on our data." | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": null, | |
"metadata": { | |
"button": false, | |
"collapsed": true, | |
"deletable": true, | |
"new_sheet": false, | |
"run_control": { | |
"read_only": false | |
} | |
}, | |
"outputs": [], | |
"source": [ | |
"# summarize the data\n", | |
"df.describe()" | |
] | |
}, | |
{ | |
"cell_type": "markdown", | |
"metadata": {}, | |
"source": [ | |
"Lets select some features to explore more." | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": null, | |
"metadata": { | |
"button": false, | |
"collapsed": true, | |
"deletable": true, | |
"new_sheet": false, | |
"run_control": { | |
"read_only": false | |
} | |
}, | |
"outputs": [], | |
"source": [ | |
"cdf = df[['ENGINESIZE','CYLINDERS','FUELCONSUMPTION_COMB','CO2EMISSIONS']]\n", | |
"cdf.head(9)" | |
] | |
}, | |
{ | |
"cell_type": "markdown", | |
"metadata": {}, | |
"source": [ | |
"we can plot each of these features:" | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": null, | |
"metadata": { | |
"button": false, | |
"collapsed": true, | |
"deletable": true, | |
"new_sheet": false, | |
"run_control": { | |
"read_only": false | |
} | |
}, | |
"outputs": [], | |
"source": [ | |
"viz = cdf[['CYLINDERS','ENGINESIZE','CO2EMISSIONS','FUELCONSUMPTION_COMB']]\n", | |
"viz.hist()\n", | |
"plt.show()" | |
] | |
}, | |
{ | |
"cell_type": "markdown", | |
"metadata": {}, | |
"source": [ | |
"Now, lets plot each of these features vs the Emission, to see how linear is their relation:" | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": null, | |
"metadata": { | |
"button": false, | |
"collapsed": true, | |
"deletable": true, | |
"new_sheet": false, | |
"run_control": { | |
"read_only": false | |
} | |
}, | |
"outputs": [], | |
"source": [ | |
"plt.scatter(cdf.FUELCONSUMPTION_COMB, cdf.CO2EMISSIONS, color='blue')\n", | |
"plt.xlabel(\"FUELCONSUMPTION_COMB\")\n", | |
"plt.ylabel(\"Emission\")\n", | |
"plt.show()" | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": null, | |
"metadata": { | |
"button": false, | |
"collapsed": true, | |
"deletable": true, | |
"new_sheet": false, | |
"run_control": { | |
"read_only": false | |
}, | |
"scrolled": true | |
}, | |
"outputs": [], | |
"source": [ | |
"plt.scatter(cdf.ENGINESIZE, cdf.CO2EMISSIONS, color='blue')\n", | |
"plt.xlabel(\"Engine size\")\n", | |
"plt.ylabel(\"Emission\")\n", | |
"plt.show()" | |
] | |
}, | |
{ | |
"cell_type": "markdown", | |
"metadata": {}, | |
"source": [ | |
"## Practice\n", | |
"plot __CYLINDER__ vs the Emission, to see how linear is their relation:" | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": null, | |
"metadata": { | |
"button": false, | |
"collapsed": true, | |
"deletable": true, | |
"new_sheet": false, | |
"run_control": { | |
"read_only": false | |
} | |
}, | |
"outputs": [], | |
"source": [ | |
"# write your code here\n" | |
] | |
}, | |
{ | |
"cell_type": "markdown", | |
"metadata": {}, | |
"source": [ | |
"Double-click __here__ for the solution.\n", | |
"\n", | |
"<!-- Your answer is below:\n", | |
" \n", | |
"plt.scatter(cdf.CYLINDERS, cdf.CO2EMISSIONS, color='blue')\n", | |
"plt.xlabel(\"Cylinders\")\n", | |
"plt.ylabel(\"Emission\")\n", | |
"plt.show()\n", | |
"\n", | |
"-->" | |
] | |
}, | |
{ | |
"cell_type": "markdown", | |
"metadata": { | |
"button": false, | |
"deletable": true, | |
"new_sheet": false, | |
"run_control": { | |
"read_only": false | |
} | |
}, | |
"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 data. It is more realistic for real world problems.\n", | |
"\n", | |
"This means that we know the outcome of each data point in this dataset, making it great to test with! And 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", | |
"Lets split our dataset into train and test sets, 80% of the entire data for training, and the 20% for testing. We create a mask to select random rows using __np.random.rand()__ function: " | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": null, | |
"metadata": { | |
"button": false, | |
"collapsed": true, | |
"deletable": true, | |
"new_sheet": false, | |
"run_control": { | |
"read_only": false | |
} | |
}, | |
"outputs": [], | |
"source": [ | |
"msk = np.random.rand(len(df)) < 0.8\n", | |
"train = cdf[msk]\n", | |
"test = cdf[~msk]" | |
] | |
}, | |
{ | |
"cell_type": "markdown", | |
"metadata": { | |
"button": false, | |
"deletable": true, | |
"new_sheet": false, | |
"run_control": { | |
"read_only": false | |
} | |
}, | |
"source": [ | |
"<h2 id=\"simple_regression\">Simple Regression Model</h2>\n", | |
"Linear Regression fits a linear model with coefficients $\\theta = (\\theta_1, ..., \\theta_n)$ to minimize the 'residual sum of squares' between the independent x in the dataset, and the dependent y by the linear approximation. " | |
] | |
}, | |
{ | |
"cell_type": "markdown", | |
"metadata": { | |
"button": false, | |
"deletable": true, | |
"new_sheet": false, | |
"run_control": { | |
"read_only": false | |
} | |
}, | |
"source": [ | |
"#### Train data distribution" | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": null, | |
"metadata": { | |
"button": false, | |
"collapsed": true, | |
"deletable": true, | |
"new_sheet": false, | |
"run_control": { | |
"read_only": false | |
} | |
}, | |
"outputs": [], | |
"source": [ | |
"plt.scatter(train.ENGINESIZE, train.CO2EMISSIONS, color='blue')\n", | |
"plt.xlabel(\"Engine size\")\n", | |
"plt.ylabel(\"Emission\")\n", | |
"plt.show()" | |
] | |
}, | |
{ | |
"cell_type": "markdown", | |
"metadata": { | |
"button": false, | |
"deletable": true, | |
"new_sheet": false, | |
"run_control": { | |
"read_only": false | |
} | |
}, | |
"source": [ | |
"#### Modeling\n", | |
"Using sklearn package to model data." | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": null, | |
"metadata": { | |
"button": false, | |
"collapsed": true, | |
"deletable": true, | |
"new_sheet": false, | |
"run_control": { | |
"read_only": false | |
} | |
}, | |
"outputs": [], | |
"source": [ | |
"from sklearn import linear_model\n", | |
"regr = linear_model.LinearRegression()\n", | |
"train_x = np.asanyarray(train[['ENGINESIZE']])\n", | |
"train_y = np.asanyarray(train[['CO2EMISSIONS']])\n", | |
"regr.fit (train_x, train_y)\n", | |
"# The coefficients\n", | |
"print ('Coefficients: ', regr.coef_)\n", | |
"print ('Intercept: ',regr.intercept_)" | |
] | |
}, | |
{ | |
"cell_type": "markdown", | |
"metadata": {}, | |
"source": [ | |
"As mentioned before, __Coefficient__ and __Intercept__ in the simple linear regression, are the parameters of the fit line. \n", | |
"Given that it is a simple linear regression, with only 2 parameters, and knowing that the parameters are the intercept and slope of the line, sklearn can estimate them directly from our data. \n", | |
"Notice that all of the data must be available to traverse and calculate the parameters.\n" | |
] | |
}, | |
{ | |
"cell_type": "markdown", | |
"metadata": { | |
"button": false, | |
"deletable": true, | |
"new_sheet": false, | |
"run_control": { | |
"read_only": false | |
} | |
}, | |
"source": [ | |
"#### Plot outputs" | |
] | |
}, | |
{ | |
"cell_type": "markdown", | |
"metadata": {}, | |
"source": [ | |
"we can plot the fit line over the data:" | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": null, | |
"metadata": { | |
"button": false, | |
"collapsed": true, | |
"deletable": true, | |
"new_sheet": false, | |
"run_control": { | |
"read_only": false | |
} | |
}, | |
"outputs": [], | |
"source": [ | |
"plt.scatter(train.ENGINESIZE, train.CO2EMISSIONS, color='blue')\n", | |
"plt.plot(train_x, regr.coef_[0][0]*train_x + regr.intercept_[0], '-r')\n", | |
"plt.xlabel(\"Engine size\")\n", | |
"plt.ylabel(\"Emission\")" | |
] | |
}, | |
{ | |
"cell_type": "markdown", | |
"metadata": { | |
"button": false, | |
"deletable": true, | |
"new_sheet": false, | |
"run_control": { | |
"read_only": false | |
} | |
}, | |
"source": [ | |
"#### Evaluation\n", | |
"we compare the actual values and predicted values to calculate the accuracy of a regression model. Evaluation metrics provide a key role in the development of a model, as it provides insight to areas that require improvement.\n", | |
"\n", | |
"There are different model evaluation metrics, lets use MSE here to calculate the accuracy of our model based on the test set: \n", | |
"<ul>\n", | |
" <li> Mean absolute error: It is the mean of the absolute value of the errors. This is the easiest of the metrics to understand since it’s just average error.</li>\n", | |
" <li> Mean Squared Error (MSE): Mean Squared Error (MSE) is the mean of the squared error. It’s more popular than Mean absolute error because the focus is geared more towards large errors. This is due to the squared term exponentially increasing larger errors in comparison to smaller ones.</li>\n", | |
" <li> Root Mean Squared Error (RMSE): This is the square root of the Mean Square Error. </li>\n", | |
" <li> R-squared is not error, but is a popular metric for accuracy of your model. It represents how close the data are to the fitted regression line. The higher the R-squared, the better the model fits your data. Best possible score is 1.0 and it can be negative (because the model can be arbitrarily worse).</li>\n", | |
"</ul>" | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": null, | |
"metadata": { | |
"button": false, | |
"collapsed": true, | |
"deletable": true, | |
"new_sheet": false, | |
"run_control": { | |
"read_only": false | |
}, | |
"scrolled": true | |
}, | |
"outputs": [], | |
"source": [ | |
"from sklearn.metrics import r2_score\n", | |
"\n", | |
"test_x = np.asanyarray(test[['ENGINESIZE']])\n", | |
"test_y = np.asanyarray(test[['CO2EMISSIONS']])\n", | |
"test_y_hat = regr.predict(test_x)\n", | |
"\n", | |
"print(\"Mean absolute error: %.2f\" % np.mean(np.absolute(test_y_hat - test_y)))\n", | |
"print(\"Residual sum of squares (MSE): %.2f\" % np.mean((test_y_hat - test_y) ** 2))\n", | |
"print(\"R2-score: %.2f\" % r2_score(test_y_hat , test_y) )" | |
] | |
}, | |
{ | |
"cell_type": "markdown", | |
"metadata": { | |
"button": false, | |
"deletable": true, | |
"new_sheet": false, | |
"run_control": { | |
"read_only": false | |
} | |
}, | |
"source": [ | |
"<h2>Want to learn more?</h2>\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: <a href=\"http://cocl.us/ML0101EN-SPSSModeler\">SPSS Modeler</a>\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 <a href=\"https://cocl.us/ML0101EN_DSX\">Watson Studio</a>\n", | |
"\n", | |
"<h3>Thanks for completing this lesson!</h3>\n", | |
"\n", | |
"<h4>Author: <a href=\"https://ca.linkedin.com/in/saeedaghabozorgi\">Saeed Aghabozorgi</a></h4>\n", | |
"<p><a href=\"https://ca.linkedin.com/in/saeedaghabozorgi\">Saeed Aghabozorgi</a>, PhD is a Data Scientist in IBM with a track record of developing enterprise level applications that substantially increases clients’ ability to turn data into actionable knowledge. He is a researcher in data mining field and expert in developing advanced analytic methods like machine learning and statistical modelling on large datasets.</p>\n", | |
"\n", | |
"<hr>\n", | |
"\n", | |
"<p>Copyright © 2018 <a href=\"https://cocl.us/DX0108EN_CC\">Cognitive Class</a>. This notebook and its source code are released under the terms of the <a href=\"https://bigdatauniversity.com/mit-license/\">MIT License</a>.</p>" | |
] | |
} | |
], | |
"metadata": { | |
"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.6.6" | |
}, | |
"widgets": { | |
"state": {}, | |
"version": "1.1.2" | |
} | |
}, | |
"nbformat": 4, | |
"nbformat_minor": 2 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment