├── Classification ├── ML0101EN-Clas-Decision-Trees-drug.jupyterlite.ipynb ├── Module 3_ML0101EN-Clas-K-Nearest-neighbors-CustCat.jupyterlite.ipynb └── classification_tree_svm.ipynb ├── LICENSE ├── README.md └── Regression ├── 01_LR.ipynb ├── Module 2_ML0101EN-Reg-Mulitple-Linear-Regression-Co2.jupyterlite.ipynb └── Module 2_ML0101EN-Reg-Simple-Linear-Regression-Co2.jupyterlite.ipynb /Classification/ML0101EN-Clas-Decision-Trees-drug.jupyterlite.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "metadata": { 3 | "kernelspec": { 4 | "name": "python", 5 | "display_name": "Python (Pyodide)", 6 | "language": "python" 7 | }, 8 | "language_info": { 9 | "codemirror_mode": { 10 | "name": "python", 11 | "version": 3 12 | }, 13 | "file_extension": ".py", 14 | "mimetype": "text/x-python", 15 | "name": "python", 16 | "nbconvert_exporter": "python", 17 | "pygments_lexer": "ipython3", 18 | "version": "3.8" 19 | } 20 | }, 21 | "nbformat_minor": 4, 22 | "nbformat": 4, 23 | "cells": [ 24 | { 25 | "cell_type": "markdown", 26 | "source": "

\n \n \"Skills\n \n

\n\n\n# Decision Trees\n\n\nEstimated time needed: **15** minutes\n \n\n## Objectives\n\nAfter completing this lab you will be able to:\n\n* Develop a classification model using Decision Tree Algorithm\n", 27 | "metadata": {} 28 | }, 29 | { 30 | "cell_type": "markdown", 31 | "source": "In this lab exercise, you will learn a popular machine learning algorithm, Decision Trees. You will use this classification algorithm to build a model from the historical data of patients, and their response to different medications. Then you will use the trained decision tree to predict the class of an unknown patient, or to find a proper drug for a new patient.\n", 32 | "metadata": {} 33 | }, 34 | { 35 | "cell_type": "markdown", 36 | "source": "

Table of contents

\n\n
\n
    \n
  1. About the dataset
  2. \n
  3. Downloading the Data
  4. \n
  5. Pre-processing
  6. \n
  7. Setting up the Decision Tree
  8. \n
  9. Modeling
  10. \n
  11. Prediction
  12. \n
  13. Evaluation
  14. \n
  15. Visualization
  16. \n
\n
\n
\n
\n", 37 | "metadata": {} 38 | }, 39 | { 40 | "cell_type": "markdown", 41 | "source": "Import the Following Libraries:\n\n", 42 | "metadata": {} 43 | }, 44 | { 45 | "cell_type": "markdown", 46 | "source": "if you uisng you own version comment out\n", 47 | "metadata": {} 48 | }, 49 | { 50 | "cell_type": "code", 51 | "source": "import piplite\nawait piplite.install(['pandas'])\nawait piplite.install(['matplotlib'])\nawait piplite.install(['numpy'])\nawait piplite.install(['scikit-learn'])\n\n", 52 | "metadata": {}, 53 | "outputs": [], 54 | "execution_count": null 55 | }, 56 | { 57 | "cell_type": "code", 58 | "source": "import numpy as np \nimport pandas as pd\nfrom sklearn.tree import DecisionTreeClassifier\nimport sklearn.tree as tree", 59 | "metadata": {}, 60 | "outputs": [], 61 | "execution_count": null 62 | }, 63 | { 64 | "cell_type": "code", 65 | "source": "from pyodide.http import pyfetch\n\nasync def download(url, filename):\n response = await pyfetch(url)\n if response.status == 200:\n with open(filename, \"wb\") as f:\n f.write(await response.bytes())", 66 | "metadata": {}, 67 | "outputs": [], 68 | "execution_count": null 69 | }, 70 | { 71 | "cell_type": "markdown", 72 | "source": "
\n

About the dataset

\n Imagine that you are a medical researcher compiling data for a study. You have collected data about a set of patients, all of whom suffered from the same illness. During their course of treatment, each patient responded to one of 5 medications, Drug A, Drug B, Drug c, Drug x and y. \n
\n
\n Part of your job is to build a model to find out which drug might be appropriate for a future patient with the same illness. The features of this dataset are Age, Sex, Blood Pressure, and the Cholesterol of the patients, and the target is the drug that each patient responded to.\n
\n
\n It is a sample of multiclass classifier, and you can use the training part of the dataset \n to build a decision tree, and then use it to predict the class of an unknown patient, or to prescribe a drug to a new patient.\n
\n", 73 | "metadata": {} 74 | }, 75 | { 76 | "cell_type": "markdown", 77 | "source": "
\n

Downloading the Data

\n To download the data, we will use !wget to download it from IBM Object Storage.\n
\n", 78 | "metadata": {} 79 | }, 80 | { 81 | "cell_type": "code", 82 | "source": "path= 'https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-ML0101EN-SkillsNetwork/labs/Module%203/data/drug200.csv'\nawait download(path,\"drug200.csv\")\npath=\"drug200.csv\"", 83 | "metadata": {}, 84 | "outputs": [], 85 | "execution_count": null 86 | }, 87 | { 88 | "cell_type": "markdown", 89 | "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)\n", 90 | "metadata": {} 91 | }, 92 | { 93 | "cell_type": "markdown", 94 | "source": "Now, read the data using pandas dataframe:\n", 95 | "metadata": {} 96 | }, 97 | { 98 | "cell_type": "code", 99 | "source": "my_data = pd.read_csv(\"drug200.csv\", delimiter=\",\")\nmy_data[0:5]", 100 | "metadata": {}, 101 | "outputs": [], 102 | "execution_count": null 103 | }, 104 | { 105 | "cell_type": "markdown", 106 | "source": "
\n

Practice

\n What is the size of data? \n
\n", 107 | "metadata": {} 108 | }, 109 | { 110 | "cell_type": "code", 111 | "source": "# write your code here\n\n\n", 112 | "metadata": {}, 113 | "outputs": [], 114 | "execution_count": null 115 | }, 116 | { 117 | "cell_type": "markdown", 118 | "source": "
Click here for the solution\n\n```python\nmy_data.shape\n\n```\n\n
\n\n", 119 | "metadata": {} 120 | }, 121 | { 122 | "cell_type": "markdown", 123 | "source": "
\n

Pre-processing

\n
\n", 124 | "metadata": {} 125 | }, 126 | { 127 | "cell_type": "markdown", 128 | "source": "Using my_data as the Drug.csv data read by pandas, declare the following variables:
\n\n\n", 129 | "metadata": {} 130 | }, 131 | { 132 | "cell_type": "markdown", 133 | "source": "Remove the column containing the target name since it doesn't contain numeric values.\n", 134 | "metadata": {} 135 | }, 136 | { 137 | "cell_type": "code", 138 | "source": "X = my_data[['Age', 'Sex', 'BP', 'Cholesterol', 'Na_to_K']].values\nX[0:5]\n", 139 | "metadata": {}, 140 | "outputs": [], 141 | "execution_count": null 142 | }, 143 | { 144 | "cell_type": "markdown", 145 | "source": "As you may figure out, some features in this dataset are categorical, such as __Sex__ or __BP__. Unfortunately, Sklearn Decision Trees does not handle categorical variables. We can still convert these features to numerical values using __LabelEncoder__\nto convert the categorical variable into numerical variables.\n", 146 | "metadata": {} 147 | }, 148 | { 149 | "cell_type": "code", 150 | "source": "from sklearn import preprocessing\nle_sex = preprocessing.LabelEncoder()\nle_sex.fit(['F','M'])\nX[:,1] = le_sex.transform(X[:,1]) \n\n\nle_BP = preprocessing.LabelEncoder()\nle_BP.fit([ 'LOW', 'NORMAL', 'HIGH'])\nX[:,2] = le_BP.transform(X[:,2])\n\n\nle_Chol = preprocessing.LabelEncoder()\nle_Chol.fit([ 'NORMAL', 'HIGH'])\nX[:,3] = le_Chol.transform(X[:,3]) \n\nX[0:5]\n", 151 | "metadata": {}, 152 | "outputs": [], 153 | "execution_count": null 154 | }, 155 | { 156 | "cell_type": "markdown", 157 | "source": "Now we can fill the target variable.\n", 158 | "metadata": {} 159 | }, 160 | { 161 | "cell_type": "code", 162 | "source": "y = my_data[\"Drug\"]\ny[0:5]", 163 | "metadata": {}, 164 | "outputs": [], 165 | "execution_count": null 166 | }, 167 | { 168 | "cell_type": "markdown", 169 | "source": "
\n\n
\n

Setting up the Decision Tree

\n We will be using train/test split on our decision tree. Let's import train_test_split from sklearn.cross_validation.\n
\n", 170 | "metadata": {} 171 | }, 172 | { 173 | "cell_type": "code", 174 | "source": "from sklearn.model_selection import train_test_split", 175 | "metadata": {}, 176 | "outputs": [], 177 | "execution_count": null 178 | }, 179 | { 180 | "cell_type": "markdown", 181 | "source": "Now train_test_split will return 4 different parameters. We will name them:
\nX_trainset, X_testset, y_trainset, y_testset

\nThe train_test_split will need the parameters:
\nX, y, test_size=0.3, and random_state=3.

\nThe X and y are the arrays required before the split, the test_size represents the ratio of the testing dataset, and the random_state ensures that we obtain the same splits.\n", 182 | "metadata": {} 183 | }, 184 | { 185 | "cell_type": "code", 186 | "source": "X_trainset, X_testset, y_trainset, y_testset = train_test_split(X, y, test_size=0.3, random_state=3)", 187 | "metadata": {}, 188 | "outputs": [], 189 | "execution_count": null 190 | }, 191 | { 192 | "cell_type": "markdown", 193 | "source": "

Practice

\nPrint the shape of X_trainset and y_trainset. Ensure that the dimensions match.\n", 194 | "metadata": {} 195 | }, 196 | { 197 | "cell_type": "code", 198 | "source": "# your code\n\n", 199 | "metadata": {}, 200 | "outputs": [], 201 | "execution_count": null 202 | }, 203 | { 204 | "cell_type": "markdown", 205 | "source": "
Click here for the solution\n\n```python\nprint('Shape of X training set {}'.format(X_trainset.shape),'&',' Size of Y training set {}'.format(y_trainset.shape))\n\n```\n\n
\n\n", 206 | "metadata": {} 207 | }, 208 | { 209 | "cell_type": "markdown", 210 | "source": "Print the shape of X_testset and y_testset. Ensure that the dimensions match.\n", 211 | "metadata": {} 212 | }, 213 | { 214 | "cell_type": "code", 215 | "source": "# your code\n\n", 216 | "metadata": {}, 217 | "outputs": [], 218 | "execution_count": null 219 | }, 220 | { 221 | "cell_type": "markdown", 222 | "source": "
Click here for the solution\n\n```python\nprint('Shape of X training set {}'.format(X_testset.shape),'&',' Size of Y training set {}'.format(y_testset.shape))\n\n```\n\n
\n\n", 223 | "metadata": {} 224 | }, 225 | { 226 | "cell_type": "markdown", 227 | "source": "
\n\n
\n

Modeling

\n We will first create an instance of the DecisionTreeClassifier called drugTree.
\n Inside of the classifier, specify criterion=\"entropy\" so we can see the information gain of each node.\n
\n", 228 | "metadata": {} 229 | }, 230 | { 231 | "cell_type": "code", 232 | "source": "drugTree = DecisionTreeClassifier(criterion=\"entropy\", max_depth = 4)\ndrugTree # it shows the default parameters", 233 | "metadata": {}, 234 | "outputs": [], 235 | "execution_count": null 236 | }, 237 | { 238 | "cell_type": "markdown", 239 | "source": "Next, we will fit the data with the training feature matrix X_trainset and training response vector y_trainset \n", 240 | "metadata": {} 241 | }, 242 | { 243 | "cell_type": "code", 244 | "source": "drugTree.fit(X_trainset,y_trainset)", 245 | "metadata": {}, 246 | "outputs": [], 247 | "execution_count": null 248 | }, 249 | { 250 | "cell_type": "markdown", 251 | "source": "
\n\n
\n

Prediction

\n Let's make some predictions on the testing dataset and store it into a variable called predTree.\n
\n", 252 | "metadata": {} 253 | }, 254 | { 255 | "cell_type": "code", 256 | "source": "predTree = drugTree.predict(X_testset)", 257 | "metadata": {}, 258 | "outputs": [], 259 | "execution_count": null 260 | }, 261 | { 262 | "cell_type": "markdown", 263 | "source": "You can print out predTree and y_testset if you want to visually compare the predictions to the actual values.\n", 264 | "metadata": {} 265 | }, 266 | { 267 | "cell_type": "code", 268 | "source": "print (predTree [0:5])\nprint (y_testset [0:5])\n", 269 | "metadata": {}, 270 | "outputs": [], 271 | "execution_count": null 272 | }, 273 | { 274 | "cell_type": "markdown", 275 | "source": "
\n\n
\n

Evaluation

\n Next, let's import metrics from sklearn and check the accuracy of our model.\n
\n", 276 | "metadata": {} 277 | }, 278 | { 279 | "cell_type": "code", 280 | "source": "from sklearn import metrics\nimport matplotlib.pyplot as plt\nprint(\"DecisionTrees's Accuracy: \", metrics.accuracy_score(y_testset, predTree))", 281 | "metadata": {}, 282 | "outputs": [], 283 | "execution_count": null 284 | }, 285 | { 286 | "cell_type": "markdown", 287 | "source": "__Accuracy classification score__ computes subset accuracy: the set of labels predicted for a sample must exactly match the corresponding set of labels in y_true. \n\nIn multilabel classification, the function returns the subset accuracy. If the entire set of predicted labels for a sample strictly matches with the true set of labels, then the subset accuracy is 1.0; otherwise it is 0.0.\n", 288 | "metadata": {} 289 | }, 290 | { 291 | "cell_type": "markdown", 292 | "source": "
\n\n
\n

Visualization

\n \n \nLet's visualize the tree\n
\n", 293 | "metadata": {} 294 | }, 295 | { 296 | "cell_type": "code", 297 | "source": "# Notice: You might need to uncomment and install the pydotplus and graphviz libraries if you have not installed these before\n#!conda install -c conda-forge pydotplus -y\n#!conda install -c conda-forge python-graphviz -y", 298 | "metadata": {}, 299 | "outputs": [], 300 | "execution_count": null 301 | }, 302 | { 303 | "cell_type": "code", 304 | "source": "tree.plot_tree(drugTree)\nplt.show()", 305 | "metadata": {}, 306 | "outputs": [], 307 | "execution_count": null 308 | }, 309 | { 310 | "cell_type": "markdown", 311 | "source": "

Want to learn more?

\n\nIBM 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\nAlso, 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", 312 | "metadata": {} 313 | }, 314 | { 315 | "cell_type": "markdown", 316 | "source": "### Thank you for completing this lab!\n\n\n## Author\n\nSaeed Aghabozorgi\n\n\n### Other Contributors\n\nJoseph Santarcangelo\n\n\n\n\n## Change Log\n\n\n| Date (YYYY-MM-DD) | Version | Changed By | Change Description |\n|---|---|---|---|\n| 2023-04-05 | 2.3 | Anita Verma | Changed pandas.get_dummies() to LabelEncoder|\n| 2020-11-20 | 2.2 | Lakshmi | Changed import statement of StringIO|\n| 2020-11-03 | 2.1 | Lakshmi | Changed URL of the csv |\n| 2020-08-27 | 2.0 | Lavanya | Moved lab to course repo in GitLab |\n| | | | |\n| | | | |\n\n\n##

© IBM Corporation 2020. All rights reserved.

\n", 317 | "metadata": {} 318 | } 319 | ] 320 | } -------------------------------------------------------------------------------- /Classification/Module 3_ML0101EN-Clas-K-Nearest-neighbors-CustCat.jupyterlite.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "metadata": { 3 | "kernelspec": { 4 | "name": "python", 5 | "display_name": "Pyolite", 6 | "language": "python" 7 | }, 8 | "language_info": { 9 | "codemirror_mode": { 10 | "name": "python", 11 | "version": 3 12 | }, 13 | "file_extension": ".py", 14 | "mimetype": "text/x-python", 15 | "name": "python", 16 | "nbconvert_exporter": "python", 17 | "pygments_lexer": "ipython3", 18 | "version": "3.8" 19 | } 20 | }, 21 | "nbformat_minor": 4, 22 | "nbformat": 4, 23 | "cells": [ 24 | { 25 | "cell_type": "markdown", 26 | "source": [ 27 | "

\n", 28 | " \n", 29 | " \"Skills\n", 30 | " \n", 31 | "

\n", 32 | "\n", 33 | "# K-Nearest Neighbors\n", 34 | "\n", 35 | "Estimated time needed: **25** minutes\n", 36 | "\n", 37 | "## Objectives\n", 38 | "\n", 39 | "After completing this lab you will be able to:\n", 40 | "\n", 41 | "* Use K Nearest neighbors to classify data\n" 42 | ], 43 | "metadata": { 44 | "button": false, 45 | "new_sheet": false, 46 | "run_control": { 47 | "read_only": false 48 | } 49 | } 50 | }, 51 | { 52 | "cell_type": "markdown", 53 | "source": [ 54 | "In this Lab you will load a customer dataset, fit the data, and use K-Nearest Neighbors to predict a data point. But what is **K-Nearest Neighbors**?\n" 55 | ], 56 | "metadata": { 57 | "button": false, 58 | "new_sheet": false, 59 | "run_control": { 60 | "read_only": false 61 | } 62 | } 63 | }, 64 | { 65 | "cell_type": "markdown", 66 | "source": [ 67 | "**K-Nearest Neighbors** is a supervised learning algorithm. Where the data is 'trained' with data points corresponding to their classification. To predict the class of a given data point, it takes into account the classes of the 'K' nearest data points and chooses the class in which the majority of the 'K' nearest data points belong to as the predicted class.\n" 68 | ], 69 | "metadata": { 70 | "button": false, 71 | "new_sheet": false, 72 | "run_control": { 73 | "read_only": false 74 | } 75 | } 76 | }, 77 | { 78 | "cell_type": "markdown", 79 | "source": [ 80 | "### Here's an visualization of the K-Nearest Neighbors algorithm.\n", 81 | "\n", 82 | "\n" 83 | ], 84 | "metadata": { 85 | "button": false, 86 | "new_sheet": false, 87 | "run_control": { 88 | "read_only": false 89 | } 90 | } 91 | }, 92 | { 93 | "cell_type": "markdown", 94 | "source": [ 95 | "In this case, we have data points of Class A and B. We want to predict what the star (test data point) is. If we consider a k value of 3 (3 nearest data points), we will obtain a prediction of Class B. Yet if we consider a k value of 6, we will obtain a prediction of Class A.\n" 96 | ], 97 | "metadata": { 98 | "button": false, 99 | "new_sheet": false, 100 | "run_control": { 101 | "read_only": false 102 | } 103 | } 104 | }, 105 | { 106 | "cell_type": "markdown", 107 | "source": [ 108 | "In this sense, it is important to consider the value of k. Hopefully from this diagram, you should get a sense of what the K-Nearest Neighbors algorithm is. It considers the 'K' Nearest Neighbors (data points) when it predicts the classification of the test point.\n" 109 | ], 110 | "metadata": { 111 | "button": false, 112 | "new_sheet": false, 113 | "run_control": { 114 | "read_only": false 115 | } 116 | } 117 | }, 118 | { 119 | "cell_type": "markdown", 120 | "source": [ 121 | "

Table of contents

\n", 122 | "\n", 123 | "
\n", 124 | "
    \n", 125 | "
  1. About the dataset
  2. \n", 126 | "
  3. Data Visualization and Analysis
  4. \n", 127 | "
  5. Classification
  6. \n", 128 | "
\n", 129 | "
\n", 130 | "
\n", 131 | "
\n" 132 | ], 133 | "metadata": {} 134 | }, 135 | { 136 | "cell_type": "code", 137 | "source": "#!pip install scikit-learn==0.23.1", 138 | "metadata": { 139 | "trusted": true 140 | }, 141 | "execution_count": null, 142 | "outputs": [] 143 | }, 144 | { 145 | "cell_type": "code", 146 | "source": "import piplite\nawait piplite.install(['pandas'])\nawait piplite.install(['matplotlib'])\nawait piplite.install(['numpy'])\nawait piplite.install(['scikit-learn'])\nawait piplite.install(['scipy'])\n\n", 147 | "metadata": { 148 | "trusted": true 149 | }, 150 | "execution_count": null, 151 | "outputs": [] 152 | }, 153 | { 154 | "cell_type": "markdown", 155 | "source": [ 156 | "Let's load required libraries\n" 157 | ], 158 | "metadata": { 159 | "button": false, 160 | "new_sheet": false, 161 | "run_control": { 162 | "read_only": false 163 | } 164 | } 165 | }, 166 | { 167 | "cell_type": "code", 168 | "source": "import numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport numpy as np\nfrom sklearn import preprocessing\n%matplotlib inline", 169 | "metadata": { 170 | "button": false, 171 | "new_sheet": false, 172 | "run_control": { 173 | "read_only": false 174 | }, 175 | "trusted": true 176 | }, 177 | "execution_count": null, 178 | "outputs": [] 179 | }, 180 | { 181 | "cell_type": "markdown", 182 | "source": [ 183 | "
\n", 184 | "

About the dataset

\n", 185 | "
\n" 186 | ], 187 | "metadata": { 188 | "button": false, 189 | "new_sheet": false, 190 | "run_control": { 191 | "read_only": false 192 | } 193 | } 194 | }, 195 | { 196 | "cell_type": "markdown", 197 | "source": [ 198 | "Imagine a telecommunications provider has segmented its customer base by service usage patterns, categorizing the customers into four groups. If demographic data can be used to predict group membership, the company can customize offers for individual prospective customers. It is a classification problem. That is, given the dataset, with predefined labels, we need to build a model to be used to predict class of a new or unknown case.\n", 199 | "\n", 200 | "The example focuses on using demographic data, such as region, age, and marital, to predict usage patterns.\n", 201 | "\n", 202 | "The target field, called **custcat**, has four possible values that correspond to the four customer groups, as follows:\n", 203 | "1- Basic Service\n", 204 | "2- E-Service\n", 205 | "3- Plus Service\n", 206 | "4- Total Service\n", 207 | "\n", 208 | "Our objective is to build a classifier, to predict the class of unknown cases. We will use a specific type of classification called K nearest neighbour.\n" 209 | ], 210 | "metadata": { 211 | "button": false, 212 | "new_sheet": false, 213 | "run_control": { 214 | "read_only": false 215 | } 216 | } 217 | }, 218 | { 219 | "cell_type": "markdown", 220 | "source": [ 221 | "Let's download the dataset. To download the data, we will use !wget to download it from IBM Object Storage.\n" 222 | ], 223 | "metadata": { 224 | "button": false, 225 | "new_sheet": false, 226 | "run_control": { 227 | "read_only": false 228 | } 229 | } 230 | }, 231 | { 232 | "cell_type": "code", 233 | "source": "from pyodide.http import pyfetch\n\nasync def download(url, filename):\n response = await pyfetch(url)\n if response.status == 200:\n with open(filename, \"wb\") as f:\n f.write(await response.bytes())\n", 234 | "metadata": { 235 | "trusted": true 236 | }, 237 | "execution_count": null, 238 | "outputs": [] 239 | }, 240 | { 241 | "cell_type": "code", 242 | "source": "path=\"https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-ML0101EN-SkillsNetwork/labs/Module%203/data/teleCust1000t.csv\"", 243 | "metadata": { 244 | "trusted": true 245 | }, 246 | "execution_count": null, 247 | "outputs": [] 248 | }, 249 | { 250 | "cell_type": "markdown", 251 | "source": [ 252 | "**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)\n" 253 | ], 254 | "metadata": {} 255 | }, 256 | { 257 | "cell_type": "markdown", 258 | "source": [ 259 | "### Load Data From CSV File\n" 260 | ], 261 | "metadata": { 262 | "button": false, 263 | "new_sheet": false, 264 | "run_control": { 265 | "read_only": false 266 | } 267 | } 268 | }, 269 | { 270 | "cell_type": "code", 271 | "source": "await download(path, 'teleCust1000t.csv')\n ", 272 | "metadata": { 273 | "trusted": true 274 | }, 275 | "execution_count": null, 276 | "outputs": [] 277 | }, 278 | { 279 | "cell_type": "code", 280 | "source": "df = pd.read_csv('teleCust1000t.csv')\ndf.head()", 281 | "metadata": { 282 | "button": false, 283 | "new_sheet": false, 284 | "run_control": { 285 | "read_only": false 286 | }, 287 | "trusted": true 288 | }, 289 | "execution_count": null, 290 | "outputs": [] 291 | }, 292 | { 293 | "cell_type": "markdown", 294 | "source": [ 295 | "
\n", 296 | "

Data Visualization and Analysis

\n", 297 | "
\n" 298 | ], 299 | "metadata": { 300 | "button": false, 301 | "new_sheet": false, 302 | "run_control": { 303 | "read_only": false 304 | } 305 | } 306 | }, 307 | { 308 | "cell_type": "markdown", 309 | "source": [ 310 | "#### Let’s see how many of each class is in our data set\n" 311 | ], 312 | "metadata": { 313 | "button": false, 314 | "new_sheet": false, 315 | "run_control": { 316 | "read_only": false 317 | } 318 | } 319 | }, 320 | { 321 | "cell_type": "code", 322 | "source": "df['custcat'].value_counts()", 323 | "metadata": { 324 | "button": false, 325 | "new_sheet": false, 326 | "run_control": { 327 | "read_only": false 328 | }, 329 | "trusted": true 330 | }, 331 | "execution_count": null, 332 | "outputs": [] 333 | }, 334 | { 335 | "cell_type": "markdown", 336 | "source": [ 337 | "#### 281 Plus Service, 266 Basic-service, 236 Total Service, and 217 E-Service customers\n" 338 | ], 339 | "metadata": { 340 | "button": false, 341 | "new_sheet": false, 342 | "run_control": { 343 | "read_only": false 344 | } 345 | } 346 | }, 347 | { 348 | "cell_type": "markdown", 349 | "source": [ 350 | "You can easily explore your data using visualization techniques:\n" 351 | ], 352 | "metadata": {} 353 | }, 354 | { 355 | "cell_type": "code", 356 | "source": "df.hist(column='income', bins=50)", 357 | "metadata": { 358 | "trusted": true 359 | }, 360 | "execution_count": null, 361 | "outputs": [] 362 | }, 363 | { 364 | "cell_type": "markdown", 365 | "source": [ 366 | "### Feature set\n" 367 | ], 368 | "metadata": { 369 | "button": false, 370 | "new_sheet": false, 371 | "run_control": { 372 | "read_only": false 373 | } 374 | } 375 | }, 376 | { 377 | "cell_type": "markdown", 378 | "source": [ 379 | "Let's define feature sets, X:\n" 380 | ], 381 | "metadata": { 382 | "button": false, 383 | "new_sheet": false, 384 | "run_control": { 385 | "read_only": false 386 | } 387 | } 388 | }, 389 | { 390 | "cell_type": "code", 391 | "source": "df.columns", 392 | "metadata": { 393 | "trusted": true 394 | }, 395 | "execution_count": null, 396 | "outputs": [] 397 | }, 398 | { 399 | "cell_type": "markdown", 400 | "source": [ 401 | "To use scikit-learn library, we have to convert the Pandas data frame to a Numpy array:\n" 402 | ], 403 | "metadata": {} 404 | }, 405 | { 406 | "cell_type": "code", 407 | "source": "X = df[['region', 'tenure','age', 'marital', 'address', 'income', 'ed', 'employ','retire', 'gender', 'reside']] .values #.astype(float)\nX[0:5]\n", 408 | "metadata": { 409 | "button": false, 410 | "new_sheet": false, 411 | "run_control": { 412 | "read_only": false 413 | }, 414 | "trusted": true 415 | }, 416 | "execution_count": null, 417 | "outputs": [] 418 | }, 419 | { 420 | "cell_type": "markdown", 421 | "source": [ 422 | "What are our labels?\n" 423 | ], 424 | "metadata": { 425 | "button": false, 426 | "new_sheet": false, 427 | "run_control": { 428 | "read_only": false 429 | } 430 | } 431 | }, 432 | { 433 | "cell_type": "code", 434 | "source": "y = df['custcat'].values\ny[0:5]", 435 | "metadata": { 436 | "button": false, 437 | "new_sheet": false, 438 | "run_control": { 439 | "read_only": false 440 | }, 441 | "trusted": true 442 | }, 443 | "execution_count": null, 444 | "outputs": [] 445 | }, 446 | { 447 | "cell_type": "markdown", 448 | "source": [ 449 | "## Normalize Data\n" 450 | ], 451 | "metadata": { 452 | "button": false, 453 | "new_sheet": false, 454 | "run_control": { 455 | "read_only": false 456 | } 457 | } 458 | }, 459 | { 460 | "cell_type": "markdown", 461 | "source": [ 462 | "Data Standardization gives the data zero mean and unit variance, it is good practice, especially for algorithms such as KNN which is based on the distance of data points:\n" 463 | ], 464 | "metadata": { 465 | "button": false, 466 | "new_sheet": false, 467 | "run_control": { 468 | "read_only": false 469 | } 470 | } 471 | }, 472 | { 473 | "cell_type": "code", 474 | "source": "X = preprocessing.StandardScaler().fit(X).transform(X.astype(float))\nX[0:5]", 475 | "metadata": { 476 | "button": false, 477 | "new_sheet": false, 478 | "run_control": { 479 | "read_only": false 480 | }, 481 | "trusted": true 482 | }, 483 | "execution_count": null, 484 | "outputs": [] 485 | }, 486 | { 487 | "cell_type": "markdown", 488 | "source": [ 489 | "### Train Test Split\n", 490 | "\n", 491 | "Out of Sample Accuracy is the percentage of correct predictions that the model makes on data that the model has NOT been trained on. Doing a train and test on the same dataset will most likely have low out-of-sample accuracy, due to the likelihood of our model overfitting.\n", 492 | "\n", 493 | "It is important that our models have a high, out-of-sample accuracy, because the purpose of any model, of course, is to make correct predictions on unknown data. So how can we improve out-of-sample accuracy? One way is to use an evaluation approach called Train/Test Split.\n", 494 | "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", 495 | "\n", 496 | "This will provide a more accurate evaluation on out-of-sample accuracy because the testing dataset is not part of the dataset that has been used to train the model. It is more realistic for the real world problems.\n" 497 | ], 498 | "metadata": { 499 | "button": false, 500 | "new_sheet": false, 501 | "run_control": { 502 | "read_only": false 503 | } 504 | } 505 | }, 506 | { 507 | "cell_type": "code", 508 | "source": "from sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.2, random_state=4)\nprint ('Train set:', X_train.shape, y_train.shape)\nprint ('Test set:', X_test.shape, y_test.shape)", 509 | "metadata": { 510 | "button": false, 511 | "new_sheet": false, 512 | "run_control": { 513 | "read_only": false 514 | }, 515 | "trusted": true 516 | }, 517 | "execution_count": null, 518 | "outputs": [] 519 | }, 520 | { 521 | "cell_type": "markdown", 522 | "source": [ 523 | "
\n", 524 | "

Classification

\n", 525 | "
\n" 526 | ], 527 | "metadata": { 528 | "button": false, 529 | "new_sheet": false, 530 | "run_control": { 531 | "read_only": false 532 | } 533 | } 534 | }, 535 | { 536 | "cell_type": "markdown", 537 | "source": [ 538 | "

K nearest neighbor (KNN)

\n" 539 | ], 540 | "metadata": { 541 | "button": false, 542 | "new_sheet": false, 543 | "run_control": { 544 | "read_only": false 545 | } 546 | } 547 | }, 548 | { 549 | "cell_type": "markdown", 550 | "source": [ 551 | "#### Import library\n" 552 | ], 553 | "metadata": { 554 | "button": false, 555 | "new_sheet": false, 556 | "run_control": { 557 | "read_only": false 558 | } 559 | } 560 | }, 561 | { 562 | "cell_type": "markdown", 563 | "source": [ 564 | "Classifier implementing the k-nearest neighbors vote.\n" 565 | ], 566 | "metadata": { 567 | "button": false, 568 | "new_sheet": false, 569 | "run_control": { 570 | "read_only": false 571 | } 572 | } 573 | }, 574 | { 575 | "cell_type": "code", 576 | "source": "from sklearn.neighbors import KNeighborsClassifier", 577 | "metadata": { 578 | "button": false, 579 | "new_sheet": false, 580 | "run_control": { 581 | "read_only": false 582 | }, 583 | "trusted": true 584 | }, 585 | "execution_count": null, 586 | "outputs": [] 587 | }, 588 | { 589 | "cell_type": "markdown", 590 | "source": [ 591 | "### Training\n", 592 | "\n", 593 | "Let's start the algorithm with k=4 for now:\n" 594 | ], 595 | "metadata": { 596 | "button": false, 597 | "new_sheet": false, 598 | "run_control": { 599 | "read_only": false 600 | } 601 | } 602 | }, 603 | { 604 | "cell_type": "code", 605 | "source": "k = 4\n#Train Model and Predict \nneigh = KNeighborsClassifier(n_neighbors = k).fit(X_train,y_train)\nneigh", 606 | "metadata": { 607 | "button": false, 608 | "new_sheet": false, 609 | "run_control": { 610 | "read_only": false 611 | }, 612 | "trusted": true 613 | }, 614 | "execution_count": null, 615 | "outputs": [] 616 | }, 617 | { 618 | "cell_type": "markdown", 619 | "source": [ 620 | "### Predicting\n", 621 | "\n", 622 | "We can use the model to make predictions on the test set:\n" 623 | ], 624 | "metadata": { 625 | "button": false, 626 | "new_sheet": false, 627 | "run_control": { 628 | "read_only": false 629 | } 630 | } 631 | }, 632 | { 633 | "cell_type": "code", 634 | "source": "yhat = neigh.predict(X_test)\nyhat[0:5]", 635 | "metadata": { 636 | "button": false, 637 | "new_sheet": false, 638 | "run_control": { 639 | "read_only": false 640 | }, 641 | "trusted": true 642 | }, 643 | "execution_count": null, 644 | "outputs": [] 645 | }, 646 | { 647 | "cell_type": "markdown", 648 | "source": [ 649 | "### Accuracy evaluation\n", 650 | "\n", 651 | "In multilabel classification, **accuracy classification score** is a function that computes subset accuracy. This function is equal to the jaccard_score function. Essentially, it calculates how closely the actual labels and predicted labels are matched in the test set.\n" 652 | ], 653 | "metadata": { 654 | "button": false, 655 | "new_sheet": false, 656 | "run_control": { 657 | "read_only": false 658 | } 659 | } 660 | }, 661 | { 662 | "cell_type": "code", 663 | "source": "from sklearn import metrics\nprint(\"Train set Accuracy: \", metrics.accuracy_score(y_train, neigh.predict(X_train)))\nprint(\"Test set Accuracy: \", metrics.accuracy_score(y_test, yhat))", 664 | "metadata": { 665 | "trusted": true 666 | }, 667 | "execution_count": null, 668 | "outputs": [] 669 | }, 670 | { 671 | "cell_type": "markdown", 672 | "source": [ 673 | "## Practice\n", 674 | "\n", 675 | "Can you build the model again, but this time with k=6?\n" 676 | ], 677 | "metadata": {} 678 | }, 679 | { 680 | "cell_type": "code", 681 | "source": "# write your code here\n\n", 682 | "metadata": { 683 | "trusted": true 684 | }, 685 | "execution_count": null, 686 | "outputs": [] 687 | }, 688 | { 689 | "cell_type": "markdown", 690 | "source": [ 691 | "
Click here for the solution\n", 692 | "\n", 693 | "```python\n", 694 | "k = 6\n", 695 | "neigh6 = KNeighborsClassifier(n_neighbors = k).fit(X_train,y_train)\n", 696 | "yhat6 = neigh6.predict(X_test)\n", 697 | "print(\"Train set Accuracy: \", metrics.accuracy_score(y_train, neigh6.predict(X_train)))\n", 698 | "print(\"Test set Accuracy: \", metrics.accuracy_score(y_test, yhat6))\n", 699 | "\n", 700 | "```\n", 701 | "\n", 702 | "
\n" 703 | ], 704 | "metadata": {} 705 | }, 706 | { 707 | "cell_type": "markdown", 708 | "source": [ 709 | "#### What about other K?\n", 710 | "\n", 711 | "K in KNN, is the number of nearest neighbors to examine. It is supposed to be specified by the user. So, how can we choose right value for K?\n", 712 | "The general solution is to reserve a part of your data for testing the accuracy of the model. Then choose k =1, use the training part for modeling, and calculate the accuracy of prediction using all samples in your test set. Repeat this process, increasing the k, and see which k is the best for your model.\n", 713 | "\n", 714 | "We can calculate the accuracy of KNN for different values of k.\n" 715 | ], 716 | "metadata": { 717 | "button": false, 718 | "new_sheet": false, 719 | "run_control": { 720 | "read_only": false 721 | } 722 | } 723 | }, 724 | { 725 | "cell_type": "code", 726 | "source": "Ks = 10\nmean_acc = np.zeros((Ks-1))\nstd_acc = np.zeros((Ks-1))\n\nfor n in range(1,Ks):\n \n #Train Model and Predict \n neigh = KNeighborsClassifier(n_neighbors = n).fit(X_train,y_train)\n yhat=neigh.predict(X_test)\n mean_acc[n-1] = metrics.accuracy_score(y_test, yhat)\n\n \n std_acc[n-1]=np.std(yhat==y_test)/np.sqrt(yhat.shape[0])\n\nmean_acc", 727 | "metadata": { 728 | "button": false, 729 | "new_sheet": false, 730 | "run_control": { 731 | "read_only": false 732 | }, 733 | "trusted": true 734 | }, 735 | "execution_count": null, 736 | "outputs": [] 737 | }, 738 | { 739 | "cell_type": "markdown", 740 | "source": [ 741 | "#### Plot the model accuracy for a different number of neighbors.\n" 742 | ], 743 | "metadata": { 744 | "button": false, 745 | "new_sheet": false, 746 | "run_control": { 747 | "read_only": false 748 | } 749 | } 750 | }, 751 | { 752 | "cell_type": "code", 753 | "source": "plt.plot(range(1,Ks),mean_acc,'g')\nplt.fill_between(range(1,Ks),mean_acc - 1 * std_acc,mean_acc + 1 * std_acc, alpha=0.10)\nplt.fill_between(range(1,Ks),mean_acc - 3 * std_acc,mean_acc + 3 * std_acc, alpha=0.10,color=\"green\")\nplt.legend(('Accuracy ', '+/- 1xstd','+/- 3xstd'))\nplt.ylabel('Accuracy ')\nplt.xlabel('Number of Neighbors (K)')\nplt.tight_layout()\nplt.show()", 754 | "metadata": { 755 | "button": false, 756 | "new_sheet": false, 757 | "run_control": { 758 | "read_only": false 759 | }, 760 | "trusted": true 761 | }, 762 | "execution_count": null, 763 | "outputs": [] 764 | }, 765 | { 766 | "cell_type": "code", 767 | "source": "print( \"The best accuracy was with\", mean_acc.max(), \"with k=\", mean_acc.argmax()+1) ", 768 | "metadata": { 769 | "button": false, 770 | "new_sheet": false, 771 | "run_control": { 772 | "read_only": false 773 | }, 774 | "trusted": true 775 | }, 776 | "execution_count": null, 777 | "outputs": [] 778 | }, 779 | { 780 | "cell_type": "markdown", 781 | "source": [ 782 | "

Want to learn more?

\n", 783 | "\n", 784 | "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", 785 | "\n", 786 | "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" 787 | ], 788 | "metadata": { 789 | "button": false, 790 | "new_sheet": false, 791 | "run_control": { 792 | "read_only": false 793 | } 794 | } 795 | }, 796 | { 797 | "cell_type": "markdown", 798 | "source": [ 799 | "### Thank you for completing this lab!\n", 800 | "\n", 801 | "## Author\n", 802 | "\n", 803 | "Saeed Aghabozorgi\n", 804 | "\n", 805 | "### Other Contributors\n", 806 | "\n", 807 | "Joseph Santarcangelo\n", 808 | "\n", 809 | "## Change Log\n", 810 | "\n", 811 | "| Date (YYYY-MM-DD) | Version | Changed By | Change Description |\n", 812 | "| ----------------- | ------- | ---------- | ---------------------------------- |\n", 813 | "| 2021-01-21 | 2.4 | Lakshmi | Updated sklearn library |\n", 814 | "| 2020-11-20 | 2.3 | Lakshmi | Removed unused imports |\n", 815 | "| 2020-11-17 | 2.2 | Lakshmi | Changed plot function of KNN |\n", 816 | "| 2020-11-03 | 2.1 | Lakshmi | Changed URL of csv |\n", 817 | "| 2020-08-27 | 2.0 | Lavanya | Moved lab to course repo in GitLab |\n", 818 | "| | | | |\n", 819 | "| | | | |\n", 820 | "\n", 821 | "##

© IBM Corporation 2020. All rights reserved.

\n" 822 | ], 823 | "metadata": {} 824 | } 825 | ] 826 | } -------------------------------------------------------------------------------- /Classification/classification_tree_svm.ipynb: -------------------------------------------------------------------------------- 1 | {"cells":[{"cell_type":"markdown","id":"ef3f373c-e39a-4b5f-9bb8-a920d161f1b6","metadata":{},"outputs":[],"source":["\u003ccenter\u003e\n"," \u003cimg src=\"https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/assets/logos/SN_web_lightmode.png\" width=\"300\" alt=\"cognitiveclass.ai logo\"\u003e\n","\u003c/center\u003e\n"]},{"cell_type":"markdown","id":"8dbdecec-cd11-4a57-9df4-82c8a80a78eb","metadata":{},"outputs":[],"source":["# **Credit Card Fraud Detection using Scikit-Learn and Snap ML**\n"]},{"cell_type":"markdown","id":"ec071c2d-d1d4-4614-aa2a-189fc7c98f94","metadata":{},"outputs":[],"source":["Estimated time needed: **30** minutes\n"]},{"cell_type":"markdown","id":"0b1690b3-6524-4109-bf72-1a4daf11b4c7","metadata":{},"outputs":[],"source":["In this exercise session you will consolidate your machine learning (ML) modeling skills by using two popular classification models to recognize fraudulent credit card transactions. These models are: Decision Tree and Support Vector Machine. You will use a real dataset to train each of these models. The dataset includes information about \n","transactions made by credit cards in September 2013 by European cardholders. You will use the trained model to assess if a credit card transaction is legitimate or not.\n","\n","In the current exercise session, you will practice not only the Scikit-Learn Python interface, but also the Python API offered by the Snap Machine Learning (Snap ML) library. Snap ML is a high-performance IBM library for ML modeling. It provides highly-efficient CPU/GPU implementations of linear models and tree-based models. Snap ML not only accelerates ML algorithms through system awareness, but it also offers novel ML algorithms with best-in-class accuracy. For more information, please visit [snapml](https://ibm.biz/BdPfxy) information page.\n"]},{"cell_type":"markdown","id":"6f509f1e-49cf-4411-a4b8-b06a9e61ad6d","metadata":{},"outputs":[],"source":["## Objectives\n"]},{"cell_type":"markdown","id":"676d912b-2c5d-47d8-9cf8-2d15db8d8503","metadata":{},"outputs":[],"source":["After completing this lab you will be able to:\n"]},{"cell_type":"markdown","id":"c1b4e289-2670-476a-8746-9f4a1db8dadd","metadata":{},"outputs":[],"source":["* Perform basic data preprocessing in Python\n","* Model a classification task using the Scikit-Learn and Snap ML Python APIs\n","* Train Suppport Vector Machine and Decision Tree models using Scikit-Learn and Snap ML\n","* Run inference and assess the quality of the trained models\n"]},{"cell_type":"markdown","id":"27a382a6-b52f-4adb-be30-5754e81775b1","metadata":{},"outputs":[],"source":["## Table of Contents\n"]},{"cell_type":"markdown","id":"cf840df9-6d1a-490a-b8c8-e2d413329748","metadata":{},"outputs":[],"source":["\u003cdiv class=\"alert alert-block alert-info\" style=\"margin-top: 10px\"\u003e\n"," \u003col\u003e\n"," \u003cli\u003e\u003ca href=\"#introduction\"\u003eIntroduction\u003c/a\u003e\u003c/li\u003e\n"," \u003cli\u003e\u003ca href=\"#import_libraries\"\u003eImport Libraries\u003c/a\u003e\u003c/li\u003e\n"," \u003cli\u003e\u003ca href=\"#dataset_analysis\"\u003eDataset Analysis\u003c/a\u003e\u003c/li\u003e\n"," \u003cli\u003e\u003ca href=\"#dataset_preprocessing\"\u003eDataset Preprocessing\u003c/a\u003e\u003c/li\u003e\n"," \u003cli\u003e\u003ca href=\"#dataset_split\"\u003eDataset Train/Test Split\u003c/a\u003e\u003c/li\u003e\n"," \u003cli\u003e\u003ca href=\"#dt_sklearn\"\u003eBuild a Decision Tree Classifier model with Scikit-Learn\u003c/a\u003e\u003c/li\u003e\n"," \u003cli\u003e\u003ca href=\"#dt_snap\"\u003eBuild a Decision Tree Classifier model with Snap ML\u003c/a\u003e\u003c/li\u003e\n"," \u003cli\u003e\u003ca href=\"#dt_sklearn_snap\"\u003eEvaluate the Scikit-Learn and Snap ML Decision Tree Classifiers\u003c/a\u003e\u003c/li\u003e\n"," \u003cli\u003e\u003ca href=\"#svm_sklearn\"\u003eBuild a Support Vector Machine model with Scikit-Learn\u003c/a\u003e\u003c/li\u003e\n"," \u003cli\u003e\u003ca href=\"#svm_snap\"\u003eBuild a Support Vector Machine model with Snap ML\u003c/a\u003e\u003c/li\u003e\n"," \u003cli\u003e\u003ca href=\"#svm_sklearn_snap\"\u003eEvaluate the Scikit-Learn and Snap ML Support Vector Machine Models\u003c/a\u003e\u003c/li\u003e\n"," \u003c/ol\u003e\n","\u003c/div\u003e\n","\u003cbr\u003e\n","\u003chr\u003e\n"]},{"cell_type":"markdown","id":"d4427c75-08bc-41f9-97d3-7354e7ab6001","metadata":{},"outputs":[],"source":["\u003cdiv id=\"Introduction\"\u003e\n"," \u003ch2\u003eIntroduction\u003c/h2\u003e\n"," \u003cbr\u003eImagine that you work for a financial institution and part of your job is to build a model that predicts if a credit card transaction is fraudulent or not. You can model the problem as a binary classification problem. A transaction belongs to the positive class (1) if it is a fraud, otherwise it belongs to the negative class (0).\n"," \u003cbr\u003e\n"," \u003cbr\u003eYou have access to transactions that occured over a certain period of time. The majority of the transactions are normally legitimate and only a small fraction are non-legitimate. Thus, typically you have access to a dataset that is highly unbalanced. This is also the case of the current dataset: only 492 transactions out of 284,807 are fraudulent (the positive class - the frauds - accounts for 0.172% of all transactions).\n"," \u003cbr\u003e\n"," \u003cbr\u003eTo train the model you can use part of the input dataset and the remaining data can be used to assess the quality of the trained model. First, let's download the dataset.\n"," \u003cbr\u003e\n","\u003c/div\u003e\n"]},{"cell_type":"code","id":"b63e0611-cc91-414d-97db-c24950151d52","metadata":{},"outputs":[],"source":["# install the opendatasets package\n!pip install opendatasets\n\nimport opendatasets as od\n\n# download the dataset (this is a Kaggle dataset)\n# during download you will be required to input your Kaggle username and password\nod.download(\"https://www.kaggle.com/mlg-ulb/creditcardfraud\")"]},{"cell_type":"markdown","id":"92cf3cd1-1413-4e75-a88e-2b6413de6c58","metadata":{},"outputs":[],"source":["__Did you know?__ When it comes to Machine Learning, you will most 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://ibm.biz/BdPfxf)\n"]},{"cell_type":"markdown","id":"c44bc0d4-2b4c-4a91-883a-35fe50a7c070","metadata":{},"outputs":[],"source":["\u003cdiv id=\"import_libraries\"\u003e\n"," \u003ch2\u003eImport Libraries\u003c/h2\u003e\n","\u003c/div\u003e\n"]},{"cell_type":"code","id":"9e5df4a7-505b-4921-9f45-cad5c0fffd79","metadata":{},"outputs":[],"source":["# Snap ML is available on PyPI. To install it simply run the pip command below.\n!pip install snapml"]},{"cell_type":"code","id":"f0b103cc-6ffd-4bb2-8baf-55d246bfdd66","metadata":{},"outputs":[],"source":["# Import the libraries we need to use in this lab\nfrom __future__ import print_function\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n%matplotlib inline\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import normalize, StandardScaler\nfrom sklearn.utils.class_weight import compute_sample_weight\nfrom sklearn.metrics import roc_auc_score\nimport time\nimport warnings\nwarnings.filterwarnings('ignore')"]},{"cell_type":"markdown","id":"cfd4973c-1def-4a5b-aeb1-dffd117a515f","metadata":{},"outputs":[],"source":["\u003cdiv id=\"dataset_analysis\"\u003e\n"," \u003ch2\u003eDataset Analysis\u003c/h2\u003e\n","\u003c/div\u003e\n"]},{"cell_type":"markdown","id":"3cc91238-9566-4282-a711-a2dc01ef2752","metadata":{},"outputs":[],"source":["In this section you will read the dataset in a Pandas dataframe and visualize its content. You will also look at some data statistics. \n","\n","Note: A Pandas dataframe is a two-dimensional, size-mutable, potentially heterogeneous tabular data structure. For more information: https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.html. \n"]},{"cell_type":"code","id":"d81a695f-54e6-469a-8af1-80a682c98003","metadata":{},"outputs":[],"source":["# read the input data\nraw_data = pd.read_csv('creditcardfraud/creditcard.csv')\nprint(\"There are \" + str(len(raw_data)) + \" observations in the credit card fraud dataset.\")\nprint(\"There are \" + str(len(raw_data.columns)) + \" variables in the dataset.\")\n\n# display the first rows in the dataset\nraw_data.head()"]},{"cell_type":"code","id":"269cfea0-24a8-49b7-8932-656bd4b95547","metadata":{},"outputs":[],"source":["#Uncomment the following lines if you are unable to download the dataset using the Kaggle website.\n\n#url= \"https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-ML0101EN-SkillsNetwork/labs/Module%203/data/creditcard.csv\"\n#raw_data=pd.read_csv(url)\n#print(\"There are \" + str(len(raw_data)) + \" observations in the credit card fraud dataset.\")\n#print(\"There are \" + str(len(raw_data.columns)) + \" variables in the dataset.\")\n#raw_data.head()"]},{"cell_type":"markdown","id":"0e7a1db2-d2a1-4948-b47a-ef55ac8c249c","metadata":{},"outputs":[],"source":["In practice, a financial institution may have access to a much larger dataset of transactions. To simulate such a case, we will inflate the original one 10 times.\n"]},{"cell_type":"code","id":"b856cd22-57e4-4774-9bb9-ff9d2e1ae5ec","metadata":{},"outputs":[],"source":["n_replicas = 10\n\n# inflate the original dataset\nbig_raw_data = pd.DataFrame(np.repeat(raw_data.values, n_replicas, axis=0), columns=raw_data.columns)\n\nprint(\"There are \" + str(len(big_raw_data)) + \" observations in the inflated credit card fraud dataset.\")\nprint(\"There are \" + str(len(big_raw_data.columns)) + \" variables in the dataset.\")\n\n# display first rows in the new dataset\nbig_raw_data.head()"]},{"cell_type":"markdown","id":"02909172-1b5b-4118-83d1-79df94fb32b3","metadata":{},"outputs":[],"source":["Each row in the dataset represents a credit card transaction. As shown above, each row has 31 variables. One variable (the last variable in the table above) is called Class and represents the target variable. Your objective will be to train a model that uses the other variables to predict the value of the Class variable. Let's first retrieve basic statistics about the target variable.\n","\n","Note: For confidentiality reasons, the original names of most features are anonymized V1, V2 .. V28. The values of these features are the result of a PCA transformation and are numerical. The feature 'Class' is the target variable and it takes two values: 1 in case of fraud and 0 otherwise. For more information about the dataset please visit this webpage: https://www.kaggle.com/mlg-ulb/creditcardfraud.\n"]},{"cell_type":"code","id":"b6eea1c2-9a0f-488a-b06f-2f19d1c11c51","metadata":{},"outputs":[],"source":["# get the set of distinct classes\nlabels = big_raw_data.Class.unique()\n\n# get the count of each class\nsizes = big_raw_data.Class.value_counts().values\n\n# plot the class value counts\nfig, ax = plt.subplots()\nax.pie(sizes, labels=labels, autopct='%1.3f%%')\nax.set_title('Target Variable Value Counts')\nplt.show()"]},{"cell_type":"markdown","id":"0345ac2b-7b3e-4379-be48-5db5df114308","metadata":{},"outputs":[],"source":["As shown above, the Class variable has two values: 0 (the credit card transaction is legitimate) and 1 (the credit card transaction is fraudulent). Thus, you need to model a binary classification problem. Moreover, the dataset is highly unbalanced, the target variable classes are not represented equally. This case requires special attention when training or when evaluating the quality of a model. One way of handing this case at train time is to bias the model to pay more attention to the samples in the minority class. The models under the current study will be configured to take into account the class weights of the samples at train/fit time.\n"]},{"cell_type":"markdown","id":"76a77289-16aa-4861-a36e-0d5df963bb35","metadata":{},"outputs":[],"source":["### Practice\n"]},{"cell_type":"markdown","id":"7a580e4a-13b9-4033-944a-022f5871dc3c","metadata":{},"outputs":[],"source":["The credit card transactions have different amounts. Could you plot a histogram that shows the distribution of these amounts? What is the range of these amounts (min/max)? Could you print the 90th percentile of the amount values?\n"]},{"cell_type":"code","id":"e8f64dfb-12a5-423b-be7f-4d1c018b12a5","metadata":{},"outputs":[],"source":["# your code here"]},{"cell_type":"code","id":"915a7737-d86d-4f47-99bb-6ed85aa316d1","metadata":{},"outputs":[],"source":["# we provide our solution here\nplt.hist(big_raw_data.Amount.values, 6, histtype='bar', facecolor='g')\nplt.show()\n\nprint(\"Minimum amount value is \", np.min(big_raw_data.Amount.values))\nprint(\"Maximum amount value is \", np.max(big_raw_data.Amount.values))\nprint(\"90% of the transactions have an amount less or equal than \", np.percentile(raw_data.Amount.values, 90))"]},{"cell_type":"markdown","id":"bc974abe-8deb-4921-a72d-dfdcf6317c7e","metadata":{},"outputs":[],"source":["\u003cdiv id=\"dataset_preprocessing\"\u003e\n"," \u003ch2\u003eDataset Preprocessing\u003c/h2\u003e\n","\u003c/div\u003e\n"]},{"cell_type":"markdown","id":"3ab66dad-f870-45bf-aecf-a45f2231d684","metadata":{},"outputs":[],"source":["In this subsection you will prepare the data for training. \n"]},{"cell_type":"code","id":"fafe2ed1-84a3-4593-a278-9bf2d259fa4b","metadata":{},"outputs":[],"source":["# data preprocessing such as scaling/normalization is typically useful for \n# linear models to accelerate the training convergence\n\n# standardize features by removing the mean and scaling to unit variance\nbig_raw_data.iloc[:, 1:30] = StandardScaler().fit_transform(big_raw_data.iloc[:, 1:30])\ndata_matrix = big_raw_data.values\n\n# X: feature matrix (for this analysis, we exclude the Time variable from the dataset)\nX = data_matrix[:, 1:30]\n\n# y: labels vector\ny = data_matrix[:, 30]\n\n# data normalization\nX = normalize(X, norm=\"l1\")\n\n# print the shape of the features matrix and the labels vector\nprint('X.shape=', X.shape, 'y.shape=', y.shape)"]},{"cell_type":"markdown","id":"578fedad-8101-4bd1-9427-12a075ee4256","metadata":{},"outputs":[],"source":["\u003cdiv id=\"dataset_split\"\u003e\n"," \u003ch2\u003eDataset Train/Test Split\u003c/h2\u003e\n","\u003c/div\u003e\n"]},{"cell_type":"markdown","id":"cf03ffcf-efc6-42ad-87e6-190c00c1d657","metadata":{},"outputs":[],"source":["Now that the dataset is ready for building the classification models, you need to first divide the pre-processed dataset into a subset to be used for training the model (the train set) and a subset to be used for evaluating the quality of the model (the test set).\n"]},{"cell_type":"code","id":"ebf3c04a-5eee-4000-ab41-8628a18cbf4f","metadata":{},"outputs":[],"source":["X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42, stratify=y) \nprint('X_train.shape=', X_train.shape, 'Y_train.shape=', y_train.shape)\nprint('X_test.shape=', X_test.shape, 'Y_test.shape=', y_test.shape)"]},{"cell_type":"markdown","id":"d21e2582-33b9-46c9-9b3a-7fbba2c98750","metadata":{},"outputs":[],"source":["\u003cdiv id=\"dt_sklearn\"\u003e\n"," \u003ch2\u003eBuild a Decision Tree Classifier model with Scikit-Learn\u003c/h2\u003e\n","\u003c/div\u003e\n"]},{"cell_type":"code","id":"f47fb031-dd33-40f8-93a4-198d9e12e095","metadata":{},"outputs":[],"source":["# compute the sample weights to be used as input to the train routine so that \n# it takes into account the class imbalance present in this dataset\nw_train = compute_sample_weight('balanced', y_train)\n\n# import the Decision Tree Classifier Model from scikit-learn\nfrom sklearn.tree import DecisionTreeClassifier\n\n# for reproducible output across multiple function calls, set random_state to a given integer value\nsklearn_dt = DecisionTreeClassifier(max_depth=4, random_state=35)\n\n# train a Decision Tree Classifier using scikit-learn\nt0 = time.time()\nsklearn_dt.fit(X_train, y_train, sample_weight=w_train)\nsklearn_time = time.time()-t0\nprint(\"[Scikit-Learn] Training time (s): {0:.5f}\".format(sklearn_time))"]},{"cell_type":"markdown","id":"bfaf66ee-a51c-43a2-8c33-5e38fa16e6c1","metadata":{},"outputs":[],"source":["\u003cdiv id=\"dt_snapml\"\u003e\n"," \u003ch2\u003eBuild a Decision Tree Classifier model with Snap ML\u003c/h2\u003e\n","\u003c/div\u003e\n"]},{"cell_type":"code","id":"52f544f8-fdf0-4414-b5b1-551298a47235","metadata":{},"outputs":[],"source":["# if not already computed, \n# compute the sample weights to be used as input to the train routine so that \n# it takes into account the class imbalance present in this dataset\n# w_train = compute_sample_weight('balanced', y_train)\n\n# import the Decision Tree Classifier Model from Snap ML\nfrom snapml import DecisionTreeClassifier\n\n# Snap ML offers multi-threaded CPU/GPU training of decision trees, unlike scikit-learn\n# to use the GPU, set the use_gpu parameter to True\n# snapml_dt = DecisionTreeClassifier(max_depth=4, random_state=45, use_gpu=True)\n\n# to set the number of CPU threads used at training time, set the n_jobs parameter\n# for reproducible output across multiple function calls, set random_state to a given integer value\nsnapml_dt = DecisionTreeClassifier(max_depth=4, random_state=45, n_jobs=4)\n\n# train a Decision Tree Classifier model using Snap ML\nt0 = time.time()\nsnapml_dt.fit(X_train, y_train, sample_weight=w_train)\nsnapml_time = time.time()-t0\nprint(\"[Snap ML] Training time (s): {0:.5f}\".format(snapml_time))"]},{"cell_type":"markdown","id":"863dac88-0c61-4ed5-b145-0b886cdaf59d","metadata":{},"outputs":[],"source":["\u003cdiv id=\"dt_sklearn_snapml\"\u003e\n"," \u003ch2\u003eEvaluate the Scikit-Learn and Snap ML Decision Tree Classifier Models\u003c/h2\u003e\n","\u003c/div\u003e\n"]},{"cell_type":"code","id":"854e529e-6fd6-4643-bf5d-638328aa9c66","metadata":{},"outputs":[],"source":["# Snap ML vs Scikit-Learn training speedup\ntraining_speedup = sklearn_time/snapml_time\nprint('[Decision Tree Classifier] Snap ML vs. Scikit-Learn speedup : {0:.2f}x '.format(training_speedup))\n\n# run inference and compute the probabilities of the test samples \n# to belong to the class of fraudulent transactions\nsklearn_pred = sklearn_dt.predict_proba(X_test)[:,1]\n\n# evaluate the Compute Area Under the Receiver Operating Characteristic \n# Curve (ROC-AUC) score from the predictions\nsklearn_roc_auc = roc_auc_score(y_test, sklearn_pred)\nprint('[Scikit-Learn] ROC-AUC score : {0:.3f}'.format(sklearn_roc_auc))\n\n# run inference and compute the probabilities of the test samples\n# to belong to the class of fraudulent transactions\nsnapml_pred = snapml_dt.predict_proba(X_test)[:,1]\n\n# evaluate the Compute Area Under the Receiver Operating Characteristic\n# Curve (ROC-AUC) score from the prediction scores\nsnapml_roc_auc = roc_auc_score(y_test, snapml_pred) \nprint('[Snap ML] ROC-AUC score : {0:.3f}'.format(snapml_roc_auc))"]},{"cell_type":"markdown","id":"bdfd6017-e6b3-4ae5-8622-d6042a00c703","metadata":{},"outputs":[],"source":["As shown above both decision tree models provide the same score on the test dataset. However Snap ML runs the training routine 12x faster than Scikit-Learn. This is one of the advantages of using Snap ML: acceleration of training of classical machine learning models, such as linear and tree-based models. For more Snap ML examples, please visit [snapml-examples](https://ibm.biz/BdPfxP).\n"]},{"cell_type":"markdown","id":"93ba40ba-1bb0-4fee-be5d-30393685744e","metadata":{},"outputs":[],"source":["\u003cdiv id=\"svm_sklearn\"\u003e\n"," \u003ch2\u003eBuild a Support Vector Machine model with Scikit-Learn\u003c/h2\u003e\n","\u003c/div\u003e\n"]},{"cell_type":"code","id":"0aaa921a-6e17-4aa9-b501-d8c4eac4d746","metadata":{},"outputs":[],"source":["# import the linear Support Vector Machine (SVM) model from Scikit-Learn\nfrom sklearn.svm import LinearSVC\n\n# instatiate a scikit-learn SVM model\n# to indicate the class imbalance at fit time, set class_weight='balanced'\n# for reproducible output across multiple function calls, set random_state to a given integer value\nsklearn_svm = LinearSVC(class_weight='balanced', random_state=31, loss=\"hinge\", fit_intercept=False)\n\n# train a linear Support Vector Machine model using Scikit-Learn\nt0 = time.time()\nsklearn_svm.fit(X_train, y_train)\nsklearn_time = time.time() - t0\nprint(\"[Scikit-Learn] Training time (s): {0:.2f}\".format(sklearn_time))"]},{"cell_type":"markdown","id":"f2eb1ece-234e-4490-9d71-10c534b9eec0","metadata":{},"outputs":[],"source":["\u003cdiv id=\"svm_snap\"\u003e\n"," \u003ch2\u003eBuild a Support Vector Machine model with Snap ML\u003c/h2\u003e\n","\u003c/div\u003e\n"]},{"cell_type":"code","id":"2078a824-1839-4c36-9a0d-2c19c39a01d4","metadata":{},"outputs":[],"source":["# import the Support Vector Machine model (SVM) from Snap ML\nfrom snapml import SupportVectorMachine\n\n# in contrast to scikit-learn's LinearSVC, Snap ML offers multi-threaded CPU/GPU training of SVMs\n# to use the GPU, set the use_gpu parameter to True\n# snapml_svm = SupportVectorMachine(class_weight='balanced', random_state=25, use_gpu=True, fit_intercept=False)\n\n# to set the number of threads used at training time, one needs to set the n_jobs parameter\nsnapml_svm = SupportVectorMachine(class_weight='balanced', random_state=25, n_jobs=4, fit_intercept=False)\n# print(snapml_svm.get_params())\n\n# train an SVM model using Snap ML\nt0 = time.time()\nmodel = snapml_svm.fit(X_train, y_train)\nsnapml_time = time.time() - t0\nprint(\"[Snap ML] Training time (s): {0:.2f}\".format(snapml_time))"]},{"cell_type":"markdown","id":"fd2825c3-05d2-4177-956d-7c2723c13449","metadata":{},"outputs":[],"source":["\u003cdiv id=\"svm_sklearn_snap\"\u003e\n"," \u003ch2\u003eEvaluate the Scikit-Learn and Snap ML Support Vector Machine Models\u003c/h2\u003e\n","\u003c/div\u003e\n"]},{"cell_type":"code","id":"13d141f3-fc01-4fff-9225-7ee5b8cdb13d","metadata":{},"outputs":[],"source":["# compute the Snap ML vs Scikit-Learn training speedup\ntraining_speedup = sklearn_time/snapml_time\nprint('[Support Vector Machine] Snap ML vs. Scikit-Learn training speedup : {0:.2f}x '.format(training_speedup))\n\n# run inference using the Scikit-Learn model\n# get the confidence scores for the test samples\nsklearn_pred = sklearn_svm.decision_function(X_test)\n\n# evaluate accuracy on test set\nacc_sklearn = roc_auc_score(y_test, sklearn_pred)\nprint(\"[Scikit-Learn] ROC-AUC score: {0:.3f}\".format(acc_sklearn))\n\n# run inference using the Snap ML model\n# get the confidence scores for the test samples\nsnapml_pred = snapml_svm.decision_function(X_test)\n\n# evaluate accuracy on test set\nacc_snapml = roc_auc_score(y_test, snapml_pred)\nprint(\"[Snap ML] ROC-AUC score: {0:.3f}\".format(acc_snapml))"]},{"cell_type":"markdown","id":"d9c9c383-8488-4c4e-9ec9-2c87b60332a4","metadata":{},"outputs":[],"source":["As shown above both SVM models provide the same score on the test dataset. However, as in the case of decision trees, Snap ML runs the training routine faster than Scikit-Learn. For more Snap ML examples, please visit [snapml-examples](https://ibm.biz/BdPfxP). Moreover, as shown above, not only is Snap ML seemlessly accelerating scikit-learn applications, but the library's Python API is also compatible with scikit-learn metrics and data preprocessors.\n"]},{"cell_type":"markdown","id":"bb0ef68e-9160-4472-8072-aace3e649ecf","metadata":{},"outputs":[],"source":["### Practice\n"]},{"cell_type":"markdown","id":"6ec6d773-355a-45df-834a-497678a83797","metadata":{},"outputs":[],"source":["In this section you will evaluate the quality of the SVM models trained above using the hinge loss metric (https://scikit-learn.org/stable/modules/generated/sklearn.metrics.hinge_loss.html). Run inference on the test set using both Scikit-Learn and Snap ML models. Compute the hinge loss metric for both sets of predictions. Print the hinge losses of Scikit-Learn and Snap ML.\n"]},{"cell_type":"code","id":"2b4cdadb-0dc7-46df-a96a-c03a70023704","metadata":{},"outputs":[],"source":["# your code goes here"]},{"cell_type":"code","id":"255c8bf9-979b-46dd-8ab1-80c6026e26c0","metadata":{},"outputs":[],"source":["# get the confidence scores for the test samples\nsklearn_pred = sklearn_svm.decision_function(X_test)\nsnapml_pred = snapml_svm.decision_function(X_test)\n\n# import the hinge_loss metric from scikit-learn\nfrom sklearn.metrics import hinge_loss\n\n# evaluate the hinge loss from the predictions\nloss_snapml = hinge_loss(y_test, snapml_pred)\nprint(\"[Snap ML] Hinge loss: {0:.3f}\".format(loss_snapml))\n\n# evaluate the hinge loss metric from the predictions\nloss_sklearn = hinge_loss(y_test, sklearn_pred)\nprint(\"[Scikit-Learn] Hinge loss: {0:.3f}\".format(loss_snapml))\n\n# the two models should give the same Hinge loss"]},{"cell_type":"markdown","id":"ac1c96f3-aa3e-4994-badd-135ba2f262ea","metadata":{},"outputs":[],"source":["## Authors\n"]},{"cell_type":"markdown","id":"48d1f5f9-a1f1-4237-99b2-ec5365924ce8","metadata":{},"outputs":[],"source":["Andreea Anghel\n"]},{"cell_type":"markdown","id":"ee595903-8c72-458b-83ac-4f97d7f0d474","metadata":{},"outputs":[],"source":["### Other Contributors\n"]},{"cell_type":"markdown","id":"d04171cd-fad2-4bf4-a519-2e6821d5a5e3","metadata":{},"outputs":[],"source":["Joseph Santarcangelo\n"]},{"cell_type":"markdown","id":"7f3815b6-3b71-4310-aac3-28cd8277a85f","metadata":{},"outputs":[],"source":["## Change Log\n"]},{"cell_type":"markdown","id":"f64915d1-9b98-4de7-840e-b9018b59ee1d","metadata":{},"outputs":[],"source":["| Date (YYYY-MM-DD) | Version | Changed By | Change Description |\n","|---|---|---|---|\n","| 2021-08-31 | 0.1 | AAN | Created Lab Content |\n"]},{"cell_type":"markdown","id":"54920996-2b56-4130-b1d4-14262bc459e0","metadata":{},"outputs":[],"source":[" Copyright \u0026copy; 2021 IBM Corporation. This notebook and its source code are released under the terms of the [MIT License](https://cognitiveclass.ai/mit-license/).\n"]}],"metadata":{"kernelspec":{"display_name":"Python","language":"python","name":"conda-env-python-py"},"language_info":{"name":""}},"nbformat":4,"nbformat_minor":4} -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Coursera-IBM-AI-Engineering 2 | I have saved all the program which i did during my coursera course 3 | -------------------------------------------------------------------------------- /Regression/Module 2_ML0101EN-Reg-Mulitple-Linear-Regression-Co2.jupyterlite.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "metadata": { 3 | "kernelspec": { 4 | "name": "python", 5 | "display_name": "Pyolite", 6 | "language": "python" 7 | }, 8 | "language_info": { 9 | "codemirror_mode": { 10 | "name": "python", 11 | "version": 3 12 | }, 13 | "file_extension": ".py", 14 | "mimetype": "text/x-python", 15 | "name": "python", 16 | "nbconvert_exporter": "python", 17 | "pygments_lexer": "ipython3", 18 | "version": "3.8" 19 | }, 20 | "widgets": { 21 | "state": {}, 22 | "version": "1.1.2" 23 | } 24 | }, 25 | "nbformat_minor": 4, 26 | "nbformat": 4, 27 | "cells": [ 28 | { 29 | "cell_type": "markdown", 30 | "source": [ 31 | "

\n", 32 | " \n", 33 | " \"Skills\n", 34 | " \n", 35 | "

\n", 36 | "\n", 37 | "# Multiple Linear Regression\n", 38 | "\n", 39 | "Estimated time needed: **15** minutes\n", 40 | "\n", 41 | "## Objectives\n", 42 | "\n", 43 | "After completing this lab you will be able to:\n", 44 | "\n", 45 | "* Use scikit-learn to implement Multiple Linear Regression\n", 46 | "* Create a model, train it, test it and use the model\n" 47 | ], 48 | "metadata": { 49 | "button": false, 50 | "new_sheet": false, 51 | "run_control": { 52 | "read_only": false 53 | } 54 | } 55 | }, 56 | { 57 | "cell_type": "markdown", 58 | "source": [ 59 | "

Table of contents

\n", 60 | "\n", 61 | "
\n", 62 | "
    \n", 63 | "
  1. Understanding the Data
  2. \n", 64 | "
  3. Reading the Data in
  4. \n", 65 | "
  5. Multiple Regression Model
  6. \n", 66 | "
  7. Prediction
  8. \n", 67 | "
  9. Practice
  10. \n", 68 | "
\n", 69 | "
\n", 70 | "
\n", 71 | "
\n" 72 | ], 73 | "metadata": {} 74 | }, 75 | { 76 | "cell_type": "markdown", 77 | "source": [ 78 | "### Importing Needed packages\n" 79 | ], 80 | "metadata": { 81 | "button": false, 82 | "new_sheet": false, 83 | "run_control": { 84 | "read_only": false 85 | } 86 | } 87 | }, 88 | { 89 | "cell_type": "code", 90 | "source": "", 91 | "metadata": { 92 | "trusted": true 93 | }, 94 | "execution_count": null, 95 | "outputs": [] 96 | }, 97 | { 98 | "cell_type": "code", 99 | "source": "import piplite\nawait piplite.install(['pandas'])\nawait piplite.install(['matplotlib'])\nawait piplite.install(['numpy'])\nawait piplite.install(['scikit-learn'])\n", 100 | "metadata": { 101 | "trusted": true 102 | }, 103 | "execution_count": null, 104 | "outputs": [] 105 | }, 106 | { 107 | "cell_type": "code", 108 | "source": "import matplotlib.pyplot as plt\nimport pandas as pd\nimport pylab as pl\nimport numpy as np\n%matplotlib inline", 109 | "metadata": { 110 | "button": false, 111 | "new_sheet": false, 112 | "run_control": { 113 | "read_only": false 114 | }, 115 | "trusted": true 116 | }, 117 | "execution_count": null, 118 | "outputs": [] 119 | }, 120 | { 121 | "cell_type": "markdown", 122 | "source": [ 123 | "### Downloading Data\n", 124 | "\n", 125 | "we will use the link, we will use !wget to download it from IBM Object Storage.\n" 126 | ], 127 | "metadata": { 128 | "button": false, 129 | "new_sheet": false, 130 | "run_control": { 131 | "read_only": false 132 | } 133 | } 134 | }, 135 | { 136 | "cell_type": "code", 137 | "source": "path='https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-ML0101EN-SkillsNetwork/labs/Module%202/data/FuelConsumptionCo2.csv'", 138 | "metadata": { 139 | "button": false, 140 | "new_sheet": false, 141 | "run_control": { 142 | "read_only": false 143 | }, 144 | "trusted": true 145 | }, 146 | "execution_count": null, 147 | "outputs": [] 148 | }, 149 | { 150 | "cell_type": "code", 151 | "source": "from pyodide.http import pyfetch\n\nasync def download(url, filename):\n response = await pyfetch(url)\n if response.status == 200:\n with open(filename, \"wb\") as f:\n f.write(await response.bytes())", 152 | "metadata": { 153 | "trusted": true 154 | }, 155 | "execution_count": null, 156 | "outputs": [] 157 | }, 158 | { 159 | "cell_type": "markdown", 160 | "source": [ 161 | "**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)\n" 162 | ], 163 | "metadata": {} 164 | }, 165 | { 166 | "cell_type": "markdown", 167 | "source": [ 168 | "

Understanding the Data

\n", 169 | "\n", 170 | "### `FuelConsumption.csv`:\n", 171 | "\n", 172 | "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?utm_medium=Exinfluencer&utm_source=Exinfluencer&utm_content=000026UJ&utm_term=10006555&utm_id=NA-SkillsNetwork-Channel-SkillsNetworkCoursesIBMDeveloperSkillsNetworkML0101ENSkillsNetwork20718538-2022-01-01)\n", 173 | "\n", 174 | "* **MODELYEAR** e.g. 2014\n", 175 | "* **MAKE** e.g. Acura\n", 176 | "* **MODEL** e.g. ILX\n", 177 | "* **VEHICLE CLASS** e.g. SUV\n", 178 | "* **ENGINE SIZE** e.g. 4.7\n", 179 | "* **CYLINDERS** e.g 6\n", 180 | "* **TRANSMISSION** e.g. A6\n", 181 | "* **FUELTYPE** e.g. z\n", 182 | "* **FUEL CONSUMPTION in CITY(L/100 km)** e.g. 9.9\n", 183 | "* **FUEL CONSUMPTION in HWY (L/100 km)** e.g. 8.9\n", 184 | "* **FUEL CONSUMPTION COMB (L/100 km)** e.g. 9.2\n", 185 | "* **CO2 EMISSIONS (g/km)** e.g. 182 --> low --> 0\n" 186 | ], 187 | "metadata": { 188 | "button": false, 189 | "new_sheet": false, 190 | "run_control": { 191 | "read_only": false 192 | } 193 | } 194 | }, 195 | { 196 | "cell_type": "markdown", 197 | "source": [ 198 | "

Reading the data in

\n" 199 | ], 200 | "metadata": { 201 | "button": false, 202 | "new_sheet": false, 203 | "run_control": { 204 | "read_only": false 205 | } 206 | } 207 | }, 208 | { 209 | "cell_type": "code", 210 | "source": "await download(path, \"FuelConsumption.csv\")\npath=\"FuelConsumption.csv\"", 211 | "metadata": { 212 | "trusted": true 213 | }, 214 | "execution_count": null, 215 | "outputs": [] 216 | }, 217 | { 218 | "cell_type": "code", 219 | "source": "df = pd.read_csv(path)\n\n# take a look at the dataset\ndf.head()", 220 | "metadata": { 221 | "button": false, 222 | "new_sheet": false, 223 | "run_control": { 224 | "read_only": false 225 | }, 226 | "trusted": true 227 | }, 228 | "execution_count": null, 229 | "outputs": [] 230 | }, 231 | { 232 | "cell_type": "markdown", 233 | "source": [ 234 | "Let's select some features that we want to use for regression.\n" 235 | ], 236 | "metadata": {} 237 | }, 238 | { 239 | "cell_type": "code", 240 | "source": "cdf = df[['ENGINESIZE','CYLINDERS','FUELCONSUMPTION_CITY','FUELCONSUMPTION_HWY','FUELCONSUMPTION_COMB','CO2EMISSIONS']]\ncdf.head(9)", 241 | "metadata": { 242 | "button": false, 243 | "new_sheet": false, 244 | "run_control": { 245 | "read_only": false 246 | }, 247 | "trusted": true 248 | }, 249 | "execution_count": null, 250 | "outputs": [] 251 | }, 252 | { 253 | "cell_type": "markdown", 254 | "source": [ 255 | "Let's plot Emission values with respect to Engine size:\n" 256 | ], 257 | "metadata": {} 258 | }, 259 | { 260 | "cell_type": "code", 261 | "source": "plt.scatter(cdf.ENGINESIZE, cdf.CO2EMISSIONS, color='blue')\nplt.xlabel(\"Engine size\")\nplt.ylabel(\"Emission\")\nplt.show()", 262 | "metadata": { 263 | "button": false, 264 | "new_sheet": false, 265 | "run_control": { 266 | "read_only": false 267 | }, 268 | "scrolled": true, 269 | "trusted": true 270 | }, 271 | "execution_count": null, 272 | "outputs": [] 273 | }, 274 | { 275 | "cell_type": "markdown", 276 | "source": [ 277 | "#### Creating train and test dataset\n", 278 | "\n", 279 | "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", 280 | "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", 281 | "\n", 282 | "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", 283 | "\n", 284 | "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" 285 | ], 286 | "metadata": { 287 | "button": false, 288 | "new_sheet": false, 289 | "run_control": { 290 | "read_only": false 291 | } 292 | } 293 | }, 294 | { 295 | "cell_type": "code", 296 | "source": "msk = np.random.rand(len(df)) < 0.8\ntrain = cdf[msk]\ntest = cdf[~msk]", 297 | "metadata": { 298 | "button": false, 299 | "new_sheet": false, 300 | "run_control": { 301 | "read_only": false 302 | }, 303 | "trusted": true 304 | }, 305 | "execution_count": null, 306 | "outputs": [] 307 | }, 308 | { 309 | "cell_type": "markdown", 310 | "source": [ 311 | "#### Train data distribution\n" 312 | ], 313 | "metadata": { 314 | "button": false, 315 | "new_sheet": false, 316 | "run_control": { 317 | "read_only": false 318 | } 319 | } 320 | }, 321 | { 322 | "cell_type": "code", 323 | "source": "plt.scatter(train.ENGINESIZE, train.CO2EMISSIONS, color='blue')\nplt.xlabel(\"Engine size\")\nplt.ylabel(\"Emission\")\nplt.show()", 324 | "metadata": { 325 | "button": false, 326 | "new_sheet": false, 327 | "run_control": { 328 | "read_only": false 329 | }, 330 | "trusted": true 331 | }, 332 | "execution_count": null, 333 | "outputs": [] 334 | }, 335 | { 336 | "cell_type": "markdown", 337 | "source": [ 338 | "

Multiple Regression Model

\n" 339 | ], 340 | "metadata": { 341 | "button": false, 342 | "new_sheet": false, 343 | "run_control": { 344 | "read_only": false 345 | } 346 | } 347 | }, 348 | { 349 | "cell_type": "markdown", 350 | "source": [ 351 | "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" 352 | ], 353 | "metadata": {} 354 | }, 355 | { 356 | "cell_type": "code", 357 | "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_)", 358 | "metadata": { 359 | "button": false, 360 | "new_sheet": false, 361 | "run_control": { 362 | "read_only": false 363 | }, 364 | "trusted": true 365 | }, 366 | "execution_count": null, 367 | "outputs": [] 368 | }, 369 | { 370 | "cell_type": "markdown", 371 | "source": [ 372 | "As mentioned before, **Coefficient** and **Intercept** are the parameters of the fitted line.\n", 373 | "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", 374 | "\n", 375 | "#### Ordinary Least Squares (OLS)\n", 376 | "\n", 377 | "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", 378 | "\n", 379 | "OLS can find the best parameters using of the following methods:\n", 380 | "\n", 381 | "* Solving the model parameters analytically using closed-form equations\n", 382 | "* Using an optimization algorithm (Gradient Descent, Stochastic Gradient Descent, Newton’s Method, etc.)\n" 383 | ], 384 | "metadata": {} 385 | }, 386 | { 387 | "cell_type": "markdown", 388 | "source": [ 389 | "

Prediction

\n" 390 | ], 391 | "metadata": {} 392 | }, 393 | { 394 | "cell_type": "code", 395 | "source": "y_hat= regr.predict(test[['ENGINESIZE','CYLINDERS','FUELCONSUMPTION_COMB']])\nx = np.asanyarray(test[['ENGINESIZE','CYLINDERS','FUELCONSUMPTION_COMB']])\ny = np.asanyarray(test[['CO2EMISSIONS']])\nprint(\"Residual sum of squares: %.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))", 396 | "metadata": { 397 | "button": false, 398 | "new_sheet": false, 399 | "run_control": { 400 | "read_only": false 401 | }, 402 | "trusted": true 403 | }, 404 | "execution_count": null, 405 | "outputs": [] 406 | }, 407 | { 408 | "cell_type": "markdown", 409 | "source": [ 410 | "**Explained variance regression score:**\\\n", 411 | "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", 412 | "\n", 413 | "$\\texttt{explainedVariance}(y, \\hat{y}) = 1 - \\frac{Var{ y - \\hat{y}}}{Var{y}}$\\\n", 414 | "The best possible score is 1.0, the lower values are worse.\n" 415 | ], 416 | "metadata": {} 417 | }, 418 | { 419 | "cell_type": "markdown", 420 | "source": [ 421 | "

Practice

\n", 422 | "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" 423 | ], 424 | "metadata": {} 425 | }, 426 | { 427 | "cell_type": "code", 428 | "source": "# write your code here\n\n", 429 | "metadata": { 430 | "trusted": true 431 | }, 432 | "execution_count": null, 433 | "outputs": [] 434 | }, 435 | { 436 | "cell_type": "markdown", 437 | "source": [ 438 | "
Click here for the solution\n", 439 | "\n", 440 | "```python\n", 441 | "regr = linear_model.LinearRegression()\n", 442 | "x = np.asanyarray(train[['ENGINESIZE','CYLINDERS','FUELCONSUMPTION_CITY','FUELCONSUMPTION_HWY']])\n", 443 | "y = np.asanyarray(train[['CO2EMISSIONS']])\n", 444 | "regr.fit (x, y)\n", 445 | "print ('Coefficients: ', regr.coef_)\n", 446 | "y_= regr.predict(test[['ENGINESIZE','CYLINDERS','FUELCONSUMPTION_CITY','FUELCONSUMPTION_HWY']])\n", 447 | "x = np.asanyarray(test[['ENGINESIZE','CYLINDERS','FUELCONSUMPTION_CITY','FUELCONSUMPTION_HWY']])\n", 448 | "y = np.asanyarray(test[['CO2EMISSIONS']])\n", 449 | "print(\"Residual sum of squares: %.2f\"% np.mean((y_ - y) ** 2))\n", 450 | "print('Variance score: %.2f' % regr.score(x, y))\n", 451 | "\n", 452 | "```\n", 453 | "\n", 454 | "
\n" 455 | ], 456 | "metadata": {} 457 | }, 458 | { 459 | "cell_type": "markdown", 460 | "source": [ 461 | "

Want to learn more?

\n", 462 | "\n", 463 | "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", 464 | "\n", 465 | "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" 466 | ], 467 | "metadata": { 468 | "button": false, 469 | "new_sheet": false, 470 | "run_control": { 471 | "read_only": false 472 | } 473 | } 474 | }, 475 | { 476 | "cell_type": "markdown", 477 | "source": [ 478 | "### Thank you for completing this lab!\n", 479 | "\n", 480 | "## Author\n", 481 | "\n", 482 | "Saeed Aghabozorgi\n", 483 | "\n", 484 | "### Other Contributors\n", 485 | "\n", 486 | "Joseph Santarcangelo\n", 487 | "\n", 488 | "## Change Log\n", 489 | "\n", 490 | "| Date (YYYY-MM-DD) | Version | Changed By | Change Description |\n", 491 | "| ----------------- | ------- | ---------- | ---------------------------------- |\n", 492 | "| 2020-11-03 | 2.1 | Lakshmi | Made changes in URL |\n", 493 | "| 2020-08-27 | 2.0 | Lavanya | Moved lab to course repo in GitLab |\n", 494 | "| | | | |\n", 495 | "| | | | |\n", 496 | "\n", 497 | "##

© IBM Corporation 2020. All rights reserved.

\n" 498 | ], 499 | "metadata": {} 500 | } 501 | ] 502 | } -------------------------------------------------------------------------------- /Regression/Module 2_ML0101EN-Reg-Simple-Linear-Regression-Co2.jupyterlite.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "metadata": { 3 | "kernelspec": { 4 | "display_name": "Pyolite", 5 | "language": "python", 6 | "name": "python" 7 | }, 8 | "language_info": { 9 | "codemirror_mode": { 10 | "name": "python", 11 | "version": 3 12 | }, 13 | "file_extension": ".py", 14 | "mimetype": "text/x-python", 15 | "name": "python", 16 | "nbconvert_exporter": "python", 17 | "pygments_lexer": "ipython3", 18 | "version": "3.8" 19 | }, 20 | "widgets": { 21 | "state": {}, 22 | "version": "1.1.2" 23 | } 24 | }, 25 | "nbformat_minor": 4, 26 | "nbformat": 4, 27 | "cells": [ 28 | { 29 | "cell_type": "markdown", 30 | "source": "

\n \n \"Skills\n \n

\n\n# Simple Linear Regression\n\nEstimated time needed: **15** minutes\n\n## Objectives\n\nAfter completing this lab you will be able to:\n\n* Use scikit-learn to implement simple Linear Regression\n* Create a model, train it, test it and use the model\n", 31 | "metadata": { 32 | "button": false, 33 | "new_sheet": false, 34 | "run_control": { 35 | "read_only": false 36 | } 37 | } 38 | }, 39 | { 40 | "cell_type": "markdown", 41 | "source": "### Importing Needed packages\n", 42 | "metadata": { 43 | "button": false, 44 | "new_sheet": false, 45 | "run_control": { 46 | "read_only": false 47 | } 48 | } 49 | }, 50 | { 51 | "cell_type": "code", 52 | "source": "import piplite\nawait piplite.install(['pandas'])\nawait piplite.install(['matplotlib'])\nawait piplite.install(['numpy'])\nawait piplite.install(['scikit-learn'])\n\n", 53 | "metadata": { 54 | "trusted": true 55 | }, 56 | "execution_count": null, 57 | "outputs": [] 58 | }, 59 | { 60 | "cell_type": "code", 61 | "source": "import matplotlib.pyplot as plt\nimport pandas as pd\nimport pylab as pl\nimport numpy as np\n%matplotlib inline", 62 | "metadata": { 63 | "button": false, 64 | "new_sheet": false, 65 | "run_control": { 66 | "read_only": false 67 | }, 68 | "trusted": true 69 | }, 70 | "execution_count": null, 71 | "outputs": [] 72 | }, 73 | { 74 | "cell_type": "markdown", 75 | "source": "### Downloading Data\n\nTo download the data, we will use !wget to download it from IBM Object Storage.\n", 76 | "metadata": { 77 | "button": false, 78 | "new_sheet": false, 79 | "run_control": { 80 | "read_only": false 81 | } 82 | } 83 | }, 84 | { 85 | "cell_type": "code", 86 | "source": "path= \"https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-ML0101EN-SkillsNetwork/labs/Module%202/data/FuelConsumptionCo2.csv\"", 87 | "metadata": { 88 | "button": false, 89 | "new_sheet": false, 90 | "run_control": { 91 | "read_only": false 92 | }, 93 | "trusted": true 94 | }, 95 | "execution_count": null, 96 | "outputs": [] 97 | }, 98 | { 99 | "cell_type": "code", 100 | "source": "from pyodide.http import pyfetch\n\nasync def download(url, filename):\n response = await pyfetch(url)\n if response.status == 200:\n with open(filename, \"wb\") as f:\n f.write(await response.bytes())\n\n", 101 | "metadata": { 102 | "trusted": true 103 | }, 104 | "execution_count": null, 105 | "outputs": [] 106 | }, 107 | { 108 | "cell_type": "markdown", 109 | "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)\n", 110 | "metadata": {} 111 | }, 112 | { 113 | "cell_type": "markdown", 114 | "source": "## Understanding the Data\n\n### `FuelConsumption.csv`:\n\nWe 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?utm_medium=Exinfluencer&utm_source=Exinfluencer&utm_content=000026UJ&utm_term=10006555&utm_id=NA-SkillsNetwork-Channel-SkillsNetworkCoursesIBMDeveloperSkillsNetworkML0101ENSkillsNetwork20718538-2022-01-01)\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", 115 | "metadata": { 116 | "button": false, 117 | "new_sheet": false, 118 | "run_control": { 119 | "read_only": false 120 | } 121 | } 122 | }, 123 | { 124 | "cell_type": "markdown", 125 | "source": "## Reading the data in\n", 126 | "metadata": { 127 | "button": false, 128 | "new_sheet": false, 129 | "run_control": { 130 | "read_only": false 131 | } 132 | } 133 | }, 134 | { 135 | "cell_type": "code", 136 | "source": "", 137 | "metadata": {}, 138 | "execution_count": null, 139 | "outputs": [] 140 | }, 141 | { 142 | "cell_type": "code", 143 | "source": "await download(path, \"FuelConsumption.csv\")\npath=\"FuelConsumption.csv\"", 144 | "metadata": { 145 | "trusted": true 146 | }, 147 | "execution_count": null, 148 | "outputs": [] 149 | }, 150 | { 151 | "cell_type": "code", 152 | "source": "df = pd.read_csv(\"FuelConsumption.csv\")\n\n# take a look at the dataset\ndf.head()\n\n", 153 | "metadata": { 154 | "button": false, 155 | "new_sheet": false, 156 | "run_control": { 157 | "read_only": false 158 | }, 159 | "trusted": true 160 | }, 161 | "execution_count": null, 162 | "outputs": [] 163 | }, 164 | { 165 | "cell_type": "markdown", 166 | "source": "### Data Exploration\n\nLet's first have a descriptive exploration on our data.\n", 167 | "metadata": { 168 | "button": false, 169 | "new_sheet": false, 170 | "run_control": { 171 | "read_only": false 172 | } 173 | } 174 | }, 175 | { 176 | "cell_type": "code", 177 | "source": "# summarize the data\ndf.describe()", 178 | "metadata": { 179 | "button": false, 180 | "new_sheet": false, 181 | "run_control": { 182 | "read_only": false 183 | }, 184 | "trusted": true 185 | }, 186 | "execution_count": null, 187 | "outputs": [] 188 | }, 189 | { 190 | "cell_type": "markdown", 191 | "source": "Let's select some features to explore more.\n", 192 | "metadata": {} 193 | }, 194 | { 195 | "cell_type": "code", 196 | "source": "cdf = df[['ENGINESIZE','CYLINDERS','FUELCONSUMPTION_COMB','CO2EMISSIONS']]\ncdf.head(9)", 197 | "metadata": { 198 | "button": false, 199 | "new_sheet": false, 200 | "run_control": { 201 | "read_only": false 202 | }, 203 | "trusted": true 204 | }, 205 | "execution_count": null, 206 | "outputs": [] 207 | }, 208 | { 209 | "cell_type": "markdown", 210 | "source": "We can plot each of these features:\n", 211 | "metadata": {} 212 | }, 213 | { 214 | "cell_type": "code", 215 | "source": "viz = cdf[['CYLINDERS','ENGINESIZE','CO2EMISSIONS','FUELCONSUMPTION_COMB']]\nviz.hist()\nplt.show()", 216 | "metadata": { 217 | "button": false, 218 | "new_sheet": false, 219 | "run_control": { 220 | "read_only": false 221 | }, 222 | "trusted": true 223 | }, 224 | "execution_count": null, 225 | "outputs": [] 226 | }, 227 | { 228 | "cell_type": "markdown", 229 | "source": "Now, let's plot each of these features against the Emission, to see how linear their relationship is:\n", 230 | "metadata": {} 231 | }, 232 | { 233 | "cell_type": "code", 234 | "source": "plt.scatter(cdf.FUELCONSUMPTION_COMB, cdf.CO2EMISSIONS, color='blue')\nplt.xlabel(\"FUELCONSUMPTION_COMB\")\nplt.ylabel(\"Emission\")\nplt.show()", 235 | "metadata": { 236 | "button": false, 237 | "new_sheet": false, 238 | "run_control": { 239 | "read_only": false 240 | }, 241 | "trusted": true 242 | }, 243 | "execution_count": null, 244 | "outputs": [] 245 | }, 246 | { 247 | "cell_type": "code", 248 | "source": "plt.scatter(cdf.ENGINESIZE, cdf.CO2EMISSIONS, color='blue')\nplt.xlabel(\"Engine size\")\nplt.ylabel(\"Emission\")\nplt.show()", 249 | "metadata": { 250 | "button": false, 251 | "new_sheet": false, 252 | "run_control": { 253 | "read_only": false 254 | }, 255 | "scrolled": true, 256 | "trusted": true 257 | }, 258 | "execution_count": null, 259 | "outputs": [] 260 | }, 261 | { 262 | "cell_type": "markdown", 263 | "source": "## Practice\n\nPlot **CYLINDER** vs the Emission, to see how linear is their relationship is:\n", 264 | "metadata": {} 265 | }, 266 | { 267 | "cell_type": "code", 268 | "source": "# write your code here\n\n\n", 269 | "metadata": { 270 | "button": false, 271 | "new_sheet": false, 272 | "run_control": { 273 | "read_only": false 274 | }, 275 | "trusted": true 276 | }, 277 | "execution_count": null, 278 | "outputs": [] 279 | }, 280 | { 281 | "cell_type": "markdown", 282 | "source": "
Click here for the solution\n\n```python\nplt.scatter(cdf.CYLINDERS, cdf.CO2EMISSIONS, color='blue')\nplt.xlabel(\"Cylinders\")\nplt.ylabel(\"Emission\")\nplt.show()\n\n```\n\n
\n", 283 | "metadata": {} 284 | }, 285 | { 286 | "cell_type": "markdown", 287 | "source": "#### Creating train and test dataset\n\nTrain/Test Split involves splitting the dataset into training and testing sets that are mutually exclusive. After which, you train with the training set and test with the testing set.\nThis 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\nThis means that 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\nLet's split our dataset into train and test sets. 80% of the entire dataset will be used for training and 20% for testing. We create a mask to select random rows using **np.random.rand()** function:\n", 288 | "metadata": { 289 | "button": false, 290 | "new_sheet": false, 291 | "run_control": { 292 | "read_only": false 293 | } 294 | } 295 | }, 296 | { 297 | "cell_type": "code", 298 | "source": "msk = np.random.rand(len(df)) < 0.8\ntrain = cdf[msk]\ntest = cdf[~msk]", 299 | "metadata": { 300 | "button": false, 301 | "new_sheet": false, 302 | "run_control": { 303 | "read_only": false 304 | }, 305 | "trusted": true 306 | }, 307 | "execution_count": null, 308 | "outputs": [] 309 | }, 310 | { 311 | "cell_type": "markdown", 312 | "source": "### Simple Regression Model\n\nLinear Regression fits a linear model with coefficients B = (B1, ..., Bn) to minimize the 'residual sum of squares' between the actual value y in the dataset, and the predicted value yhat using linear approximation.\n", 313 | "metadata": { 314 | "button": false, 315 | "new_sheet": false, 316 | "run_control": { 317 | "read_only": false 318 | } 319 | } 320 | }, 321 | { 322 | "cell_type": "markdown", 323 | "source": "#### Train data distribution\n", 324 | "metadata": { 325 | "button": false, 326 | "new_sheet": false, 327 | "run_control": { 328 | "read_only": false 329 | } 330 | } 331 | }, 332 | { 333 | "cell_type": "code", 334 | "source": "plt.scatter(train.ENGINESIZE, train.CO2EMISSIONS, color='blue')\nplt.xlabel(\"Engine size\")\nplt.ylabel(\"Emission\")\nplt.show()", 335 | "metadata": { 336 | "button": false, 337 | "new_sheet": false, 338 | "run_control": { 339 | "read_only": false 340 | }, 341 | "trusted": true 342 | }, 343 | "execution_count": null, 344 | "outputs": [] 345 | }, 346 | { 347 | "cell_type": "markdown", 348 | "source": "#### Modeling\n\nUsing sklearn package to model data.\n", 349 | "metadata": { 350 | "button": false, 351 | "new_sheet": false, 352 | "run_control": { 353 | "read_only": false 354 | } 355 | } 356 | }, 357 | { 358 | "cell_type": "code", 359 | "source": "from sklearn import linear_model\nregr = linear_model.LinearRegression()\ntrain_x = np.asanyarray(train[['ENGINESIZE']])\ntrain_y = np.asanyarray(train[['CO2EMISSIONS']])\nregr.fit(train_x, train_y)\n# The coefficients\nprint ('Coefficients: ', regr.coef_)\nprint ('Intercept: ',regr.intercept_)", 360 | "metadata": { 361 | "button": false, 362 | "new_sheet": false, 363 | "run_control": { 364 | "read_only": false 365 | }, 366 | "trusted": true 367 | }, 368 | "execution_count": null, 369 | "outputs": [] 370 | }, 371 | { 372 | "cell_type": "markdown", 373 | "source": "As mentioned before, **Coefficient** and **Intercept** in the simple linear regression, are the parameters of the fit line.\nGiven 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.\nNotice that all of the data must be available to traverse and calculate the parameters.\n", 374 | "metadata": {} 375 | }, 376 | { 377 | "cell_type": "markdown", 378 | "source": "#### Plot outputs\n", 379 | "metadata": { 380 | "button": false, 381 | "new_sheet": false, 382 | "run_control": { 383 | "read_only": false 384 | } 385 | } 386 | }, 387 | { 388 | "cell_type": "markdown", 389 | "source": "We can plot the fit line over the data:\n", 390 | "metadata": {} 391 | }, 392 | { 393 | "cell_type": "code", 394 | "source": "plt.scatter(train.ENGINESIZE, train.CO2EMISSIONS, color='blue')\nplt.plot(train_x, regr.coef_[0][0]*train_x + regr.intercept_[0], '-r')\nplt.xlabel(\"Engine size\")\nplt.ylabel(\"Emission\")", 395 | "metadata": { 396 | "button": false, 397 | "new_sheet": false, 398 | "run_control": { 399 | "read_only": false 400 | }, 401 | "trusted": true 402 | }, 403 | "execution_count": null, 404 | "outputs": [] 405 | }, 406 | { 407 | "cell_type": "markdown", 408 | "source": "#### Evaluation\n\nWe 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\nThere are different model evaluation metrics, lets use MSE here to calculate the accuracy of our model based on the test set:\n\n* 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.\n\n* 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.\n\n* Root Mean Squared Error (RMSE).\n\n* R-squared is not an error, but rather a popular metric to measure the performance of your regression model. It represents how close the data points are to the fitted regression line. The higher the R-squared value, the better the model fits your data. The best possible score is 1.0 and it can be negative (because the model can be arbitrarily worse).\n", 409 | "metadata": { 410 | "button": false, 411 | "new_sheet": false, 412 | "run_control": { 413 | "read_only": false 414 | } 415 | } 416 | }, 417 | { 418 | "cell_type": "code", 419 | "source": "from sklearn.metrics import r2_score\n\ntest_x = np.asanyarray(test[['ENGINESIZE']])\ntest_y = np.asanyarray(test[['CO2EMISSIONS']])\ntest_y_ = regr.predict(test_x)\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_) )", 420 | "metadata": { 421 | "button": false, 422 | "new_sheet": false, 423 | "run_control": { 424 | "read_only": false 425 | }, 426 | "scrolled": true, 427 | "trusted": true 428 | }, 429 | "execution_count": null, 430 | "outputs": [] 431 | }, 432 | { 433 | "cell_type": "markdown", 434 | "source": "## Exercise\n", 435 | "metadata": {} 436 | }, 437 | { 438 | "cell_type": "markdown", 439 | "source": "Lets see what the evaluation metrics are if we trained a regression model using the `FUELCONSUMPTION_COMB` feature.\n\nStart by selecting `FUELCONSUMPTION_COMB` as the train_x data from the `train` dataframe, then select `FUELCONSUMPTION_COMB` as the test_x data from the `test` dataframe\n", 440 | "metadata": {} 441 | }, 442 | { 443 | "cell_type": "code", 444 | "source": "train_x = #ADD CODE\n\ntest_x = #ADD CODE\n\n", 445 | "metadata": { 446 | "trusted": true 447 | }, 448 | "execution_count": null, 449 | "outputs": [] 450 | }, 451 | { 452 | "cell_type": "markdown", 453 | "source": "
Click here for the solution\n\n```python\ntrain_x = train[[\"FUELCONSUMPTION_COMB\"]]\n\ntest_x = test[[\"FUELCONSUMPTION_COMB\"]]\n\n```\n\n
\n", 454 | "metadata": {} 455 | }, 456 | { 457 | "cell_type": "markdown", 458 | "source": "Now train a Linear Regression Model using the `train_x` you created and the `train_y` created previously\n", 459 | "metadata": {} 460 | }, 461 | { 462 | "cell_type": "code", 463 | "source": "regr = linear_model.LinearRegression()\n\n#ADD CODE\n", 464 | "metadata": { 465 | "trusted": true 466 | }, 467 | "execution_count": null, 468 | "outputs": [] 469 | }, 470 | { 471 | "cell_type": "markdown", 472 | "source": "
Click here for the solution\n\n```python\nregr = linear_model.LinearRegression()\n\nregr.fit(train_x, train_y)\n\n```\n\n
\n", 473 | "metadata": {} 474 | }, 475 | { 476 | "cell_type": "markdown", 477 | "source": "Find the predictions using the model's `predict` function and the `test_x` data\n", 478 | "metadata": {} 479 | }, 480 | { 481 | "cell_type": "code", 482 | "source": "predictions = #ADD CODE", 483 | "metadata": {}, 484 | "execution_count": null, 485 | "outputs": [] 486 | }, 487 | { 488 | "cell_type": "markdown", 489 | "source": "
Click here for the solution\n\n```python\npredictions = regr.predict(test_x)\n\n```\n\n
\n", 490 | "metadata": {} 491 | }, 492 | { 493 | "cell_type": "markdown", 494 | "source": "Finally use the `predictions` and the `test_y` data and find the Mean Absolute Error value using the `np.absolute` and `np.mean` function like done previously\n", 495 | "metadata": {} 496 | }, 497 | { 498 | "cell_type": "code", 499 | "source": "#ADD CODE\n", 500 | "metadata": {}, 501 | "execution_count": null, 502 | "outputs": [] 503 | }, 504 | { 505 | "cell_type": "markdown", 506 | "source": "
Click here for the solution\n\n```python\nprint(\"Mean Absolute Error: %.2f\" % np.mean(np.absolute(predictions - test_y)))\n\n```\n\n
\n", 507 | "metadata": {} 508 | }, 509 | { 510 | "cell_type": "markdown", 511 | "source": "We can see that the MAE is much worse when we train using `ENGINESIZE` than `FUELCONSUMPTION_COMB`.\n", 512 | "metadata": {} 513 | }, 514 | { 515 | "cell_type": "markdown", 516 | "source": "

Want to learn more?

\n\nIBM 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\nAlso, 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", 517 | "metadata": { 518 | "button": false, 519 | "new_sheet": false, 520 | "run_control": { 521 | "read_only": false 522 | } 523 | } 524 | }, 525 | { 526 | "cell_type": "markdown", 527 | "source": "### Thank you for completing this lab!\n\n## Author\n\nSaeed Aghabozorgi\n\n### Other Contributors\n\nJoseph Santarcangelo\n\nAzim Hirjani\n\n## Change Log\n\n| Date (YYYY-MM-DD) | Version | Changed By | Change Description |\n| ----------------- | ------- | ------------- | ---------------------------------- |\n| 2020-11-03 | 2.1 | Lakshmi Holla | Changed URL of the csv |\n| 2020-08-27 | 2.0 | Lavanya | Moved lab to course repo in GitLab |\n| | | | |\n| | | | |\n\n##

© IBM Corporation 2020. All rights reserved.

\n", 528 | "metadata": {} 529 | } 530 | ] 531 | } --------------------------------------------------------------------------------