×

How to implement classifiers in Python

What is classification?

Classification is a type of supervised machine learning problem with a categorical target (response) variable. Given the known label in the training data, the classifier approximates a mapping function (f) from the input variables (X) to the output variables (Y) (Y).

Import Libraries and Load Dataset

To begin, we must import the following libraries: pandas (for dataset loading), numpy (for matrix manipulation), matplotlib and seaborn (for visualisation), and sklearn (for machine learning) (building classifiers). Before importing them, make sure they are already installed. To import the libraries and load the dataset, use the following code:

import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from pandas.plotting import parallel_coordinates
from sklearn.tree import DecisionTreeClassifier, plot_tree
from sklearn import metrics
from sklearn.naive_bayes import GaussianNB
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis, QuadraticDiscriminantAnalysis
from sklearn.neighbors import KNeighborsClassifier
from sklearn.svm import SVC
from sklearn.linear_model import LogisticRegression

To load the dataset, we can use the read_csv function from pandas (my code also includes the option of loading through URL).

data = pd.read_csv('data.csv')

After we load the data, we can take a look at the first couple of rows through the head function:

data.head(5)

Train-Test Split

We can now divide the dataset into two parts: training and testing. In general, we should have a validation set that is used to evaluate the performance of each classifier and fine-tune the model parameters in order to find the best model. The test set is primarily used for reporting. However, because this dataset is small, we can simplify the process by using the test set to serve the purpose of the validation set.

In addition, to estimate model accuracy, I used a stratified hold-out approach. Cross-validation is another method for reducing bias and variances.

train, test = train_test_split(data, test_size = 0.4, stratify = data[‘species’], random_state = 42)

Exploratory Data Analysis

We can now proceed to explore the training data after we have split the dataset. Matplotlib and Seaborn both have excellent plotting tools that we can use for visualisation.

Let's start by making some univariate plots with a histogram for each feature:

n_bins = 10
fig, axs = plt.subplots(2, 2)
axs[0,0].hist(train['sepal_length'], bins = n_bins);
axs[0,0].set_title('Sepal Length');
axs[0,1].hist(train['sepal_width'], bins = n_bins);
axs[0,1].set_title('Sepal Width');
axs[1,0].hist(train['petal_length'], bins = n_bins);
axs[1,0].set_title('Petal Length');
axs[1,1].hist(train['petal_width'], bins = n_bins);
axs[1,1].set_title('Petal Width');
# add some spacing between subplots
fig.tight_layout(pad=1.0);

It's worth noting that for both petal length and petal width, there appears to be a group of data points with lower values than the others, implying that there could be different groups in this data.

Let's try some side-by-side box plots next:

fig, axs = plt.subplots(2, 2)
fn = ["sepal_length", "sepal_width", "petal_length", "petal_width"]
cn = ['setosa', 'versicolor', 'virginica']
sns.boxplot(x = 'species', y = 'sepal_length', data = train, order = cn, ax = axs[0,0]);
sns.boxplot(x = 'species', y = 'sepal_width', data = train, order = cn, ax = axs[0,1]);
sns.boxplot(x = 'species', y = 'petal_length', data = train, order = cn, ax = axs[1,0]);
sns.boxplot(x = 'species', y = 'petal_width', data = train,  order = cn, ax = axs[1,1]);
# add some spacing between subplots
fig.tight_layout(pad=1.0);

The two plots at the bottom imply that the setosas we saw earlier are setosas. Their petal measurements are smaller and more evenly distributed than those of the other two species. When compared to the other two species, versicolor has lower average values than virginica.

Another type of visualisation is the violin plot, which combines the advantages of both the histogram and the box plot:

sns.violinplot(x="species", y="petal_length", data=train, size=5, order = cn, palette = 'colorblind');

Gaussian Naive Bayes Classifier

Naive Bayes is a popular classification model. It contains the word "Naive" because it contains a key assumption of class-conditional independence, which means that given the class, each feature's value is assumed to be independent of any other feature's value (read more here).

We know that this is not the case here, as evidenced by the high correlation between the petal features. Let's look at the test accuracy using this model to see if this assumption is sound:

The accuracy of the Guassian Naive Bayes Classifier on test data is 0.933

What about the result if we only use the petal features:

The accuracy of the Guassian Naive Bayes Classifier with 2 predictors on test data is 0.950

Interestingly, using only two features results in more correctly classified points, implying that using all features may result in over-fitting. Our Naive Bayes classifier appears to have done a good job.

Linear Discriminant Analysis (LDA)

If we calculate the class conditional density using a multivariate Gaussian distribution rather than a product of univariate Gaussian distributions (as in Naive Bayes), we get an LDA model (read more here). The key assumption of LDA is that covariances between classes are equal. We can examine the test accuracy using both all and only petal features:

The accuracy of the LDA Classifier on test data is 0.983
The accuracy of the LDA Classifier with two predictors on test data is 0.933

The use of all features improves the test accuracy of our LDA model.

We can use our LDA model with only petals and plot the test data to visualise the decision boundary in 2D:

Three virginica and one versicolor test points are misclassified.


Related Topics

Python Unit Test Cheat String

Python: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

3 minutes read.

How to Install Scikit-Learn

Sklearn or Scikit-learn is a python library used for machine learning. It contains many features like classification, regression, clustering, and Dimensionality reduction algorithms. Sklearn is used to build machine learning...

3 minutes read.

Python email utils

Python is a popular programming language in this growing world. There are many resources to learn python online without spending a single penny. In this article, we will talk about a...

4 minutes read.

Anonymous/Lambda Function in Python

Lambda keyword is used to declare an Anonymous function, i.e. a function that does not have any name. It is also called Anonymous functions. In python, normal functions are defined...

3 minutes read.

Python Seaborn

Seaborn is an open-source library in Python that is used for data visualization and plotting graphs. The plots are used for the Visualization of data. It is built on top...

10 minutes read.

Python program to print array element present at even position

Python program to print array element present at even position In this program, we'll see a Python program that prints the elements of an array that are in even positions. We...

1 minute read.

Operator Module In Python

Introduction The operator module is used for performing operations using methods rather than utilizing operators in Python code. The operator module provides several methods for performing the operations.  The operator module contains...

7 minutes read.

Python SQLite

SQLite It is an RDBMS (Relational Database Management System). It is an embedded, serverless, transactional SQL database engine. It is an open-source application. It is named SQLite because of its lightweight....

3 minutes read.

Colors in Python

Adding colour to your visualisations will help them come to life. Even if you know the colours you want to use, picking good ones and putting them into practise might...

4 minutes read.

Python data science course

What is meant by Data Science? When processing raw, structured, and unstructured data utilizing various technologies, algorithms, and the scientific method, data science is a detailed study of the enormous quantity...

4 minutes read.

Python Basics

In this tutorial, we will learn about the basics of Python, a very famous programming language. This tutorial will help you understand the language better if you start with python....

8 minutes read.

Python program to find the area of the triangle

Python program to find the area of the triangle This article will discuss how to find the area of a triangle in Python with all three given sides. The area of...

2 minutes read.

Find Median of List in Python

The median is an enlightening measurement that is utilized as a proportion of the focal inclination of a circulation. It is equivalent to the centre worth of the conveyance. There...

3 minutes read.

Python md5_file() function

Python md5_file() function The md5_file() function in PHP calculates the md5 hash of a given file. Syntax md5_file ( string $filename [, bool $raw_output ] )  Parameter filename(required)- This parameter signifies the file to be calculated. raw_output(optional)- It takes a boolean value that specifies hex or binary...

1 minute read.

Static Variables in Python

What is a Static Variable? The variable that remains with a constant value throughout the program or throughout the class is known as a " Static Variable ". Static variables are...

3 minutes read.

How to Import Files in Python

Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

3 minutes read.

Python IDE

What is an IDE?  An IDE or an Integrated Development Environment is a type of software where developers can develop many software’s and applications and run the programs inside it. An...

11 minutes read.

Python Arithmetic Operators

An arithmetic operator is a mathematical operator that is used to operate on two operands. Based on the operator used, action is performed on the operands, and output is delivered. Following...

3 minutes read.

Python Stack

Python Stack: The work Stack is defined as arranging a pile of objects or items on top of another. It is the same method of allocating memory in the stack...

10 minutes read.

How to run a Program in Python

How to run a Program in Python Writing a program in Python is an easy task, beginners who are ready to kickstart their career in the world of programming can create...

3 minutes read.