...
Table of Contents |
---|
Introduction
Monitoring incoming data for statistical drift is necessary to track whether assumptions made during model development are still valid in a production setting. For instance, a data scientist may assume that the values of a particular feature are normally distributed or the choice of encoding of a certain categorical variable may have been made with a certain multinomial distribution in mind. Tests should be run routinely against batches of live data and compared against the distribution of the training data to ensure that these assumptions are still valid, and if the tests fail, then appropriate alerts are raised for the data scientist or ModelOps engineer to investigate.
ModelOp Center provides a number of Drift monitors out of the box, but also allows you to write your own drift monitor. The subsequent sections describe how to add a drift monitor (assuming an out-of-the-box monitor) and the detailed makeup of a drift monitor for multiple types of models.
Adding Drift Monitors
As background on the terminology and concepts used in the below, please read the Monitoring Concepts section of the Model overview documentation.
To add a statistical monitor to your model, you will add an existing “associated” model to your model. .
Details
As the same data set may serve several models, you can write one drift detection model to associate Below are the steps to accomplish this. For tutorial purposes, these instructions use all out-of-the-box and publicly available content provided by ModelOp, focusing on the Consumer Linear Demo and its related assets.
Define thresholds for your model
As mentioned in the Monitoring Concepts article, ModelOp Center uses decision tables to define the thresholds within which the model should operate for the given monitor.
The first step is to define these thresholds. For this tutorial, we will leverage the example
Performance-test.dmn
decision table. This assumes that the out-of-the-box metrics function in the Consumer Credit Default example model is used, which outputs AUC, ROC, F1, amongst others. Specifically, this decision table ensures that the F1 and AUC from the Consumer Linear Demo model are within specification.Save the files locally to your machine.
Associate Monitor models to snapshot
Navigate to the specific model snapshot
Using the Associated Models widget, create a data drift association
Use the provided data and the DMN you made in step 2.
Use the provided data and the DMN you made in step 2.
Click Save.
The monitor “associated model” will be saved and now ready to run against the model’s specific snapshot
Schedule the Monitor
Schedule. Monitors can be scheduled to run using your preferred enterprise scheduling capability (Control-M, Airflow, Autosys, etc.)
While the details will depend on the specific scheduling software, at the highest level, the user simply needs to create a REST call to the ModelOp Center API. Here are the steps:
Obtain the Model snapshot’s unique ID, which can be obtained from the Model snapshot screen. Simply copy the ID from the URL bar:
Example:
Within the scheduler, configure the REST call to ModelOp Center’s automation engine to trigger the monitor for your model:
Obtain a valid auth token
Make a call to the ModelOp Center API to initiate the monitor
Example:
Monitoring Execution: once the scheduler triggers the monitoring job, the relevant model life cycle will initiated the specific monitor, which likely includes:
Preparing the monitoring job with all artifacts necessary to run the job
Creating the monitoring job
Parsing the results into viewable test results
Comparing the results against the thresholds in the decision table
Taking action, which could include creating a notification and/or opening up an incident in JIRA/ServiceNow/etc.
Viewing Monitoring Notifications
Typically, the model life cycle that runs the monitor will create notifications, such as:
A monitor has been started
A monitor has run successfully
A monitor’s output (model test) has failed
These Notifications can be viewed in the home page of ModelOp Center’s UI:
Viewing Monitoring Job Results
All monitor job results are persisted and can be viewed directly by clicking the specific “result” in the “Model Tests” section of the model snapshot page:
Statistical Monitor Details
While the types of statistical metrics used will vary based on the type of model (e.g. regression vs. classification), typically a small set of statistical metrics “monitors” can be created and then simply associated to several models. This association is made during the Model Lifecycle process. The drift model can compare the training data of the associated models to a given batch of data. statistical metrics monitor would require labeled data in order to output the required metrics.
The following is a simple example of how statistical metrics would be calculated for the Consumer Credit Default public model:
Code Block | ||
---|---|---|
| ||
import pandas as pd import numpy as np from scipysklearn.statsmetrics import ks_2samp from scipy.stats import binom_test # modelop.init def begin(roc_auc_score, roc_curve, f1_score, confusion_matrix #modelop.metrics def metrics(data): metrics = {} global train, numerical_featuresprep_data = preprocess(data) traindata = pd.read_csv('training_data.csv') numerical_features = train.select_dtypes(['int64', 'float64']).columnsconcat([data, prep_data], axis=1) data.loc[:, 'probabilities'] = prediction(data) data.loc[:, 'predictions'] = data.probabilities \ .apply(lambda x: threshold > x) \ pass # modelop.metrics def metrics.astype(int) if is_validated(data): ks_tests f1 = [ksf1_2sampscore(train.loc[:, feat], data.loc[:, feat]) \data.loan_status, data.predictions) cm = confusion_matrix(data.loan_status, data.predictions) labels = ['Fully Paid', 'Charged Off'] cm = matrix_to_dicts(cm, labels) fpr, tpr, thres = roc_curve(data.loan_status, data.probabilities) for featauc_val in numerical_features]= roc_auc_score(data.loan_status, data.probabilities) pvaluesrc = [{'fpr': x[0], 'tpr': x[1]} for x in ks_tests] ks_pvalues = dict(zip(numerical_features, pvalues)) list(zip(fpr, tpr))] metrics['f1_score'] = f1 metrics['confusion_matrix'] = cm metrics['auc'] = auc_val metrics['ROC'] = rc yield dict(pvalues=ks_pvalues) |
This drift model executes a two-sample Kolmogorov-Smirnov test between numerical features of the training data and the incoming batch and reports the p-values. If the p-values are sufficiently large (over 0.01 or 0.05), you can assume that the two samples are similar. If the p-values are small, you can assume that these samples are different and generate an alert.
If the training data is too large to fit in memory, you can save summary statistics about the training data and save those as, e.g., a pickle file and read those statistics in during the init function of the drift model. The metrics function can contain other statistical tests to compare those statistics to the statistics of the incoming batch.
Spark Models
A similar drift detection
metrics |
This statistical metrics monitor outputs a standard set of metrics including the F1 score, confusion matrix, AUC, and ROC. These are not the only metrics that are available. Rather, a user can add any additional metric--including custom-defined metrics with nested objects--in ModelOp Center as long as they are defined as key/value pairs. However, note that there are a few metrics that are pre-defined in ModelOp Center that will be plotted in the Test Results page based on the following keys in the key/value pairs:
“ROC” - the ROC curve will be plotted using the fpr and tpr values
“confusion_matrix” - a confusion matrix will be plotted based on the provided values
“shap” - a graph of the shap values by feature will be plotted based on the provided values
“bias” - a plot of ethical fairness metrics will be generated using the protected entities and related ethical fairness measures
Spark Models
A similar statistical evaluation method may be used for PySpark models with HDFS assets by parsing the HDFS asset URLs from the parameters of the metrics function. The following is a simple example:
...
This model uses a Spark MulticlassClassificationEvaluator
to determine the accuracy of the predictions generated by the titanic model.
Next Article: Ethical Fairness Monitoring >