Date Updated: Feb 25, 2020
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:
Read Time : Approx. 30 Minutes
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:
pip install pycaret
!pip install pycaret
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()
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.
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.
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:
Target Column
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.
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).
from pycaret.datasets import get_data
dataset = get_data('diamond')
#check the shape of data
dataset.shape
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.
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))
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()
.
from pycaret.regression import *
exp_reg101 = setup(data = data, target = 'Price', session_id=123)
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
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.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.
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.
compare_models()
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.
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.
There are 25 regressors available in the model library of PyCaret. Please view the create_model()
docstring for the list of all available models.
ada = create_model('ada')
#trained model object is stored in the variable 'dt'.
print(ada)
lightgbm = create_model('lightgbm')
dt = create_model('dt')
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.
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.
tuned_ada = tune_model('ada')
#tuned model object is stored in the variable 'tuned_dt'.
print(tuned_ada)
tuned_lightgbm = tune_model('lightgbm')
tuned_dt = tune_model('dt')
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:
0.7467
, After: 0.8309
) 0.9711
, After: 0.9753
)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.
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.
plot_model(tuned_lightgbm)
plot_model(tuned_lightgbm, plot = 'error')
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.
evaluate_model(tuned_lightgbm)
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.
predict_model(tuned_lightgbm);
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()
.)
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.
final_lightgbm = finalize_model(tuned_lightgbm)
#Final Light Gradient Boosting Machine parameters for deployment
print(final_lightgbm)
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.
predict_model(final_lightgbm);
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.
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)
unseen_predictions = predict_model(final_lightgbm, data=data_unseen)
unseen_predictions.head()
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()
.
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.
save_model(final_lightgbm,'Final Lightgbm Model 08Feb2020')
(TIP : It's always good to use date in the filename when saving models, it's good for version control.)
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.
saved_final_lightgbm = load_model('Final Lightgbm Model 08Feb2020')
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.
new_prediction = predict_model(saved_final_lightgbm, data=data_unseen)
new_prediction.head()
Notice that the results of unseen_predictions
and new_prediction
are identical.
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