Binary Classification Tutorial (CLF101) - Level Beginner

Date Updated: Feb 25, 2020

1.0 Tutorial Objective

Welcome to the Binary Classification Tutorial (CLF101) - Level Beginner. This tutorial assumes that you are new to PyCaret and looking to get started with Binary Classification using the pycaret.classification Module.

In this tutorial we will learn:

  • Getting Data: How to import data from PyCaret repository
  • Setting up Environment: How to setup an experiment in PyCaret and get started with building classification models
  • Create Model: How to create a model, perform stratified cross validation and evaluate classification metrics
  • Tune Model: How to automatically tune the hyper-parameters of a classification model
  • Plot Model: How to analyze model performance using various plots
  • Finalize Model: How to finalize the best model at the end of the experiment
  • Predict Model: How to make predictions on new / unseen data
  • Save / Load Model: How to save / load a model for future use

Read Time : Approx. 30 Minutes

1.1 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

1.2 Pre-Requisites

  • Python 3.x
  • Latest version of pycaret
  • Internet connection to load data from pycaret's repository
  • Basic Knowledge of Binary Classification

1.3 For Google colab users:

If you are running this notebook on Google colab, run the following code at top of your notebook to display interactive visuals.

from pycaret.utils import enable_colab
enable_colab()

1.4 See also:

2.0 What is Binary Classification?

Binary classification is a supervised machine learning technique where the goal is to predict categorical class labels which are discrete and unoredered such as Pass/Fail, Positive/Negative, Default/Not-Default etc. A few real world use cases for classification are listed below:

  • Medical testing to determine if a patient has a certain disease or not - the classification property is the presence of the disease.
  • A "pass or fail" test method or quality control in factories, i.e. deciding if a specification has or has not been met – a go/no-go classification.
  • Information retrieval, namely deciding whether a page or an article should be in the result set of a search or not – the classification property is the relevance of the article, or the usefulness to the user.

Learn More about Binary Classification

3.0 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 a binary group based on various techniques and algorithms. Some common use cases of classification problems include predicting customer default (yes or no), customer churn (customer will leave or stay), disease found (positive or negative).

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.

4.0 Dataset for the Tutorial

For this tutorial we will use a dataset from UCI called Default of Credit Card Clients Dataset. This dataset contains information on default payments, demographic factors, credit data, payment history, and billing statements of credit card clients in Taiwan from April 2005 to September 2005. There are 24,000 samples and 25 features. Short descriptions of each column are as follows:

  • ID: ID of each client
  • LIMIT_BAL: Amount of given credit in NT dollars (includes individual and family/supplementary credit)
  • SEX: Gender (1=male, 2=female)
  • EDUCATION: (1=graduate school, 2=university, 3=high school, 4=others, 5=unknown, 6=unknown)
  • MARRIAGE: Marital status (1=married, 2=single, 3=others)
  • AGE: Age in years
  • PAY_0 to PAY_6: Repayment status by n months ago (PAY_0 = last month ... PAY_6 = 6 months ago) (Labels: -1=pay duly, 1=payment delay for one month, 2=payment delay for two months, ... 8=payment delay for eight months, 9=payment delay for nine months and above)
  • BILL_AMT1 to BILL_AMT6: Amount of bill statement by n months ago ( BILL_AMT1 = last_month .. BILL_AMT6 = 6 months ago)
  • PAY_AMT1 to PAY_AMT6: Amount of payment by n months ago ( BILL_AMT1 = last_month .. BILL_AMT6 = 6 months ago)
  • default: Default payment (1=yes, 0=no) Target Column

Dataset Acknowledgement:

Lichman, M. (2013). UCI Machine Learning Repository. Irvine, CA: University of California, School of Information and Computer Science.

The original dataset and data dictionary can be found here.

5.0 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('credit')
LIMIT_BAL SEX EDUCATION MARRIAGE AGE PAY_1 PAY_2 PAY_3 PAY_4 PAY_5 ... BILL_AMT4 BILL_AMT5 BILL_AMT6 PAY_AMT1 PAY_AMT2 PAY_AMT3 PAY_AMT4 PAY_AMT5 PAY_AMT6 default
0 20000 2 2 1 24 2 2 -1 -1 -2 ... 0.0 0.0 0.0 0.0 689.0 0.0 0.0 0.0 0.0 1
1 90000 2 2 2 34 0 0 0 0 0 ... 14331.0 14948.0 15549.0 1518.0 1500.0 1000.0 1000.0 1000.0 5000.0 0
2 50000 2 2 1 37 0 0 0 0 0 ... 28314.0 28959.0 29547.0 2000.0 2019.0 1200.0 1100.0 1069.0 1000.0 0
3 50000 1 2 1 57 -1 0 -1 0 0 ... 20940.0 19146.0 19131.0 2000.0 36681.0 10000.0 9000.0 689.0 679.0 0
4 50000 1 1 2 37 0 0 0 0 0 ... 19394.0 19619.0 20024.0 2500.0 1815.0 657.0 1000.0 1000.0 800.0 0

5 rows × 24 columns

In [2]:
#check the shape of data
dataset.shape
Out[2]:
(24000, 24)

In order to demonstrate the predict_model() function on unseen data, a sample of 1200 records has been withheld from the original dataset to be used for predictions. This should not be confused with a train/test split as this particular split is performed to simulate a real life scenario. Another way to think about this is that these 1200 records are not available at the time when the machine learning experiment was performed.

In [3]:
data = dataset.sample(frac=0.95, random_state=786).reset_index(drop=True)
data_unseen = dataset.drop(data.index).reset_index(drop=True)

print('Data for Modeling: ' + str(data.shape))
print('Unseen Data For Predictions: ' + str(data_unseen.shape))
Data for Modeling: (22800, 24)
Unseen Data For Predictions: (1200, 24)

6.0 Setting up Environment in PyCaret

The setup() function initializes the environment in pycaret and creates the transformation pipeline to prepare the data for modeling and deployment. setup() must be called before executing any other function in pycaret. It takes two mandatory parameters: a pandas dataframe and the name of the target column. All other parameters are optional and are used to customize the pre-processing pipeline (we will see them in later tutorials).

When setup() is executed, PyCaret's inference algorithm will automatically infer the data types for all features based on certain properties. The data type should be inferred correctly but this is not always the case. To account for this, PyCaret displays a table containing the features and their inferred data types after setup() is executed. If all of the data types are correctly identified enter can be pressed to continue or quit can be typed to end the expriment. Ensuring that the data types are correct is of fundamental importance in PyCaret as it automatically performs a few pre-processing tasks which are imperative to any machine learning experiment. These tasks are performed differently for each data type which means it is very important for them to be correctly configured.

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 *
In [5]:
exp_clf101 = setup(data = data, target = 'default', session_id=123) 
 
Setup Succesfully Completed!
Description Value
0 session_id 123
1 Target Type Binary
2 Label Encoded None
3 Original Data (22800, 24)
4 Missing Values False
5 Numeric Features 14
6 Categorical Features 9
7 Ordinal Features False
8 High Cardinality Features False
9 High Cardinality Method None
10 Sampled Data (22800, 24)
11 Transformed Train Set (15959, 90)
12 Transformed Test Set (6841, 90)
13 Numeric Imputer mean
14 Categorical Imputer constant
15 Normalize False
16 Normalize Method None
17 Transformation False
18 Transformation Method None
19 PCA False
20 PCA Method None
21 PCA Components None
22 Ignore Low Variance False
23 Combine Rare Levels False
24 Rare Level Threshold None
25 Numeric Binning False
26 Remove Outliers False
27 Outliers Threshold None
28 Remove Multicollinearity False
29 Multicollinearity Threshold None
30 Clustering False
31 Clustering Iteration None
32 Polynomial Features False
33 Polynomial Degree None
34 Trignometry Features False
35 Polynomial Threshold None
36 Group Features False
37 Feature Selection False
38 Features Selection Threshold None
39 Feature Interaction False
40 Feature Ratio False
41 Interaction Threshold None

Once the setup has been succesfully executed it prints the information grid which contains several important pieces of information. Most of the information is related to the pre-processing pipeline which is constructed when setup() is executed. The majority of these features are out of scope for the purposes of this tutorial however a few important things to note at this stage include:

  • session_id : A pseduo-random number distributed as a seed in all functions for later reproducibility. If no session_id is passed, a random number is automatically generated that is distributed to all functions. In this experiment, the session_id is set as 123 for later reproducibility.

  • Target Type : Binary or Multiclass. The Target type is automatically detected and shown. There is no difference in how the experiment is performed for Binary or Multiclass problems. All functionalities are identical.

  • Label Encoded : When the Target variable is of type string (i.e. 'Yes' or 'No') instead of 1 or 0, it automatically encodes the label into 1 and 0 and displays the mapping (0 : No, 1 : Yes) for reference. In this experiment no label encoding is required since the target variable is of type numeric.

  • Original Data : Displays the original shape of the dataset. In this experiment (22800, 24) means 22,800 samples and 24 features including the target column.

  • Missing Values : When there are missing values in the original data this will show as True. For this experiment there are no missing values in the dataset.

  • Numeric Features : The number of features inferred as numeric. In this dataset, 14 out of 24 features are inferred as numeric.

  • Categorical Features : The number of features inferred as categorical. In this dataset, 9 out of 24 features are inferred as categorical.

  • Transformed Train Set : Displays the shape of the transformed training set. Notice that the original shape of (22800, 24) is transformed into (15959, 91) for the transformed train set and the number of features have increased to 91 from 24 due to categorical encoding

  • Transformed Test Set : Displays the shape of the transformed test/hold-out set. There are 6841 samples in test/hold-out set. This split is based on the default value of 70/30 that can be changed using the train_size parameter in setup.

Notice how a few tasks that are imperative to perform modeling are automatically handled such as missing value imputation (in this case there are no missing values in the training data, but we still need imputers for unseen data), categorical encoding etc. Most of the parameters in setup() are optional and used for customizing the pre-processing pipeline. These parameters are out of scope for this tutorial but as you progress to the intermediate and expert levels, we will cover them in much greater detail.

7.0 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, AUC, Recall, Precision, F1 and Kappa accross the folds (10 by default) of all the available models in the model library.

In [6]:
compare_models()
Out[6]:
Model Accuracy AUC Recall Prec. F1 Kappa
0 Ridge Classifier 0.8236 0 0.3646 0.6932 0.4776 0.3836
1 Linear Discriminant Analysis 0.8236 0.7703 0.3813 0.6818 0.4888 0.3923
2 Gradient Boosting Classifier 0.8225 0.7887 0.3649 0.687 0.4763 0.3813
3 CatBoost Classifier 0.822 0.7867 0.3873 0.6691 0.4904 0.3917
4 Extreme Gradient Boosting 0.8218 0.7894 0.3595 0.6862 0.4715 0.3767
5 Light Gradient Boosting Machine 0.8214 0.7859 0.3878 0.6663 0.49 0.3908
6 Ada Boost Classifier 0.8185 0.7783 0.3507 0.6729 0.4607 0.3644
7 Extra Trees Classifier 0.8093 0.7533 0.3839 0.61 0.4711 0.362
8 Random Forest Classifier 0.8084 0.738 0.3337 0.6254 0.4349 0.3323
9 Quadratic Discriminant Analysis 0.7893 0.7392 0.1734 0.6276 0.2378 0.1698
10 Logistic Regression 0.7786 0.6508 0.0006 0.075 0.0011 0.0001
11 K Neighbors Classifier 0.7505 0.6099 0.1802 0.3693 0.2421 0.1134
12 Decision Tree Classifier 0.7294 0.6197 0.4221 0.3953 0.4081 0.233
13 SVM - Linear Kernel 0.653 0 0.2547 0.1056 0.112 0.0121
14 Naive Bayes 0.3651 0.6457 0.902 0.2455 0.3859 0.0585

Two simple words of code (not even a line) have created over 15 models using 10 fold stratified cross validation and evaluated the 6 most commonly used classification metrics (Accuracy, AUC, Recall, Precision, F1, Kappa). The score grid printed above highlights the highest performing metric for comparison purposes only. The grid by default is sorted using 'Accuracy' (highest to lowest) which can be changed by passing the sort parameter. For example compare_models(sort = 'Recall') will sort the grid by Recall instead of Accuracy. If you want to change the fold parameter from the default value of 10 to a different value then you can use the fold parameter. For example compare_models(fold = 5) will compare all models on 5 fold cross validation. Reducing the number of folds will improve the training time.

8.0 Create a Model

While compare_models() is a powerful function and often a starting point in any experiment, it does not return any trained models. PyCaret's recommended experiment workflow is to use compare_models() right after setup to evaluate top performing models and finalize a few candidates for continued experimentation. As such, the function that actually allows to you create a model is unimaginatively called create_model(). This function creates a model and scores it using stratified cross validation. Similar to compare_models(), the output prints a score grid that shows Accuracy, AUC, Recall, Precision, F1 and Kappa 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')
  • Random Forest Classifier ('rf')

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

8.1 Decision Tree Classifier

In [7]:
dt = create_model('dt')
Accuracy AUC Recall Prec. F1 Kappa
0 0.7325 0.6213 0.4221 0.4005 0.4110 0.2381
1 0.7237 0.6199 0.4306 0.3878 0.4081 0.2285
2 0.7400 0.6361 0.4504 0.4184 0.4338 0.2654
3 0.7155 0.5984 0.3853 0.3646 0.3747 0.1907
4 0.7375 0.6175 0.4023 0.4057 0.4040 0.2356
5 0.7356 0.6376 0.4618 0.4127 0.4358 0.2639
6 0.7237 0.6210 0.4363 0.3889 0.4112 0.2315
7 0.7387 0.6365 0.4533 0.4167 0.4342 0.2647
8 0.7262 0.6062 0.3909 0.3833 0.3871 0.2108
9 0.7210 0.6030 0.3881 0.3743 0.3811 0.2011
Mean 0.7294 0.6197 0.4221 0.3953 0.4081 0.2330
SD 0.0081 0.0134 0.0274 0.0175 0.0211 0.0252
In [8]:
#trained model object is stored in the variable 'dt'. 
print(dt)
DecisionTreeClassifier(ccp_alpha=0.0, class_weight=None, criterion='gini',
                       max_depth=None, max_features=None, max_leaf_nodes=None,
                       min_impurity_decrease=0.0, min_impurity_split=None,
                       min_samples_leaf=1, min_samples_split=2,
                       min_weight_fraction_leaf=0.0, presort='deprecated',
                       random_state=123, splitter='best')

8.2 K Neighbors Classifier

In [9]:
knn = create_model('knn')
Accuracy AUC Recall Prec. F1 Kappa
0 0.7406 0.5879 0.1671 0.3296 0.2218 0.0857
1 0.7350 0.5787 0.1473 0.2989 0.1973 0.0601
2 0.7632 0.6648 0.2096 0.4277 0.2814 0.1590
3 0.7462 0.5984 0.1530 0.3375 0.2105 0.0842
4 0.7550 0.6098 0.2040 0.3956 0.2692 0.1397
5 0.7613 0.6203 0.1870 0.4125 0.2573 0.1384
6 0.7412 0.5883 0.1671 0.3315 0.2222 0.0868
7 0.7594 0.6139 0.1898 0.4061 0.2587 0.1371
8 0.7487 0.6100 0.1898 0.3681 0.2505 0.1177
9 0.7542 0.6264 0.1870 0.3860 0.2519 0.1256
Mean 0.7505 0.6099 0.1802 0.3693 0.2421 0.1134
SD 0.0091 0.0234 0.0197 0.0407 0.0260 0.0305

8.3 Random Forest Classifier

In [10]:
rf = create_model('rf')
Accuracy AUC Recall Prec. F1 Kappa
0 0.8064 0.7435 0.3229 0.6196 0.4246 0.3218
1 0.8076 0.7488 0.3314 0.6223 0.4325 0.3295
2 0.8170 0.7576 0.3683 0.6533 0.4710 0.3707
3 0.8139 0.7175 0.3513 0.6458 0.4550 0.3544
4 0.8026 0.7199 0.2890 0.6145 0.3931 0.2930
5 0.8114 0.7446 0.3569 0.6300 0.4557 0.3520
6 0.8008 0.7286 0.3258 0.5897 0.4197 0.3113
7 0.8070 0.7502 0.3144 0.6271 0.4189 0.3181
8 0.8114 0.7262 0.3371 0.6398 0.4416 0.3410
9 0.8063 0.7428 0.3399 0.6122 0.4372 0.3315
Mean 0.8084 0.7380 0.3337 0.6254 0.4349 0.3323
SD 0.0048 0.0131 0.0216 0.0174 0.0213 0.0217

Notice that the mean score of all models matches with the score printed in compare_models(). This is because the metrics printed in the compare_models() score grid are the average scores across all CV folds. Similar to compare_models(), if you want to change the fold parameter from the default value of 10 to a different value then you can use the fold parameter. For Example: create_model('dt', fold = 5) will create a Decision Tree Classifier using 5 fold stratified CV.

9.0 Tune a Model

When a model is created using the create_model() function it uses the default hyperparameters. In order to tune hyperparameters, the tune_model() function is used. This function automatically tunes the hyperparameters of a model on a pre-defined search space and scores it using stratified cross validation. The output prints a score grid that shows Accuracy, AUC, Recall, Precision, F1 and Kappa by fold.

Note: tune_model() does not take a trained model object as an input. It instead requires a model name to be passed as an abbreviated string similar to how it is passed in create_model(). All other functions in pycaret.classification require a trained model object as an argument.

9.1 Decision Tree Classifier

In [11]:
tuned_dt = tune_model('dt')
Accuracy AUC Recall Prec. F1 Kappa
0 0.8264 0.7219 0.3201 0.7533 0.4493 0.3656
1 0.8239 0.7259 0.3059 0.7500 0.4346 0.3515
2 0.8158 0.7548 0.2946 0.6980 0.4143 0.3258
3 0.8208 0.7171 0.3173 0.7134 0.4392 0.3508
4 0.8133 0.7178 0.3173 0.6627 0.4291 0.3337
5 0.8239 0.7359 0.3003 0.7571 0.4300 0.3481
6 0.8164 0.7197 0.2975 0.7000 0.4175 0.3290
7 0.8264 0.7408 0.3031 0.7754 0.4358 0.3557
8 0.8214 0.7158 0.3003 0.7361 0.4266 0.3423
9 0.8107 0.7322 0.3003 0.6584 0.4125 0.3179
Mean 0.8199 0.7282 0.3057 0.7204 0.4289 0.3420
SD 0.0053 0.0120 0.0087 0.0384 0.0111 0.0143
In [12]:
#tuned model object is stored in the variable 'tuned_dt'. 
print(tuned_dt)
DecisionTreeClassifier(ccp_alpha=0.0, class_weight=None, criterion='gini',
                       max_depth=3, max_features=78, max_leaf_nodes=None,
                       min_impurity_decrease=0.0, min_impurity_split=None,
                       min_samples_leaf=3, min_samples_split=2,
                       min_weight_fraction_leaf=0.0, presort='deprecated',
                       random_state=123, splitter='best')

9.2 K Neighbors Classifier

In [13]:
tuned_knn = tune_model('knn')
Accuracy AUC Recall Prec. F1 Kappa
0 0.7738 0.6494 0.0708 0.4310 0.1217 0.0632
1 0.7769 0.6662 0.0652 0.4694 0.1144 0.0640
2 0.7838 0.7061 0.1161 0.5541 0.1920 0.1250
3 0.7769 0.6407 0.0623 0.4681 0.1100 0.0612
4 0.7769 0.6507 0.0708 0.4717 0.1232 0.0694
5 0.7788 0.6858 0.0878 0.5000 0.1494 0.0892
6 0.7807 0.6516 0.0765 0.5294 0.1337 0.0824
7 0.7845 0.6591 0.0935 0.5789 0.1610 0.1060
8 0.7769 0.6565 0.0652 0.4694 0.1144 0.0640
9 0.7812 0.6807 0.0935 0.5323 0.1590 0.0995
Mean 0.7791 0.6647 0.0802 0.5004 0.1379 0.0824
SD 0.0032 0.0192 0.0163 0.0442 0.0253 0.0209

9.3 Random Forest Classifier

In [14]:
tuned_rf = tune_model('rf')
Accuracy AUC Recall Prec. F1 Kappa
0 0.8289 0.7871 0.3484 0.7410 0.4740 0.3873
1 0.8227 0.7990 0.3513 0.6966 0.4670 0.3743
2 0.8221 0.8251 0.3824 0.6716 0.4874 0.3894
3 0.8227 0.7740 0.3626 0.6882 0.4750 0.3804
4 0.8227 0.7795 0.3513 0.6966 0.4670 0.3743
5 0.8239 0.7918 0.3598 0.6978 0.4748 0.3817
6 0.8202 0.7536 0.3343 0.6941 0.4512 0.3591
7 0.8302 0.7935 0.3569 0.7412 0.4818 0.3948
8 0.8214 0.7649 0.3541 0.6868 0.4673 0.3729
9 0.8138 0.7824 0.3598 0.6414 0.4610 0.3590
Mean 0.8229 0.7851 0.3561 0.6955 0.4707 0.3773
SD 0.0043 0.0186 0.0116 0.0279 0.0098 0.0113

The tune_model() function is a random grid search of hyperparameters over a pre-defined search space. By default, it is set to optimize Accuracy but this can be changed using optimize parameter. For example: tune_model('dt', optimize = 'AUC') will search for the hyperparameters of a Decision Tree Classifier that results in highest AUC. For the purposes of this example, we have used the default metric Accuracy for the sake of simplicity only. Generally, when the dataset is imbalanced (such as the credit dataset we are working with) Accuracy is not a good metric for consideration. The methodology behind selecting the right metric to evaluate a classifier is beyond the scope of this tutorial but if you would like to learn more about it, you can click here to read an article on how to choose the right evaluation metric.

Notice how the results after tuning have been improved:

  • Decision Tree Classifier (Before: 0.7294 , After: 0.8199)
  • K Neighbors Classifier (Before: 0.7505 , After: 0.7791)
  • Random Forest Classifier (Before: 0.8084 , After: 0.8229)

Metrics alone are not the only criteria you should consider when finalizing the best model for production. Other factors to consider include training time, standard deviation of kfolds etc. As you progress through the tutorial series we will discuss those factors in detail at the intermediate and expert levels. For now, let's move forward considering the Tuned Random Forest Classifier as our best model for the remainder of this tutorial.

10.0 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.

10.1 AUC Plot

In [15]:
plot_model(tuned_rf, plot = 'auc')

10.2 Precision-Recall Curve

In [16]:
plot_model(tuned_rf, plot = 'pr')

10.3 Feature Importance Plot

In [17]:
plot_model(tuned_rf, plot='feature')

10.4 Confusion Matrix

In [18]:
plot_model(tuned_rf, plot = 'confusion_matrix')

Another way to analyze the performance of models is to use the evaluate_model() function which displays a user interface for all of the available plots for a given model. It internally uses the plot_model() function.

In [19]:
evaluate_model(tuned_rf)

11.0 Predict on test / hold-out Sample

Before finalizing the model, it is advisable to perform one final check by predicting the test/hold-out set and reviewing the evaluation metrics. If you look at the information grid in Section 6 above, you will see that 30% (6,841 samples) of the data has been separated out as test/hold-out sample. All of the evaluation metrics we have seen above are cross validated results based on the training set (70%) only. Now, using our final trained model stored in the tuned_rf variable we will predict against the hold-out sample and evaluate the metrics to see if they are materially different than the CV results.

In [20]:
predict_model(tuned_rf);
Model Accuracy AUC Recall Prec. F1 Kappa
0 Random Forest Classifier 0.8126 0.7538 0.3212 0.6559 0.4312 0.3345

The accuracy on test/hold-out set is 0.8126 compared to 0.8229 achieved on the tuned_rf CV results (in section 9.3 above). This is not a significant difference. If there is a large variation between the test/hold-out and CV results, then this would normally indicate over-fitting but could also be due to several other factors and would require further investigation. In this case, we will move forward with finalizing the model and predicting on unseen data (the 5% that we had separated in the beginning and never exposed to PyCaret).

(TIP : It's always good to look at the standard deviation of CV results when using create_model().)

12.0 Finalize Model for Deployment

Model finalization is the last step in the experiment. A normal machine learning workflow in PyCaret starts with setup(), followed by comparing all models using compare_models() and shortlisting a few candidate models (based on the metric of interest) to perform several modeling techniques such as hyperparameter tuning, ensembling, stacking etc. This workflow will eventually lead you to the best model for use in making predictions on new and unseen data. The finalize_model() function fits the model onto the complete dataset including the test/hold-out sample (30% in this case). The purpose of this function is to train the model on the complete dataset before it is deployed in production.

In [21]:
final_rf = finalize_model(tuned_rf)
In [22]:
#Final Random Forest model parameters for deployment
print(final_rf)
RandomForestClassifier(bootstrap=True, ccp_alpha=0.0, class_weight=None,
                       criterion='gini', max_depth=10, max_features='auto',
                       max_leaf_nodes=None, max_samples=None,
                       min_impurity_decrease=0.0, min_impurity_split=None,
                       min_samples_leaf=2, min_samples_split=10,
                       min_weight_fraction_leaf=0.0, n_estimators=70,
                       n_jobs=None, oob_score=False, random_state=123,
                       verbose=0, warm_start=False)

Caution: One final word of caution. Once the model is finalized using finalize_model(), the entire dataset including the test/hold-out set is used for training. As such, if the model is used for predictions on the hold-out set after finalize_model() is used, the information grid printed will be misleading as you are trying to predict on the same data that was used for modeling. In order to demonstrate this point only, we will use final_rf under predict_model() to compare the information grid with the one above in section 11.

In [23]:
predict_model(final_rf);
Model Accuracy AUC Recall Prec. F1 Kappa
0 Random Forest Classifier 0.8361 0.8189 0.3681 0.7715 0.4984 0.4148

Notice how the AUC in final_rf has increased to 0.8189 from 0.7538, even though the model is the same. This is because the final_rf variable has been trained on the complete dataset including the test/hold-out set.

13.0 Predict on unseen data

The predict_model() function is also used to predict on the unseen dataset. The only difference from section 11 above is that this time we will pass the data_unseen parameter. data_unseen is the variable created at the beginning of the tutorial and contains 5% (1200 samples) of the original dataset which was never exposed to PyCaret. (see section 5 for explanation)

In [24]:
unseen_predictions = predict_model(final_rf, data=data_unseen)
unseen_predictions.head()
Out[24]:
LIMIT_BAL SEX EDUCATION MARRIAGE AGE PAY_1 PAY_2 PAY_3 PAY_4 PAY_5 ... BILL_AMT6 PAY_AMT1 PAY_AMT2 PAY_AMT3 PAY_AMT4 PAY_AMT5 PAY_AMT6 default Label Score
0 50000 2 2 1 48 0 0 0 0 0 ... 8011.0 2028.0 2453.0 2329.0 431.0 300.0 500.0 0 0 0.1498
1 200000 2 1 1 40 2 2 2 2 2 ... 89112.0 4200.0 4100.0 3000.0 3400.0 3500.0 0.0 1 1 0.7986
2 50000 2 3 1 44 1 2 3 2 4 ... 15798.0 2100.0 1000.0 2300.0 0.0 0.0 0.0 1 1 0.6261
3 60000 2 2 1 31 2 2 -1 0 0 ... 30384.0 1132.0 60994.0 1436.0 1047.0 1056.0 1053.0 1 1 0.5063
4 120000 2 3 2 32 -1 0 0 0 0 ... 81354.0 2429.0 3120.0 3300.0 10000.0 3200.0 3200.0 0 0 0.1479

5 rows × 26 columns

The Label and Score columns are added onto the data_unseen set. Label is the prediction and score is the probability of the prediction. Notice that predicted results are concatenated to the original dataset while all the transformations are automatically performed in the background.

14.0 Saving the model

We have now finished the experiment by finalizing the tuned_rf model which is now stored in final_rf variable. We have also used the model stored in final_rf to predict data_unseen. This brings us to the end of our experiment, but one question is still to be asked: What happens when you have more new data to predict? Do you have to go through the entire experiment again? The answer is no, PyCaret's inbuilt function save_model() allows you to save the model along with entire transformation pipeline for later use.

In [25]:
save_model(final_rf,'Final RF Model 08Feb2020')
Transformation Pipeline and Model Succesfully Saved

(TIP : It's always good to use date in the filename when saving models, it's good for version control.)

15.0 Loading the saved model

To load a saved model at a future date in the same or an alternative environment, we would use PyCaret's load_model() function and then easily apply the saved model on new unseen data for prediction.

In [26]:
saved_final_rf = load_model('Final RF Model 08Feb2020')
Transformation Pipeline and Model Sucessfully Loaded

Once the model is loaded in the environment, you can simply use it to predict on any new data using the same predict_model() function. Below we have applied the loaded model to predict the same data_unseen that we used in section 13 above.

In [27]:
new_prediction = predict_model(saved_final_rf, data=data_unseen)
In [28]:
new_prediction.head()
Out[28]:
LIMIT_BAL SEX EDUCATION MARRIAGE AGE PAY_1 PAY_2 PAY_3 PAY_4 PAY_5 ... BILL_AMT6 PAY_AMT1 PAY_AMT2 PAY_AMT3 PAY_AMT4 PAY_AMT5 PAY_AMT6 default Label Score
0 50000 2 2 1 48 0 0 0 0 0 ... 8011.0 2028.0 2453.0 2329.0 431.0 300.0 500.0 0 0 0.1498
1 200000 2 1 1 40 2 2 2 2 2 ... 89112.0 4200.0 4100.0 3000.0 3400.0 3500.0 0.0 1 1 0.7986
2 50000 2 3 1 44 1 2 3 2 4 ... 15798.0 2100.0 1000.0 2300.0 0.0 0.0 0.0 1 1 0.6261
3 60000 2 2 1 31 2 2 -1 0 0 ... 30384.0 1132.0 60994.0 1436.0 1047.0 1056.0 1053.0 1 1 0.5063
4 120000 2 3 2 32 -1 0 0 0 0 ... 81354.0 2429.0 3120.0 3300.0 10000.0 3200.0 3200.0 0 0 0.1479

5 rows × 26 columns

Notice that the results of unseen_predictions and new_prediction are identical.

16.0 Wrap-up / Next Steps?

This tutorial has covered the entire machine learning pipeline from data ingestion, pre-processing, training the model, hyperparameter tuning, prediction and saving the model for later use. We have completed all of these steps in less than 10 commands which are naturally constructed and very intuitive to remember such as create_model(), tune_model(), compare_models(). Re-creating the entire experiment without PyCaret would have taken well over 100 lines of code in most libraries.

We have only covered the basics of pycaret.classification. In following tutorials we will go deeper into advanced pre-processing, ensembling, generalized stacking and other techniques that allow you to fully customize your machine learning pipeline and are must know for any data scientist.

See you at the next tutorial. Follow the link to Binary Classification Tutorial (CLF102) - Intermediate Level