Regression Tutorial (REG101) - Level Beginner

Date Updated: Feb 25, 2020

1.0 Tutorial Objective

Welcome to Regression Tutorial (REG101) - Level Beginner. This tutorial assumes that you are new to PyCaret and looking to get started with Regression using the pycaret.regression 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 regression models
  • Create Model: How to create a model, perform cross validation and evaluate regression metrics
  • Tune Model: How to automatically tune the hyper-parameters of a regression 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 prediction 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 Regression

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 Regression?

Regression analysis is a set of statistical processes for estimating the relationships between a dependent variable (often called the 'outcome variable', or 'target') and one or more independent variables (often called 'features', 'predictors', or 'covariates'). The objective of regression in machine learning is to predict continuous values such as sales amount, quantity, temperature etc.

Learn More about Regression

3.0 Overview of the Regression Module in PyCaret

PyCaret's Regression module (pycaret.regression) is a supervised machine learning module which is used for predicting continuous values / outcomes using various techniques and algorithms. Regression can be used for predicting values / outcomes such as sales, units sold, temperature or any number which is continuous.

PyCaret's regression module has over 25 algorithms and 10 plots to analyze the performance of models. Be it hyper-parameter tuning, ensembling or advanced techniques like stacking, PyCaret's regression module has it all.

4.0 Dataset for the Tutorial

For this tutorial we will use a dataset based on a case study called "Sarah Gets a Diamond". This case was presented in the first year decision analysis course at Darden School of Business (University of Virginia). The basis for the data is a case regarding a hopeless romantic MBA student choosing the right diamond for his bride-to-be, Sarah. The data contains 6000 records for training. Short descriptions of each column are as follows:

  • ID: Uniquely identifies each observation (diamond)
  • Carat Weight: The weight of the diamond in metric carats. One carat is equal to 0.2 grams, roughly the same weight as a paperclip
  • Cut: One of five values indicating the cut of the diamond in the following order of desirability (Signature-Ideal, Ideal, Very Good, Good, Fair)
  • Color: One of six values indicating the diamond's color in the following order of desirability (D, E, F - Colorless, G, H, I - Near colorless)
  • Clarity: One of seven values indicating the diamond's clarity in the following order of desirability (F - Flawless, IF - Internally Flawless, VVS1 or VVS2 - Very, Very Slightly Included, or VS1 or VS2 - Very Slightly Included, SI1 - Slightly Included)
  • Polish: One of four values indicating the diamond's polish (ID - Ideal, EX - Excellent, VG - Very Good, G - Good)
  • Symmetry: One of four values indicating the diamond's symmetry (ID - Ideal, EX - Excellent, VG - Very Good, G - Good)
  • Report: One of of two values "AGSL" or "GIA" indicating which grading agency reported the qualities of the diamond qualities
  • Price: The amount in USD that the diamond is valued Target Column

Dataset Acknowledgement:

This case was prepared by Greg Mills (MBA ’07) under the supervision of Phillip E. Pfeifer, Alumni Research Professor of Business Administration. Copyright (c) 2007 by the University of Virginia Darden School Foundation, Charlottesville, VA. All rights reserved.

The original dataset and description 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 internet connection).

In [1]:
from pycaret.datasets import get_data
dataset = get_data('diamond')
Carat Weight Cut Color Clarity Polish Symmetry Report Price
0 1.10 Ideal H SI1 VG EX GIA 5169
1 0.83 Ideal H VS1 ID ID AGSL 3470
2 0.85 Ideal H SI1 EX EX GIA 3183
3 0.91 Ideal E SI1 VG VG GIA 4370
4 0.83 Ideal G SI1 EX EX GIA 3171
In [2]:
#check the shape of data
dataset.shape
Out[2]:
(6000, 8)

In order to demonstrate the predict_model() function on unseen data, a sample of 600 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 600 records are not available at the time when the machine learning experiment was performed.

In [3]:
data = dataset.sample(frac=0.9, 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: (5400, 8)
Unseen Data For Predictions: (600, 8)

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.regression import *
In [5]:
exp_reg101 = setup(data = data, target = 'Price', session_id=123) 
 
Setup Succesfully Completed!
Description Value
0 session_id 123
1 Transform Target False
2 Transform Target Method None
3 Original Data (5400, 8)
4 Missing Values False
5 Numeric Features 1
6 Categorical Features 6
7 Ordinal Features False
8 High Cardinality Features False
9 High Cardinality Method None
10 Sampled Data (5400, 8)
11 Transformed Train Set (3779, 28)
12 Transformed Test Set (1621, 28)
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.

  • Original Data : Displays the original shape of dataset. In this experiment (5400, 8) means 5400 samples and 8 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 : Number of features inferred as numeric. In this dataset, 1 out of 8 features are inferred as numeric.

  • Categorical Features : Number of features inferred as categorical. In this dataset, 6 out of 8 features are inferred as categorical.

  • Transformed Train Set : Displays the shape of the transformed training set. Notice that the original shape of (5400, 8) is transformed into (3779, 28) for the transformed train set. The number of features has increased from 8 from 28 due to categorical encoding

  • Transformed Test Set : Displays the shape of transformed test/hold-out set. There are 1621 samples in test/hold-out set. This split is based on the default value of 70/30 that can be changed using 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 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 kfold cross validation for metric evaluation. The output prints a score grid that shows average MAE, MSE, RMSE, R2, RMSLE and MAPE accross the folds (10 by default) of all the available models in the model library.

In [6]:
compare_models()
Out[6]:
Model MAE MSE RMSE R2 RMSLE MAPE
0 CatBoost Regressor 629.397 2.07934e+06 1376.31 0.9803 0.0676 0.0497
1 Extra Trees Regressor 762.012 2.764e+06 1612.24 0.9729 0.0817 0.0607
2 Random Forest 760.63 2.92968e+06 1663.01 0.9714 0.0818 0.0597
3 Light Gradient Boosting Machine 752.236 3.05557e+06 1687.78 0.9711 0.0773 0.0567
4 Extreme Gradient Boosting 932.797 3.53405e+06 1855.33 0.9652 0.1061 0.0801
5 Gradient Boosting Regressor 920.291 3.7643e+06 1901.18 0.9633 0.1024 0.077
6 Decision Tree 1003.12 5.30562e+06 2228.73 0.9476 0.1083 0.0775
7 Ridge Regression 2413.57 1.41205e+07 3726.16 0.8621 0.6689 0.2875
8 Lasso Regression 2412.19 1.42468e+07 3744.23 0.8608 0.6767 0.2866
9 Linear Regression 2413.55 1.42423e+07 3744.01 0.8607 0.68 0.2871
10 Least Angle Regression 2414.22 1.42427e+07 3744.09 0.8607 0.6683 0.2871
11 Lasso Least Angle Regression 2355.61 1.4272e+07 3745.31 0.8607 0.6391 0.2728
12 Bayesian Ridge 2415.8 1.42708e+07 3746.99 0.8606 0.6696 0.2873
13 TheilSen Regressor 2130.78 1.60278e+07 3942.55 0.8459 0.4814 0.2173
14 Random Sample Consensus 2023.8 1.64513e+07 4010.84 0.8405 0.439 0.1965
15 Huber Regressor 1936.05 1.85888e+07 4251.83 0.821 0.4334 0.1657
16 Passive Aggressive Regressor 1944.16 1.99557e+07 4400.21 0.8083 0.4317 0.1594
17 Orthogonal Matching Pursuit 2792.73 2.37287e+07 4829.32 0.7678 0.5818 0.2654
18 AdaBoost Regressor 4232.22 2.52014e+07 5012.42 0.7467 0.5102 0.597
19 K Neighbors Regressor 2967.05 2.96249e+07 5421.44 0.7051 0.3663 0.2728
20 Elastic Net 5029.59 5.63998e+07 7467.66 0.4472 0.5369 0.5845
21 Support Vector Machine 6438.09 1.15316e+08 10710.4 -0.1422 0.7137 0.5281

Two simple words of code (not even a line) have created over 22 models using 10 fold cross validation and evaluated the 6 most commonly use regression metrics (MAE, MSE, RMSE, R2, RMSLE and MAPE). The score grid printed above highlights the highest performing metric for comparison purposes only. The grid by default is sorted using R2 (highest to lowest) which can be changed by passing sort parameter. For example compare_models(sort = 'RMSLE') will sort the grid by RMSLE (lower to higher since lower is better). 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 MAE, MSE, RMSE, R2, RMSLE and MAPE 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.

  • AdaBoost Regressor ('ada')
  • Light Gradient Boosting Machine ('lightgbm')
  • Decision Tree ('dt')

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

8.1 AdaBoost Regressor

In [7]:
ada = create_model('ada')
MAE MSE RMSE R2 RMSLE MAPE
0 4101.8809 2.301383e+07 4797.2732 0.7473 0.4758 0.5470
1 4251.5693 2.929675e+07 5412.6474 0.7755 0.4940 0.5702
2 4047.8474 2.229166e+07 4721.4045 0.7955 0.5068 0.5871
3 4298.3867 2.348278e+07 4845.9038 0.7409 0.5089 0.5960
4 3888.5584 2.446181e+07 4945.8880 0.6949 0.4764 0.5461
5 4566.4889 2.973391e+07 5452.8813 0.7462 0.5462 0.6598
6 4628.7271 2.784109e+07 5276.4659 0.7384 0.5549 0.6676
7 4316.4317 2.597975e+07 5097.0336 0.6715 0.5034 0.5858
8 3931.2163 2.109707e+07 4593.1549 0.7928 0.4858 0.5513
9 4291.1097 2.481557e+07 4981.5225 0.7637 0.5495 0.6592
Mean 4232.2217 2.520142e+07 5012.4175 0.7467 0.5102 0.5970
SD 233.2282 2.804219e+06 277.6577 0.0375 0.0284 0.0457
In [8]:
#trained model object is stored in the variable 'dt'. 
print(ada)
AdaBoostRegressor(base_estimator=None, learning_rate=1.0, loss='linear',
                  n_estimators=50, random_state=123)

8.2 Light Gradient Boosting Machine

In [9]:
lightgbm = create_model('lightgbm')
MAE MSE RMSE R2 RMSLE MAPE
0 625.1813 1.051763e+06 1025.5550 0.9885 0.0715 0.0526
1 797.6185 5.638866e+06 2374.6297 0.9568 0.0727 0.0537
2 825.0215 3.318727e+06 1821.7374 0.9696 0.0857 0.0616
3 720.3923 1.697211e+06 1302.7707 0.9813 0.0714 0.0554
4 645.6800 1.799949e+06 1341.6218 0.9775 0.0745 0.0534
5 830.7176 6.423604e+06 2534.4830 0.9452 0.0810 0.0567
6 800.2611 3.355856e+06 1831.8996 0.9685 0.0793 0.0585
7 714.3607 1.930223e+06 1389.3245 0.9756 0.0732 0.0556
8 784.7648 2.211933e+06 1487.2569 0.9783 0.0766 0.0582
9 778.3590 3.127561e+06 1768.4913 0.9702 0.0872 0.0609
Mean 752.2357 3.055569e+06 1687.7770 0.9711 0.0773 0.0567
SD 68.9270 1.661228e+06 454.9486 0.0119 0.0055 0.0029

8.3 Decision Tree

In [10]:
dt = create_model('dt')
MAE MSE RMSE R2 RMSLE MAPE
0 859.1907 2.456840e+06 1567.4310 0.9730 0.1016 0.0727
1 1122.9409 9.852564e+06 3138.8795 0.9245 0.1102 0.0758
2 911.3452 2.803663e+06 1674.4141 0.9743 0.0988 0.0729
3 1002.5575 3.926739e+06 1981.6002 0.9567 0.1049 0.0772
4 1167.8154 9.751516e+06 3122.7418 0.8784 0.1226 0.0876
5 1047.7778 7.833771e+06 2798.8874 0.9331 0.1128 0.0791
6 1010.0816 3.989282e+06 1997.3188 0.9625 0.1106 0.0803
7 846.8085 2.182535e+06 1477.3405 0.9724 0.0933 0.0709
8 1001.8451 4.904945e+06 2214.7111 0.9518 0.1053 0.0734
9 1060.8742 5.354348e+06 2313.9463 0.9490 0.1230 0.0847
Mean 1003.1237 5.305620e+06 2228.7271 0.9476 0.1083 0.0775
SD 100.2165 2.734195e+06 581.7181 0.0280 0.0091 0.0052

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) to create Decision Tree using 5 fold cross validation.

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 kfold cross validation. The output prints a score grid that shows MAE, MSE, RMSE, R2, RMSLE and MAPE 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 inpycaret.regression require a trained model object as an argument.

9.1 AdaBoost Regressor

In [11]:
tuned_ada = tune_model('ada')
MAE MSE RMSE R2 RMSLE MAPE
0 2755.4687 1.641891e+07 4052.0257 0.8197 0.2801 0.2603
1 2865.2921 2.326518e+07 4823.3988 0.8217 0.3017 0.2827
2 2570.6452 1.554483e+07 3942.6927 0.8574 0.2606 0.2355
3 2630.2358 1.475497e+07 3841.2197 0.8372 0.2719 0.2329
4 2422.9553 1.388942e+07 3726.8506 0.8268 0.2656 0.2252
5 2530.4172 1.962855e+07 4430.4123 0.8325 0.2635 0.2265
6 2744.5501 1.711563e+07 4137.1039 0.8392 0.2936 0.2696
7 2820.4718 1.767699e+07 4204.4014 0.7765 0.2999 0.2817
8 2574.6180 1.489709e+07 3859.6744 0.8537 0.2954 0.2708
9 2392.6510 1.631377e+07 4039.0306 0.8447 0.2632 0.2225
Mean 2630.7305 1.695053e+07 4105.6810 0.8309 0.2796 0.2508
SD 153.6911 2.620557e+06 306.4572 0.0217 0.0158 0.0233
In [12]:
#tuned model object is stored in the variable 'tuned_dt'. 
print(tuned_ada)
AdaBoostRegressor(base_estimator=None, learning_rate=0.11, loss='exponential',
                  n_estimators=90, random_state=123)

9.2 Light Gradient Boosting Machine

In [13]:
tuned_lightgbm = tune_model('lightgbm')
MAE MSE RMSE R2 RMSLE MAPE
0 696.8135 1.223186e+06 1105.9776 0.9866 0.0816 0.0611
1 769.7567 2.878033e+06 1696.4767 0.9779 0.0740 0.0569
2 796.1051 2.123431e+06 1457.1999 0.9805 0.0816 0.0629
3 766.5171 1.927426e+06 1388.3177 0.9787 0.0815 0.0616
4 740.2536 2.694766e+06 1641.5743 0.9664 0.0815 0.0601
5 789.1642 4.094534e+06 2023.4955 0.9651 0.0805 0.0601
6 720.8130 1.581897e+06 1257.7347 0.9851 0.0801 0.0603
7 841.3175 3.026922e+06 1739.8053 0.9617 0.0857 0.0649
8 816.6643 2.177376e+06 1475.5935 0.9786 0.0809 0.0628
9 765.3249 2.960101e+06 1720.4943 0.9718 0.0933 0.0633
Mean 770.2730 2.468767e+06 1550.6669 0.9753 0.0821 0.0614
SD 41.2386 7.905609e+05 253.3759 0.0081 0.0046 0.0021

9.3 Decision Tree

In [14]:
tuned_dt = tune_model('dt')
MAE MSE RMSE R2 RMSLE MAPE
0 874.4352 2.276756e+06 1508.8923 0.9750 0.0973 0.0740
1 961.9344 5.311160e+06 2304.5955 0.9593 0.0947 0.0709
2 867.5361 2.470714e+06 1571.8506 0.9773 0.0947 0.0732
3 996.1490 4.213594e+06 2052.7042 0.9535 0.1034 0.0747
4 1084.2670 8.813849e+06 2968.8127 0.8901 0.1149 0.0816
5 1062.5522 8.153284e+06 2855.3956 0.9304 0.1131 0.0780
6 911.7975 3.759584e+06 1938.9647 0.9647 0.0957 0.0693
7 975.3512 4.392592e+06 2095.8512 0.9445 0.1061 0.0763
8 1053.7695 4.874987e+06 2207.9373 0.9521 0.1070 0.0802
9 975.3018 4.146015e+06 2036.1766 0.9605 0.1176 0.0821
Mean 976.3094 4.841254e+06 2154.1181 0.9507 0.1045 0.0760
SD 72.1572 2.035135e+06 448.3626 0.0241 0.0083 0.0042

tune_model() function is a random grid search of hyperparameters over a pre-defined search space. By default, it is set to optimize R2 but this can be changed using the optimize parameter. For example: tune_model('dt', optimize = 'MAE') will search for the hyperparameters of a Decision Tree that result in the lowest MAE (lower is better). For the purposes of this example, we have used the default metric R2 for the sake of simplicity only. The methodology behind selecting the right metric to evaluate a regressor is beyond the scope of this tutorial but if you would like to learn more about it, you can click here to develop an understanding on regression error metrics.

Notice how the results after tuning have been improved:

  • AdaBoost Regressor (Before: 0.7467 , After: 0.8309)
  • Light Gradient Boosting Machine (Before: 0.9711 , After: 0.9753)
  • Decision Tree (Before: 0.9476 , After: 0.9507)

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 Light Gradient Boosting Machine stored in the tuned_lightgbm variable 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 Residuals Plot, Prediction Error, feature importance etc. This function takes a trained model object and returns a plot based on the test / hold-out set.

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

10.1 Residual Plot

In [15]:
plot_model(tuned_lightgbm)

10.2 Prediction Error Plot

In [16]:
plot_model(tuned_lightgbm, plot = 'error')

10.3 Feature Importance Plot

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

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 [18]:
evaluate_model(tuned_lightgbm)

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% (1621 samples) of the data has been separated out as a test/hold-out sample. All of the evaluation metrics we have seen above are cross validated results based on training set (70%) only. Now, using our final trained model stored in the tuned_lightgbm variable we will predict the hold-out sample and evaluate the metrics to see if they are materially different than the CV results.

In [19]:
predict_model(tuned_lightgbm);
Model MAE MSE RMSE R2 RMSLE MAPE
0 Light Gradient Boosting Machine 789.8498 2.985032e+06 1727.7244 0.9728 0.0841 0.0613

The R2 on the test/hold-out set is 0.9728 compared to 0.9753 achieved on tuned_lightgbm CV results (in section 9.2 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 10% 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 [20]:
final_lightgbm = finalize_model(tuned_lightgbm)
In [21]:
#Final Light Gradient Boosting Machine parameters for deployment
print(final_lightgbm)
LGBMRegressor(boosting_type='gbdt', class_weight=None, colsample_bytree=1.0,
              importance_type='split', learning_rate=0.4, max_depth=10,
              min_child_samples=20, min_child_weight=0.001, min_split_gain=0.9,
              n_estimators=90, n_jobs=-1, num_leaves=10, objective=None,
              random_state=123, reg_alpha=0.9, reg_lambda=0.2, silent=True,
              subsample=1.0, subsample_for_bin=200000, subsample_freq=0)

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_knn under predict_model() to compare the information grid with the one above in section 11.

In [22]:
predict_model(final_lightgbm);
Model MAE MSE RMSE R2 RMSLE MAPE
0 Light Gradient Boosting Machine 582.5217 1221486.605 1105.2089 0.9889 0.0653 0.0493

Notice how the R2 in the final_lightgbm has increased to 0.9889 from 0.9728, even though the model is same. This is because the final_lightgbm variable is 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 10% (600 samples) of the original dataset which was never exposed to PyCaret. (see section 5 for explanation)

In [23]:
unseen_predictions = predict_model(final_lightgbm, data=data_unseen)
unseen_predictions.head()
Out[23]:
Carat Weight Cut Color Clarity Polish Symmetry Report Price Label
0 1.21 Ideal G VVS1 EX EX GIA 11572 10812.8943
1 2.00 Ideal I SI1 EX VG GIA 16775 15453.9273
2 1.51 Good F SI1 VG G GIA 10429 10591.0952
3 0.90 Ideal F SI1 EX EX GIA 4523 4639.1068
4 1.01 Very Good I SI1 VG VG GIA 4375 4307.9166

The Label column is added onto the data_unseen set. Label is the predicted value using the final_lightgbm model. If you want predictions to be rounded, you can use round parameter inside predict_model().

14.0 Saving the model

We have now finished the experiment by finalizing the tuned_lightgbm model which is now stored in final_lightgbm variable. We have also used the model stored in final_lightgbm 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 [24]:
save_model(final_lightgbm,'Final Lightgbm 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 [25]:
saved_final_lightgbm = load_model('Final Lightgbm 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 [26]:
new_prediction = predict_model(saved_final_lightgbm, data=data_unseen)
In [27]:
new_prediction.head()
Out[27]:
Carat Weight Cut Color Clarity Polish Symmetry Report Price Label
0 1.21 Ideal G VVS1 EX EX GIA 11572 10812.8943
1 2.00 Ideal I SI1 EX VG GIA 16775 15453.9273
2 1.51 Good F SI1 VG G GIA 10429 10591.0952
3 0.90 Ideal F SI1 EX EX GIA 4523 4639.1068
4 1.01 Very Good I SI1 VG VG GIA 4375 4307.9166

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.regression. 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 Regression Tutorial (REG102) - Level Intermediate