#!/usr/bin/env python # coding: utf-8 # Last updated: 15 Feb 2023 # # # πŸ‘‹ PyCaret Anomaly Detection Tutorial # # PyCaret is an open-source, low-code machine learning library in Python that automates machine learning workflows. It is an end-to-end machine learning and model management tool that exponentially speeds up the experiment cycle and makes you more productive. # # Compared with the other open-source machine learning libraries, PyCaret is an alternate low-code library that can be used to replace hundreds of lines of code with a few lines only. This makes experiments exponentially fast and efficient. PyCaret is essentially a Python wrapper around several machine learning libraries and frameworks, such as scikit-learn, XGBoost, LightGBM, CatBoost, spaCy, Optuna, Hyperopt, Ray, and a few more. # # The design and simplicity of PyCaret are inspired by the emerging role of citizen data scientists, a term first used by Gartner. Citizen Data Scientists are power users who can perform both simple and moderately sophisticated analytical tasks that would previously have required more technical expertise. # # # πŸ’» Installation # # PyCaret is tested and supported on the following 64-bit systems: # - Python 3.7 – 3.10 # - Python 3.9 for Ubuntu only # - Ubuntu 16.04 or later # - Windows 7 or later # # You can install PyCaret with Python's pip package manager: # # `pip install pycaret` # # PyCaret's default installation will not install all the extra dependencies automatically. For that you will have to install the full version: # # `pip install pycaret[full]` # # or depending on your use-case you may install one of the following variant: # # - `pip install pycaret[analysis]` # - `pip install pycaret[models]` # - `pip install pycaret[tuner]` # - `pip install pycaret[mlops]` # - `pip install pycaret[parallel]` # - `pip install pycaret[test]` # In[44]: # check installed version import pycaret pycaret.__version__ # # πŸš€ Quick start # PyCaret’s Anomaly Detection Module is an unsupervised machine learning module that is used for identifying rare items, events, or observations that raise suspicions by differing significantly from the majority of the data. # # Typically, the anomalous items will translate to some kind of problems such as bank fraud, a structural defect, medical problems, or errors. # # PyCaret's Anomaly Detection module provides several pre-processing features to prepare the data for modeling through the `setup` function. It has over 10 ready-to-use algorithms and few plots to analyze the performance of trained models. # # A typical workflow in PyCaret's unsupervised module consist of following 6 steps in this order: # # **Setup** ➑️ **Create Model** ➑️ **Assign Labels** ➑️ **Analyze Model** ➑️ **Prediction** ➑️ **Save Model** # In[45]: # loading sample dataset from pycaret dataset module from pycaret.datasets import get_data data = get_data('anomaly') # ## Setup # This function initializes the training environment and creates the transformation pipeline. The setup function must be called before executing any other function. It takes one mandatory parameter only: data. All the other parameters are optional. # In[46]: # import pycaret anomaly and init setup from pycaret.anomaly import * s = setup(data, session_id = 123) # Once the setup has been successfully executed it shows the information grid containing experiment level information. # # - **Session id:** A pseudo-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.
#
# - **Original data shape:** Shape of the original data prior to any transformations.
#
# - **Transformed data shape:** Shape of data after transformations
#
# - **Numeric features :** The number of features considered as numerical.
#
# - **Categorical features :** The number of features considered as categorical.
# PyCaret has two set of API's that you can work with. (1) Functional (as seen above) and (2) Object Oriented API. # # With Object Oriented API instead of executing functions directly you will import a class and execute methods of class. # In[47]: # import AnomalyExperiment and init the class from pycaret.anomaly import AnomalyExperiment exp = AnomalyExperiment() # In[48]: # check the type of exp type(exp) # In[49]: # init setup on exp exp.setup(data, session_id = 123) # You can use any of the two method i.e. Functional or OOP and even switch back and forth between two set of API's. The choice of method will not impact the results and has been tested for consistency. # ## Create Model # # This function trains an unsupervised anomaly detection model. All the available models can be accessed using the models function. # In[50]: # train iforest model iforest = create_model('iforest') iforest # In[51]: # to check all the available models models() # ## Assign Model # This function assigns anomaly labels to the training data, given a trained model. # In[52]: iforest_anomalies = assign_model(iforest) iforest_anomalies # ## Analyze Model # You can use the `plot_model` function to analyzes the performance of a trained model on the test set. It may require re-training the model in certain cases. # In[53]: # tsne plot anomalies plot_model(iforest, plot = 'tsne') # In[54]: # check docstring to see available plots # help(plot_model) # An alternate to `plot_model` function is `evaluate_model`. It can only be used in Notebook since it uses ipywidget. # In[87]: evaluate_model(iforest) # ## Prediction # The `predict_model` function returns `Anomaly` and `Anomaly_Score` label as a new column in the input dataframe. This step may or may not be needed depending on the use-case. Some times clustering models are trained for analysis purpose only and the interest of user is only in assigned labels on the training dataset, that can be done using `assign_model` function. `predict_model` is only useful when you want to obtain cluster labels on unseen data (i.e. data that was not used during training the model). # In[56]: # predict on test set iforest_pred = predict_model(iforest, data=data) iforest_pred # The same function works for predicting the labels on unseen dataset. Let's create a copy of original data and drop the `Class variable`. We can then use the new data frame without labels for scoring. # ## Save Model # Finally, you can save the entire pipeline on disk for later use, using pycaret's `save_model` function. # In[57]: # save pipeline save_model(iforest, 'iforest_pipeline') # In[58]: # load pipeline loaded_iforest_pipeline = load_model('iforest_pipeline') loaded_iforest_pipeline # # πŸ‘‡ Detailed function-by-function overview # ## βœ… Setup # This function initializes the training environment and creates the transformation pipeline. The setup function must be called before executing any other function. It takes one mandatory parameter only: data. All the other parameters are optional. # In[59]: s = setup(data, session_id = 123) # To access all the variables created by the setup function such as transformed dataset, random_state, etc. you can use `get_config` method. # In[60]: # check all available config get_config() # In[61]: # lets access X_train_transformed get_config('X_train_transformed') # In[62]: # another example: let's access seed print("The current seed is: {}".format(get_config('seed'))) # now lets change it using set_config set_config('seed', 786) print("The new seed is: {}".format(get_config('seed'))) # All the preprocessing configurations and experiment settings/parameters are passed into the `setup` function. To see all available parameters, check the docstring: # In[63]: # help(setup) # In[64]: # init setup with bin_numeric_feature s = setup(data, session_id = 123, bin_numeric_features=['Col1']) # In[65]: # lets check the X_train_transformed to see effect of params passed get_config('X_train_transformed')['Col1'].hist() # Notice that `Col1` originally was a numeric feature with a continious distribution. After transformation it is now converted into categorical feature. We can also access non-transformed values using `get_config` and then compare the differences. # In[66]: get_config('X_train')['Col1'].hist() # ## βœ… Experiment Logging # PyCaret integrates with many different type of experiment loggers (default = 'mlflow'). To turn on experiment tracking in PyCaret you can set `log_experiment` and `experiment_name` parameter. It will automatically track all the metrics, hyperparameters, and artifacts based on the defined logger. # In[67]: # from pycaret.anomaly import * # s = setup(data, session_id = 123, log_experiment='mlflow', experiment_name='anomaly_project') # In[68]: # train iforest # iforest = create_model('iforest') # In[69]: # start mlflow server on localhost:5000 # !mlflow ui # By default PyCaret uses `MLFlow` logger that can be changed using `log_experiment` parameter. Following loggers are available: # # - mlflow # - wandb # - comet_ml # - dagshub # # Other logging related parameters that you may find useful are: # # - experiment_custom_tags # - log_plots # - log_data # - log_profile # # For more information check out the docstring of the `setup` function. # In[70]: # help(setup) # ## βœ… Create Model # This function trains an unsupervised anomaly detection model. All the available models can be accessed using the models function. # In[71]: # check all the available models models() # In[72]: # train iforest model iforest = create_model('iforest') # In[73]: iforest # In[74]: # train iforest with specific model parameter create_model('iforest', contamination = 0.1) # In[75]: # help(create_model) # ## βœ… Assign Model # This function assigns anomaly labels to the dataset for a given model. (1 = outlier, 0 = inlier). # In[76]: iforest_results = assign_model(iforest) iforest_results # In[77]: # help(assign_model) # ## βœ… Plot Model # In[78]: # tsne plot of anomalies plot_model(iforest, plot = 'tsne') # In[79]: # umap plot of anomalies (you need to install umap library for this separately) # plot_model(iforest, plot = 'umap') # In[80]: # help(plot_model) # ## βœ… Deploy Model # This function deploys the entire ML pipeline on the cloud. # # **AWS:** When deploying model on AWS S3, environment variables must be configured using the command-line interface. To configure AWS environment variables, type `aws configure` in terminal. The following information is required which can be generated using the Identity and Access Management (IAM) portal of your amazon console account: # # - AWS Access Key ID # - AWS Secret Key Access # - Default Region Name (can be seen under Global settings on your AWS console) # - Default output format (must be left blank) # # **GCP:** To deploy a model on Google Cloud Platform ('gcp'), the project must be created using the command-line or GCP console. Once the project is created, you must create a service account and download the service account key as a JSON file to set environment variables in your local environment. Learn more about it: https://cloud.google.com/docs/authentication/production # # **Azure:** To deploy a model on Microsoft Azure ('azure'), environment variables for the connection string must be set in your local environment. Go to settings of storage account on Azure portal to access the connection string required. # AZURE_STORAGE_CONNECTION_STRING (required as environment variable) # Learn more about it: https://docs.microsoft.com/en-us/azure/storage/blobs/storage-quickstart-blobs-python?toc=%2Fpython%2Fazure%2FTOC.json # In[81]: # deploy model on aws s3 # deploy_model(iforest, model_name = 'my_first_platform_on_aws', # platform = 'aws', authentication = {'bucket' : 'pycaret-test'}) # In[82]: # load model from aws s3 # loaded_from_aws = load_model(model_name = 'my_first_platform_on_aws', platform = 'aws', # authentication = {'bucket' : 'pycaret-test'}) # loaded_from_aws # ## βœ… Save / Load Model # This function saves the transformation pipeline and a trained model object into the current working directory as a pickle file for later use. # In[83]: # save model save_model(iforest, 'my_first_model') # In[84]: # load model loaded_from_disk = load_model('my_first_model') loaded_from_disk # ## βœ… Save / Load Experiment # This function saves all the experiment variables on disk, allowing to later resume without rerunning the setup function. # In[85]: # save experiment save_experiment('my_experiment') # In[86]: # load experiment from disk exp_from_disk = load_experiment('my_experiment', data=data) # In[ ]: