Multiclass Classification Tutorial

Installing PyCaret

The first step to get started with PyCaret is to install pycaret. Installation is easy and will only take a few minutes. Follow the instructions below:

Installing PyCaret in Local Jupyter Notebook

pip install pycaret

Installing PyCaret on Google Colab or Azure Notebooks

!pip install pycaret

Pre-Requisites

  • Python 3.6 or greater
  • PyCaret 2.0 or greater
  • Internet connection to load data from pycaret's repository
  • Basic Knowledge of Multiclass Classification

What is Multiclass Classification?

Multiclass classification is a supervised machine learning technique where the goal is to classify instances into one of three or more classes. (Classifying instances into one of two classes is called Binary Classification). Multiclass classification should not be confused with multi-label classification, where multiple labels are to be predicted for each instance.


Overview of the Classification Module in PyCaret

PyCaret's classification module (pycaret.classification) is a supervised machine learning module which is used for classifying the elements into binary or multinomial groups based on various techniques and algorithms.

The PyCaret classification module can be used for Binary or Multi-class classification problems. It has over 18 algorithms and 14 plots to analyze the performance of models. Be it hyper-parameter tuning, ensembling or advanced techniques like stacking, PyCaret's classification module has it all.


Dataset for the Tutorial

For this tutorial we will use the Iris Dataset from UCI. This is perhaps the best known database to be found in the pattern recognition literature. The data set contains 3 classes of 50 instances each, where each class refers to a type of iris plant. Short descriptions of each column are as follows:

  • sepal_length: Length of Sepal
  • sepal_width: Width of Sepal
  • petal_length: Length of Petal
  • petal_width: Width of Petal
  • species: One of three class (Setosa, Versicolour, Virginica) Target Column

Dataset Acknowledgement:

Creator: R.A. Fisher, Donor : Michael Marshall (MARSHALL%PLU '@' io.arc.nasa.gov)

The original dataset and data dictionary can be found here.

Getting the Data

You can download the data from the original source found here and load it using pandas (Learn How) or you can use PyCaret's data respository to load the data using the get_data() function (This will require an internet connection).

In [1]:
from pycaret.datasets import get_data
dataset = get_data('iris')
sepal_lengthsepal_widthpetal_lengthpetal_widthspecies
05.13.51.40.2Iris-setosa
14.93.01.40.2Iris-setosa
24.73.21.30.2Iris-setosa
34.63.11.50.2Iris-setosa
45.03.61.40.2Iris-setosa

Setting up the Environment in PyCaret

In later tutorials we will learn how to overwrite PyCaret's infered data type using the numeric_features and categorical_features parameters in setup().

In [4]:
from pycaret.classification import *
exp_mclf101 = setup(data = data, target = 'species', session_id=123) 
DescriptionValue
0session_id123
1Target TypeMulticlass
2Label EncodedIris-setosa: 0, Iris-versicolor: 1, Iris-virginica: 2
3Original Data(135, 5)
4Missing ValuesFalse
5Numeric Features4
6Categorical Features0
7Ordinal FeaturesFalse
8High Cardinality FeaturesFalse
9High Cardinality MethodNone
10Sampled Data(135, 5)
11Transformed Train Set(94, 4)
12Transformed Test Set(41, 4)
13Numeric Imputermean
14Categorical Imputerconstant
15NormalizeFalse
16Normalize MethodNone
17TransformationFalse
18Transformation MethodNone
19PCAFalse
20PCA MethodNone
21PCA ComponentsNone
22Ignore Low VarianceFalse
23Combine Rare LevelsFalse
24Rare Level ThresholdNone
25Numeric BinningFalse
26Remove OutliersFalse
27Outliers ThresholdNone
28Remove MulticollinearityFalse
29Multicollinearity ThresholdNone
30ClusteringFalse
31Clustering IterationNone
32Polynomial FeaturesFalse
33Polynomial DegreeNone
34Trignometry FeaturesFalse
35Polynomial ThresholdNone
36Group FeaturesFalse
37Feature SelectionFalse
38Features Selection ThresholdNone
39Feature InteractionFalse
40Feature RatioFalse
41Interaction ThresholdNone
42Fix ImbalanceFalse
43Fix Imbalance MethodSMOTE

 Comparing All Models

Comparing all models to evaluate performance is the recommended starting point for modeling once the setup is completed (unless you exactly know what kind of model you need, which is often not the case). This function trains all models in the model library and scores them using stratified cross validation for metric evaluation. The output prints a score grid that shows average Accuracy, Recall, Precision, F1, Kappa, and MCC accross the folds (10 by default) along with training times.

In [5]:
best = compare_models()
ModelAccuracyAUCRecallPrec.F1KappaMCCTT (Sec)
0Naive Bayes0.95670.00000.95560.96190.95610.93480.93780.0076
1K Neighbors Classifier0.94670.00000.94440.96330.94300.91970.92950.0077
2Extreme Gradient Boosting0.94670.00000.94440.96330.94300.91970.92950.0521
3Light Gradient Boosting Machine0.94670.00000.94440.96000.94510.91970.92710.0606
4Random Forest Classifier0.94560.00000.94440.95360.94460.91820.92270.2123
5Quadratic Discriminant Analysis0.94560.00000.94440.95360.94460.91820.92270.0071
6Extra Trees Classifier0.93560.00000.93330.94330.93370.90300.90820.3872
7CatBoost Classifier0.93560.00000.93330.94330.93370.90300.90822.1596
8Gradient Boosting Classifier0.93440.00000.93330.94530.93320.90150.90760.1215
9Logistic Regression0.92440.00000.92220.93450.92210.88610.89290.0213
10Ada Boost Classifier0.92440.00000.92220.93500.92230.88640.89310.1121
11Decision Tree Classifier0.92330.00000.92220.93420.92110.88480.89190.0082
12Linear Discriminant Analysis0.86110.00000.86670.85200.84820.79440.81300.0081
13Ridge Classifier0.82890.00000.83610.82510.81470.74610.76860.0098
14SVM - Linear Kernel0.72330.00000.72220.65200.65020.58840.64390.0093

Create a Model

create_model is the most granular function in PyCaret and is often the foundation behind most of the PyCaret functionalities. As the name suggests this function trains and evaluates a model using cross validation that can be set with fold parameter. The output prints a score grid that shows Accuracy, Recall, Precision, F1, Kappa and MCC by fold.

For the remaining part of this tutorial, we will work with the below models as our candidate models. The selections are for illustration purposes only and do not necessarily mean they are the top performing or ideal for this type of data.

  • Decision Tree Classifier ('dt')
  • K Neighbors Classifier ('knn')
  • Logistic Regression ('lr')

There are 18 classifiers available in the model library of PyCaret. Please view the create_model() docstring for the list of all available models.


Decision Tree Classifier

In [6]:
dt = create_model('dt')
AccuracyAUCRecallPrec.F1KappaMCC
01.00000.00001.00001.00001.00001.00001.0000
11.00000.00001.00001.00001.00001.00001.0000
21.00000.00001.00001.00001.00001.00001.0000
30.90000.00000.88890.92500.89710.84850.8616
40.88890.00000.88890.91670.88570.83330.8492
51.00000.00001.00001.00001.00001.00001.0000
60.88890.00000.88890.91670.88570.83330.8492
70.88890.00000.88890.91670.88570.83330.8492
81.00000.00001.00001.00001.00001.00001.0000
90.66670.00000.66670.66670.65710.50000.5095
Mean0.92330.00000.92220.93420.92110.88480.8919
SD0.09970.00000.10000.09710.10250.14960.1453

 Neighbors Classifier

In [8]:
knn = create_model('knn')
AccuracyAUCRecallPrec.F1KappaMCC
01.00000.00001.00001.00001.00001.00001.0000
11.00000.00001.00001.00001.00001.00001.0000
20.90000.00000.88890.92500.89710.84850.8616
30.90000.00000.88890.92500.89710.84850.8616
41.00000.00001.00001.00001.00001.00001.0000
51.00000.00001.00001.00001.00001.00001.0000
60.88890.00000.88890.91670.88570.83330.8492
71.00000.00001.00001.00001.00001.00001.0000
81.00000.00001.00001.00001.00001.00001.0000
90.77780.00000.77780.86670.75000.66670.7223
Mean0.94670.00000.94440.96330.94300.91970.9295
SD0.07300.00000.07450.04750.08010.10970.0940

Logistic Regression

lr = create_model('lr')
AccuracyAUCRecallPrec.F1KappaMCC
00.90000.00000.88890.92000.89560.84620.8598
11.00000.00001.00001.00001.00001.00001.0000
21.00000.00001.00001.00001.00001.00001.0000
30.90000.00000.88890.92500.89710.84850.8616
41.00000.00001.00001.00001.00001.00001.0000
51.00000.00001.00001.00001.00001.00001.0000
60.88890.00000.88890.91670.88570.83330.8492
70.66670.00000.66670.66670.65710.50000.5095
81.00000.00001.00001.00001.00001.00001.0000
90.88890.00000.88890.91670.88570.83330.8492
Mean0.92440.00000.92220.93450.92210.88610.8929
SD0.09940.00000.10000.09700.10220.14920.1450

Tune a Model

When a model is created using the create_model() function it uses the default hyperparameters to train the model. In order to tune hyperparameters, the tune_model() function is used. This function automatically tunes the hyperparameters of a model using Random Grid Search on a pre-defined search space. The output prints a score grid that shows Accuracy, AUC, Recall, Precision, F1, Kappa, and MCC by fold for the best model. To use the custom search grid, you can pass custom_grid parameter in the tune_model function (see 9.2 KNN tuning below).

Decision Tree Classifier

In [10]:
tuned_dt = tune_model(dt)
AccuracyAUCRecallPrec.F1KappaMCC
01.00000.00001.00001.00001.00001.00001.0000
11.00000.00001.00001.00001.00001.00001.0000
21.00000.00001.00001.00001.00001.00001.0000
30.90000.00000.88890.92500.89710.84850.8616
40.88890.00000.88890.91670.88570.83330.8492
51.00000.00001.00001.00001.00001.00001.0000
60.88890.00000.88890.91670.88570.83330.8492
70.88890.00000.88890.91670.88570.83330.8492
81.00000.00001.00001.00001.00001.00001.0000
90.77780.00000.77780.77780.77780.66670.6667
Mean0.93440.00000.93330.94530.93320.90150.9076
SD0.07310.00000.07370.06770.07380.10970.1063

K Neighbors Classifier

In [13]:
import numpy as np
tuned_knn = tune_model(knn, custom_grid = {'n_neighbors' : np.arange(0,50,1)})
AccuracyAUCRecallPrec.F1KappaMCC
01.00000.00001.00001.00001.00001.00001.0000
11.00000.00001.00001.00001.00001.00001.0000
20.90000.00000.88890.92500.89710.84850.8616
30.90000.00000.88890.92500.89710.84850.8616
40.88890.00000.88890.91670.88570.83330.8492
51.00000.00001.00001.00001.00001.00001.0000
61.00000.00001.00001.00001.00001.00001.0000
70.88890.00000.88890.91670.88570.83330.8492
81.00000.00001.00001.00001.00001.00001.0000
90.77780.00000.77780.86670.75000.66670.7223
Mean0.93560.00000.93330.95500.93160.90300.9144
SD0.07250.00000.07370.04760.07930.10890.0936

 Logistic Regression

In [14]:
tuned_lr = tune_model(lr)
AccuracyAUCRecallPrec.F1KappaMCC
01.00000.00001.00001.00001.00001.00001.0000
11.00000.00001.00001.00001.00001.00001.0000
21.00000.00001.00001.00001.00001.00001.0000
30.90000.00000.88890.92500.89710.84850.8616
41.00000.00001.00001.00001.00001.00001.0000
51.00000.00001.00001.00001.00001.00001.0000
60.88890.00000.88890.91670.88570.83330.8492
70.88890.00000.88890.91670.88570.83330.8492
81.00000.00001.00001.00001.00001.00001.0000
90.77780.00000.77780.77780.77780.66670.6667
Mean0.94560.00000.94440.95360.94460.91820.9227
SD0.07380.00000.07450.06880.07450.11080.1077

Plot a Model

Before model finalization, the plot_model() function can be used to analyze the performance across different aspects such as AUC, confusion_matrix, decision boundary etc. This function takes a trained model object and returns a plot based on the test / hold-out set.

There are 15 different plots available, please see the plot_model() docstring for the list of available plots.

Confusion Matrix

In [15]:
plot_model(tuned_knn, plot = 'confusion_matrix')

In [16]:
plot_model(tuned_knn, plot = 'class_report')

Decision Boundary Plot

In [17]:
plot_model(tuned_knn, plot='boundary')

Prediction Error Plot

In [18]:
plot_model(tuned_knn, plot = 'error')

Predict on test / hold-out Sample

predict_model(tuned_knn);
ModelAccuracyAUCRecallPrec.F1KappaMCC
0One Vs Rest Classifier0.951200.95050.95120.95120.92680.9268

Last modified: Thursday, 24 March 2022, 11:28 AM