Uncategorized

25:Machine Learning

Machine Learning

Artificial Intelligence (AI) is the most used buzz word nowadays. AI is the process of getting decisions from computers rather than humans and AI generates these decisions on the basis of Machine Learning (ML). Machine learning performs only two kinds of operations, Classification and Prediction. In this lecture we will understand how we can use built-in machine learning functions in Python libraries to perform these two operations.

Classification

  1. In classification we assign a label on a data instance.
  2. For example, we have a leaf of an unknown tree and want to identify it.
  3. There some features on the leaf like, height, width, roundness, color, veins pattern and some other information help us to recognize it.
  4. To properly recognize a leaf we must have knowledge of trees and plants. As we have knowledge about it, we are more able to recognize it correctly.
  5. For instance, we have only knowledge of 10 plants and after analyzing the leaf we will label it as nearest.
  6. It might be possible that the leaf doesn’t belong to our labeled type but it is correct to the best of our knowledge.
  7. Another example, a Facebook user is scrolling.
  8. For Facebook’s advertisement algorithm, he is just a customer.
  9. The advertisement algorithm has to make a decision that a particular ad should appear in front of this user or not because when the algorithm decides to show an ad a large bunch of data will move from server to client and the transportation cost will be paid by Facebook.
  10. Facebook algorithm must be very intelligent to select the target customer because Facebook has billions of users.
  11. If the user is interested in motor bikes, then he must be a potential customer of some motor bike related product such as light, stand or other things.
  12. Now Facebook algorithm classifies its user in two classes, one is potential customer and other is not a potential customer.
  13. Similarly, a brain tumor detection system can identify malignant cells from a CT scan, a vehicle monitor can read the number plate of cars and other examples.
  14. Consider that classification is a high level of analytics so all steps which are involved in data analytics must perform initially.
  15. Following steps are involved in a real time machine learning project.
  16. Acquiring Dataset.
  17. Understanding the Dataset.
  18. Preprocessing.
  19. Cleaning.
  20. Selection of a Machine Learning Algorithm called Classifier.
  21. Splitting Dataset.
  22. Training.
  23. Validation Metrics.
  24. Tuning.
  25. Deployment.
  26. We have an example here that helps us to understand the whole process. The last two steps, tuning and deployment will not study here.
  27. Acquiring: For this time, we use an example dataset Iris. Iris is easily available on multiple websites and requires no licensing on it.
  28. Iris is very popular, simple and easy for students to understand the concepts of machine learning.
  29. Understanding: The Iris dataset is about flowers and usage purpose is to identify the correct flower on the basis of given information of unknown flower.
  30. The dataset is available in multiple formats but we will use CSV.
  31. The CSV file contains a total of 5 columns, the first four are attributes and the last is called target class. This target class column name is “species”.
  32. Attribute columns are such columns which provide the information about object and class columns that we have to find.
  33. Following are attribute columns.
  34. Sepal Length
  35. Sepal Width
  36. Petal Length
  37. Petal Width
  38. Three classes are mentioned in the species column.
  39. Setosa
  40. Versicolor
  41. Virginica

Figure 1: CSV file of Iris Dataset in MS Excel

  1. All measurements are in centimeters.
  2. On the base attributes, we have to select which flower is which one of the classes.
  3. We have a total 150 records (rows) in the file.
  4. 50 rows of each class.
  5. Cleaning and Preprocessing: Fortunately, the dataset has no empty or invalid entries so, we don’t need to remove or hypothetically generate values in it.
  6. But we are required to manage string data because machine learning only works with numerical values. We convert strings into suitable numbers.
  7. For instance, we convert species names to index numbers.
  8. Classifier Selection: We have a large set of classifiers who are fit to work with Iris. Every classifier uses its own technique such as KNN which normally works on geometrical expressions, NaĂŻve Bayes, which is probability base and Neural Network that works on perceptron layers.
  9. Every classification algorithm has its own methodology, efficiency and performance metrics.
  10. Just for the example, we use NaĂŻve Bayes.
  11. We just use this algorithm and not go into the detailed working.
  12. Splitting: before deploying the algorithm for a dataset, we will first test this. The splitting process is the part of testing.
  13. We split the number of records in two sets.
  14. Training Set.
  15. Testing Set.
  16. As we know that a total 150 records are in our dataset (Iris) so we can divide it into 50%, 50% ratios. Half records (75) will be the part of the training set and the remaining half (75) will be in the testing set.
  17. This division ratio is not a standard; we can change it to our choice.
  18. Training: The term training means, the model will save the data of 75 records using NaĂŻve Bayes formula (or any other formula that is selected).
  19. The term testing means, after training, these records load one by one and the model will generate the class label for it.
  20. This class label will be matched in the actual dataset and find that either machine correctly labels the data or not.
  21. Validation Metrics: After training, we test the performance of algorithms. There are multiple measurements to validate.
  22. Accuracy: It is the percentage of correctness. We get it by given formula.

Equations 1: Formula for Accuracy

For example, if correctly labeled all 75 tested instances, then our accuracy will be 100%.

  1. Confusion Matrix: This is a table that maps how our model distributes the labeled instances in different classes.
  2. Recall: Accuracy is overall but recall is class wise. We can find it by following the formula.

  1. Precision: This is also class wise but this is the ratio between correct instances for a class by overall instances labeled by this class. In Iris we have three classes and for each class we have to evaluate the formula.

F1 Score: This is harmonic mean of the recall and precision

  1. Now we write the code, run it and examine the results on validation metrics.
  2. For machine learning functions we must have installed the scikit-learn library.
pip install scikit-learn

Code 1: Installing SciKit Library

  1. First, import the important libraries.
import pandas as pd from sklearn.model_selection import train_test_splitfrom sklearn.preprocessing import LabelEncoderfrom sklearn.naive_bayes import GaussianNBfrom sklearn.metrics import classification_report, confusion_matrix, accuracy_score

Code 2: Importing Libraries and Methods

  1. pandas will use to load CSV of dataset
  2. We also import functions from sklearn library
  3. train_test_split: This function to create training and test sets from a dataset.
  4. LabelEncoder: This sub-library helps to convert strings to numbers
  5. GussianNB: This the actual classifier library
  6. classification_report: It helps to generate validation metrics
  7. confusion_matrix: This is the part of validation metrics.
  8. accuracy_score: This is also part of validation metrics.
  9. We load the CSV by pandas as follows. I put the iris data in file “iris.data.csv” in iris directory.
df = pd.read_csv ("iris\\iris.data.csv")

Code 3: Loading CSV

  1. We know that machine learning only works on numeric data. Four attribute columns are already in number form but the last species column is string. it is required to convert in numeric.
  2. We simply assign a number to each specie. 0 for Setosa, 1 for Versicolor and 2 for Virginica.
if df['species'].dtype == 'object':    label_encoder = LabelEncoder ()    df['species'] = label_encoder.fit_transform (df['species'])

Code 4: Converting String values to Numeric

  1. Now it’s time to segregate the feature columns and target columns. First four columns are features, we create a sperate DataFrame that contains these features and the target class column “species” also go into some other DataFrame.
x = df.drop('species', axis=1)y = df['species']
  1. axis means drop the species column. If it changes to 0 then it removes the row.
  2. This step is important because our classifier will evaluate the classification expression on features and correlate it with species and this process is called learning.
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.5)

Code 6: Splitting Dataset into Training and Test Sets

  1. The train_test_split function has three arguments.
  2. x: This features DataFrame.
  3. y: Target class DataFrame.
  4. test_size: How much percentage of total dataset goes into the test. Here is 50%.
  5. This function will return four values.
  6. x_train: The features DataFrame goes into the training set.
  7. x_test: The features DataFrame goes into the testing set.
  8. y_train: The classes DataFrame go into training. It will correlate to x_train.
  9. y_test: The classes DataFrame go into testing.
  10. We will train the model on given data.
  11. It will be performed by GaussianNB object and its fit function. that will accept the train sets of features and target classes as parameters.
model = GaussianNB()model.fit (x_train, y_train)

Code 7: Training the model

  1. The model will train after the above code and we can test it on testing data.
  2. The model will train after the above code and we can test it on testing data.
y_pred = model.predict (x_test)

Code 8: Testing the Trained Model

  1. The y_pred variable contains all data about validation metrics.
  2. First, we find the accuracy of the model.
print ("\nAccuracy Score:")print (f"{accuracy_score(y_test, y_pred) * 100:.2f}%")
  1. The accuracy_score function will calculate the overall accuracy. It will perform some operations on y_pred with respect to y_test that contains the target class DataFrame.

Figure 2: Accuracy

  1. It means our testing set (75 instances) is almost correctly classified.
  2. How many instances are not correctly classified, can be determined by a confusion matrix.
print("\nConfusion Matrix:")print(confusion_matrix(y_test, y_pred))

Code 10: Printing Confusion Matrix

  1. The above code prints the following output.
  2. The output of the confusion matrix required some explanation.
  3. We have changed the species name to number 51.
  4. We have a total of three species and the output also shows a 3×3 matrix.
  5. The rows and columns both belong to these species.
  6. The index number of rows and columns represents the species.

Figure 3: Confusion Matrix

  1. More elaborated view of the confusion matrix be like

  1. The rows represent the tested instances and columns represent actual instances.
  2. We can see that for Setosa, blue box, there are 29 and all rows and columns of Setosa are empty.
  3. It means the system selected 29 instances of Setosa for testing; all 29 were correctly labeled as Setosa.
  4. Similarly, for Versicolor, all 23 instances are correctly labeled.
  5. 23 instances of Verginica were also tested but one instance marked as versicolor and 22 were correctly labeled.
  6. It means a total 74 were correct while 1 was wrong and system overall performance is 98.67%.
  7. These things are also reflected in remaining metrics (precision, recall and F1).

Figure 4: Precision, Recall and F1-Score of All three Classes

  1. Line 0 represents Setosa and support column represents number of instances.
  2. Precision is 1.00 (100%) because all 29 instances of Setosa were correctly labeled and consequently, recall and f1-score are also 100%.
  3. The recall of Versicolor (line number 1) is 100% but precision is 96% because one Verginica instance was incorrectly labeled as Versicolor.
  4. Precision of Verginica is 100% means all marked Verginica were actually Verginica but recall is 96% because 1 Verginica is labeled as Versicolor and it also affects F1.

Prediction

  1. In classification, we have to identify the class label for a testing instance but in prediction, we have to calculate a number.
  2. For example, we want to predict the price of stock next year. The price is a real number.
  3. All the steps in regression are quite similar to classification; only the validation metrics are different.
  4. We use the Advertisement dataset as an example here.
  5. This is a licensing free dataset and can be found in CSV format.
  6. Acquire: We search and download advertisement.csv.
  7. Understanding: The dataset has four columns. TV, Radio, Newspaper and Sales.
  8. The first three columns are features and the fourth is target value.
  9. This set belongs to an advertisement company who run the campaigns for an electronics manufacturing firm.
  10.  The advertisement campaigns target TV, radio and newspaper. A specific amount spent to run ads on these media.
  11. The amount and sales in thousands.
  12. For example, in the first row we found 230.1 in TV, 37.8 in radio, 69.2 in newspaper and 22.1 in sales.
  13. It means the company spent $230.1 thousands in TV ads, $37.8 thousands in radio ads and $69.2 thousands while it got 22.1 thousand units sold.
  14. Our aim is to find the estimated sales spent on different media.
  15. For example, if you spend $150K in TV, $20K in radio and $10K in newspapers then how much the company will get sales.
  16. After running the linear regression code, we will find 14.94 thousand units, just a simple number that can help us to estimate the sales.
  17. Cleaning and Preprocessing: As similar to Iris, this dataset is also a complete dataset with no missing or invalid entries and also a dataset completely in numeric form and no string categories in it to replace.
  18. We are still required to segregate the feature columns and target columns. We know that the first three columns are features and the fourth is the target class. We will put both in separate variables.
  19. Predictor Selection: Like classification, we have dozens of regression algorithms. For keeping the things simple, we select linear_model.
  20. Training: There is a small difference between classification and prediction. In prediction, we have no need to split data into training sets and testing sets.
  21. We use all data in the training set.
  22. For testing, we provide some random values.
  23. We also have performance metrics but that metrics is beyond the scope of this course.
import pandas as pdfrom sklearn.linear_model import LinearRegression df = pd.read_csv("advertising.csv")x = df[['TV', 'Radio', 'Newspaper']]y = df['Sales'] model = LinearRegression()model.fit(x, y)new_spend = [[150, 20, 10]]predicted_sales = model.predict(new_spend)print(f"Predicted Sales: {predicted_sales[0]:.2f} units")

Code 11: Simple Linear Regression to get Predictions

  1. First, we import the libraries for reading CSV and predict LinearRegression.
  2. Then read the CSV and create a DataFrame.
  3. Put the feature columns into x and target sales columns into y.
  4. Create a model of LinearRegression and fit it on x and y.
  5. new_spent is an example value and we want to calculate the prediction for this value.
  6. The predict function of the model will return the estimated value for sales which we print.

Leave a Reply

Your email address will not be published. Required fields are marked *