%pip install -q validmind
Ongoing Monitoring for Application Scorecard
In this notebook, you’ll learn how to seamlessly monitor your production models using the ValidMind Platform.
We’ll walk you through the process of initializing the ValidMind Library, loading a sample dataset and model, and running a monitoring test suite to quickly generate documentation about your new data and model.
About ValidMind
ValidMind is a suite of tools for managing model risk, including risk associated with AI and statistical models.
You use the ValidMind Library to automate documentation, validation, monitoring tests, and then use the ValidMind Platform to collaborate on model documentation. Together, these products simplify model risk management, facilitate compliance with regulations and institutional standards, and enhance collaboration between yourself and model validators.
Before you begin
This notebook assumes you have basic familiarity with Python, including an understanding of how functions work. If you are new to Python, you can still run the notebook but we recommend further familiarizing yourself with the language.
If you encounter errors due to missing modules in your Python environment, install the modules with pip install
, and then re-run the notebook. For more help, refer to Installing Python Modules.
New to ValidMind?
If you haven’t already seen our Get started with the ValidMind Library, we recommend you explore the available resources for developers at some point. There, you can learn more about documenting models, find code samples, or read our developer reference.
Signing up is FREE — Register with ValidMind
Key concepts
Model documentation: A structured and detailed record pertaining to a model, encompassing key components such as its underlying assumptions, methodologies, data sources, inputs, performance metrics, evaluations, limitations, and intended uses. It serves to ensure transparency, adherence to regulatory requirements, and a clear understanding of potential risks associated with the model’s application.
Documentation template: Functions as a test suite and lays out the structure of model documentation, segmented into various sections and sub-sections. Documentation templates define the structure of your model documentation, specifying the tests that should be run, and how the results should be displayed.
Model monitoring documentation: A comprehensive and structured record of a production model, including key elements such as data sources, inputs, performance metrics, and periodic evaluations. This documentation ensures transparency and visibility of the model’s performance in the production environment.
Monitoring documentation template: Similar to documentation template, The monitoring documentation template functions as a test suite and lays out the structure of model monitoring documentation, segmented into various sections and sub-sections. Monitoring documentation templates define the structure of your model monitoring documentation, specifying the tests that should be run, and how the results should be displayed.
Tests: A function contained in the ValidMind Library, designed to run a specific quantitative test on the dataset or model. Tests are the building blocks of ValidMind, used to evaluate and document models and datasets, and can be run individually or as part of a suite defined by your model documentation template.
Custom tests: Custom tests are functions that you define to evaluate your model or dataset. These functions can be registered via the ValidMind Library to be used with the ValidMind Platform.
Inputs: Objects to be evaluated and documented in the ValidMind Library. They can be any of the following:
- model: A single model that has been initialized in ValidMind with
vm.init_model()
. - dataset: Single dataset that has been initialized in ValidMind with
vm.init_dataset()
. - models: A list of ValidMind models - usually this is used when you want to compare multiple models in your custom test.
- datasets: A list of ValidMind datasets - usually this is used when you want to compare multiple datasets in your custom test. See this example for more information.
Parameters: Additional arguments that can be passed when running a ValidMind test, used to pass additional information to a test, customize its behavior, or provide additional context.
Outputs: Custom tests can return elements like tables or plots. Tables may be a list of dictionaries (each representing a row) or a pandas DataFrame. Plots may be matplotlib or plotly figures.
Install the ValidMind Library
To install the library:
Initialize the ValidMind Library
ValidMind generates a unique code snippet for each registered model to connect with your developer environment. You initialize the ValidMind Library with this code snippet, which ensures that your documentation and tests are uploaded to the correct model when you run the notebook.
Get your code snippet
In a browser, log in to ValidMind.
In the left sidebar, navigate to Model Inventory and click + Register Model.
Enter the model details and click Continue. (Need more help?)
For example, to register a model for use with this notebook, select:
- Documentation template:
Binary classification
- Use case:
Marketing/Sales - Attrition/Churn Management
You can fill in other options according to your preference.
- Documentation template:
Go to Getting Started and click Copy snippet to clipboard.
Next, load your model identifier credentials from an .env
file or replace the placeholder with your own code snippet:
# Load your model identifier credentials from an `.env` file
%load_ext dotenv
%dotenv .env
# Or replace with your code snippet
import validmind as vm
vm.init(= "https://api.prod.validmind.ai/api/v1/tracking",
api_host = "...",
api_key = "...",
api_secret = "...",
model = True
monitoring )
Initialize the Python environment
Next, let’s import the necessary libraries and set up your Python environment for data analysis:
import xgboost as xgb
import numpy as np
from datetime import datetime, timedelta
from validmind.tests import run_test
from validmind.datasets.credit_risk import lending_club
from validmind.unit_metrics import list_metrics
from validmind.unit_metrics import describe_metric
from validmind.unit_metrics import run_metric
from validmind.api_client import log_metric
%matplotlib inline
Preview the monitoring template
A template predefines sections for your model monitoring documentation and provides a general outline to follow, making the documentation process much easier.
You will upload documentation and test results into this template later on. For now, take a look at the structure that the template provides with the vm.preview_template()
function from the ValidMind library and note the empty sections:
vm.preview_template()
Load the reference and monitoring datasets
The sample dataset used here is provided by the ValidMind library. For demonstration purposes we’ll use the training, test dataset splits as reference
and monitoring
datasets.
= lending_club.load_data(source="offline")
df df.head()
= lending_club.preprocess(df)
preprocess_df preprocess_df.head()
= lending_club.feature_engineering(preprocess_df)
fe_df fe_df.head()
Train the model
In this section, we focus on constructing and refining our predictive model. - We begin by dividing our data, which is based on Weight of Evidence (WoE) features, into training and testing sets (train_df
, test_df
). - With lending_club.split
, we employ a simple random split, randomly allocating data points to each set to ensure a mix of examples in both.
# Split the data
= lending_club.split(fe_df, test_size=0.2)
train_df, test_df
= train_df.drop(lending_club.target_column, axis=1)
x_train = train_df[lending_club.target_column]
y_train
= test_df.drop(lending_club.target_column, axis=1)
x_test = test_df[lending_club.target_column] y_test
# Define the XGBoost model
= xgb.XGBClassifier(
xgb_model =50,
n_estimators=42,
random_state=10
early_stopping_rounds
)
xgb_model.set_params(=["error", "logloss", "auc"],
eval_metric
)
# Fit the model
xgb_model.fit(
x_train,
y_train,=[(x_test, y_test)],
eval_set=False
verbose
)
# Compute probabilities
= xgb_model.predict_proba(x_train)[:, 1]
train_xgb_prob = xgb_model.predict_proba(x_test)[:, 1]
test_xgb_prob
# Compute binary predictions
= 0.3
cut_off_threshold = (train_xgb_prob > cut_off_threshold).astype(int)
train_xgb_binary_predictions = (test_xgb_prob > cut_off_threshold).astype(int) test_xgb_binary_predictions
Initialize the ValidMind datasets
Before you can run tests, you must first initialize a ValidMind dataset object using the init_dataset
function from the ValidMind (vm
) module.
This function takes a number of arguments:
dataset
— The raw dataset that you want to provide as input to tests.input_id
- A unique identifier that allows tracking what inputs are used when running each individual test.target_column
— A required argument if tests require access to true values. This is the name of the target column in the dataset.
With all datasets ready, you can now initialize training, reference(test) and monitor datasets (reference_df
and monitor_df
) created earlier into their own dataset objects using vm.init_dataset()
:
= vm.init_dataset(
vm_reference_ds =train_df,
dataset="reference_dataset",
input_id=lending_club.target_column,
target_column
)
= vm.init_dataset(
vm_monitoring_ds =test_df,
dataset="monitoring_dataset",
input_id=lending_club.target_column,
target_column )
Initialize a model object
You will also need to initialize a ValidMind model object (vm_model
) that can be passed to other functions for analysis and tests on the data. You simply intialize this model object with vm.init_model()
:
= vm.init_model(
vm_xgb_model
xgb_model,="xgb_model",
input_id )
Assign prediction values and probabilities to the datasets
With our model now trained, we’ll move on to assigning both the predictive probabilities coming directly from the model’s predictions, and the binary prediction after applying the cutoff threshold described in the previous steps. - These tasks are achieved through the use of the assign_predictions()
method associated with the VM dataset
object. - This method links the model’s class prediction values and probabilities to our VM train and test datasets.
vm_reference_ds.assign_predictions(=vm_xgb_model,
model=train_xgb_binary_predictions,
prediction_values=train_xgb_prob,
prediction_probabilities
)
vm_monitoring_ds.assign_predictions(=vm_xgb_model,
model=test_xgb_binary_predictions,
prediction_values=test_xgb_prob,
prediction_probabilities )
Compute credit risk scores
In this phase, we translate model predictions into actionable scores using probability estimates generated by our trained model.
= lending_club.compute_scores(train_xgb_prob)
train_xgb_scores = lending_club.compute_scores(test_xgb_prob)
test_xgb_scores
# Assign scores to the datasets
"xgb_scores", train_xgb_scores)
vm_reference_ds.add_extra_column("xgb_scores", test_xgb_scores) vm_monitoring_ds.add_extra_column(
Adding custom context to the LLM descriptions
To enable the LLM descriptions context, you need to set the VALIDMIND_LLM_DESCRIPTIONS_CONTEXT_ENABLED
environment variable to 1
. This will enable the LLM descriptions context, which will be used to provide additional context to the LLM descriptions. This is a global setting that will affect all tests.
import os
"VALIDMIND_LLM_DESCRIPTIONS_CONTEXT_ENABLED"] = "1"
os.environ[
= """
context FORMAT FOR THE LLM DESCRIPTIONS:
**<Test Name>** is designed to <begin with a concise overview of what the test does and its primary purpose,
extracted from the test description>.
The test operates by <write a paragraph about the test mechanism, explaining how it works and what it measures.
Include any relevant formulas or methodologies mentioned in the test description.>
The primary advantages of this test include <write a paragraph about the test's strengths and capabilities,
highlighting what makes it particularly useful for specific scenarios.>
Users should be aware that <write a paragraph about the test's limitations and potential risks.
Include both technical limitations and interpretation challenges.
If the test description includes specific signs of high risk, incorporate these here.>
**Key Insights:**
The test results reveal:
- **<insight title>**: <comprehensive description of one aspect of the results>
- **<insight title>**: <comprehensive description of another aspect>
...
Based on these results, <conclude with a brief paragraph that ties together the test results with the test's
purpose and provides any final recommendations or considerations.>
ADDITIONAL INSTRUCTIONS:
Present insights in order from general to specific, with each insight as a single bullet point with bold title.
For each metric in the test results, include in the test overview:
- The metric's purpose and what it measures
- Its mathematical formula
- The range of possible values
- What constitutes good/bad performance
- How to interpret different values
Each insight should progressively cover:
1. Overall scope and distribution
2. Complete breakdown of all elements with specific values
3. Natural groupings and patterns
4. Comparative analysis between datasets/categories
5. Stability and variations
6. Notable relationships or dependencies
Remember:
- Keep all insights at the same level (no sub-bullets or nested structures)
- Make each insight complete and self-contained
- Include specific numerical values and ranges
- Cover all elements in the results comprehensively
- Maintain clear, concise language
- Use only "- **Title**: Description" format for insights
- Progress naturally from general to specific observations
""".strip()
"VALIDMIND_LLM_DESCRIPTIONS_CONTEXT"] = context os.environ[
Monitoring data description
The Monitoring Data Description tests aim to provide a comprehensive statistical analysis of the monitoring dataset’s characteristics. These tests examine the basic statistical properties, identify any missing data patterns, assess data uniqueness, visualize numerical feature distributions, and evaluate feature relationships through correlation analysis.
The primary objective is to establish a baseline understanding of the monitoring data’s structure and quality, enabling the detection of any significant deviations from expected patterns that could impact model performance. Each test is designed to capture different aspects of the data, from univariate statistics to multivariate relationships, providing a foundation for ongoing data quality assessment in the production environment.
run_test("validmind.data_validation.DescriptiveStatistics:monitoring_data",
={
inputs"dataset": vm_monitoring_ds,
} ).log()
run_test("validmind.data_validation.MissingValues:monitoring_data",
={
inputs"dataset": vm_monitoring_ds,
},={
params"min_threshold": 1
} ).log()
run_test("validmind.data_validation.UniqueRows:monitoring_data",
={
inputs"dataset": vm_monitoring_ds,
},={
params"min_percent_threshold": 1
} ).log()
run_test("validmind.data_validation.TabularNumericalHistograms:monitoring_data",
={
inputs"dataset": vm_monitoring_ds,
}, ).log()
run_test("validmind.data_validation.PearsonCorrelationMatrix:monitoring_data",
={
inputs"dataset": vm_monitoring_ds,
} ).log()
run_test("validmind.data_validation.HighPearsonCorrelation:monitoring_data",
={
inputs"dataset": vm_monitoring_ds,
},={
params"feature_columns": vm_monitoring_ds.feature_columns,
"max_threshold": 0.5,
"top_n_correlations": 10
} ).log()
run_test("validmind.ongoing_monitoring.ClassImbalanceDrift",
={
inputs"datasets": [vm_reference_ds, vm_monitoring_ds],
},={
params"drift_pct_threshold": 1
}, ).log()
Target and feature drift
Next, the goal is to investigate the distributional characteristics of predictions and features to determine if the underlying data has changed. These tests are crucial for assessing the expected accuracy of the model.
- Target drift: We compare the dataset used for testing (reference data) with the monitoring data. This helps to identify any shifts in the target variable distribution.
- Feature drift: We compare the training dataset with the monitoring data. Since features were used to train the model, any drift in these features could indicate potential issues, as the underlying patterns that the model was trained on may have changed.
Next, we can examine the correlation between features and predictions. Significant changes in these correlations may trigger a deeper assessment.
run_test("validmind.model_validation.sklearn.PopulationStabilityIndex",
={
inputs"datasets": [vm_reference_ds, vm_monitoring_ds],
"model": vm_xgb_model,
}, ).log()
run_test("validmind.ongoing_monitoring.TargetPredictionDistributionPlot",
={
inputs"datasets": [vm_reference_ds, vm_monitoring_ds],
"model": vm_xgb_model,
},={
params"drift_pct_threshold": 5
}, ).log()
Now we want see difference in correlation pairs between model prediction and features.
run_test("validmind.ongoing_monitoring.PredictionCorrelation",
={
inputs"datasets": [vm_reference_ds, vm_monitoring_ds],
"model": vm_xgb_model,
},={
params"drift_pct_threshold": 5
}, ).log()
Finally for target drift, let’s plot each prediction value and feature grid side by side.
run_test("validmind.ongoing_monitoring.PredictionQuantilesAcrossFeatures",
={
inputs"datasets": [vm_reference_ds, vm_monitoring_ds],
"model": vm_xgb_model,
}, ).log()
Next, let’s add run a test to investigate how or if the features have drifted. In this instance we want to compare the training data with prediction data.
run_test("validmind.ongoing_monitoring.FeatureDrift",
={
inputs"datasets": [vm_reference_ds, vm_monitoring_ds],
"model": vm_xgb_model,
},={
params"psi_threshold": 0.2,
}, ).log()
Classification accuracy
We now evaluate the model’s predictive performance by comparing its behavior between reference and monitoring datasets. These tests analyze shifts in overall accuracy metrics, examine changes in the confusion matrix to identify specific classification pattern changes, and assess the model’s probability calibration across different prediction thresholds.
The primary objective is to detect any degradation in the model’s classification performance that might indicate reliability issues in production. The tests provide both aggregate performance metrics and detailed breakdowns of prediction patterns, enabling the identification of specific areas where the model’s accuracy might be deteriorating.
run_test("validmind.ongoing_monitoring.ClassificationAccuracyDrift",
={
inputs"datasets": [vm_reference_ds, vm_monitoring_ds],
"model": vm_xgb_model,
},={
params"drift_pct_threshold": 5,
}, ).log()
run_test("validmind.ongoing_monitoring.ConfusionMatrixDrift",
={
inputs"datasets": [vm_reference_ds, vm_monitoring_ds],
"model": vm_xgb_model,
},={
params"drift_pct_threshold": 5,
}, ).log()
run_test("validmind.ongoing_monitoring.CalibrationCurveDrift",
={
inputs"datasets": [vm_reference_ds, vm_monitoring_ds],
"model": vm_xgb_model,
},={
params"n_bins": 10,
"drift_pct_threshold": 10,
}, ).log()
Class discrimination
The following tests assess the model’s ability to effectively separate different classes in both reference and monitoring datasets. These tests analyze the model’s discriminative power by examining the separation between class distributions, evaluating changes in the ROC curve characteristics, comparing probability distribution patterns, and assessing cumulative prediction trends.
The primary objective is to identify any deterioration in the model’s ability to distinguish between classes, which could indicate a decline in model effectiveness. The tests examine both the overall discriminative capability and the granular patterns in prediction distributions, providing insights into whether the model maintains its ability to effectively differentiate between classes in the production environment.
run_test("validmind.ongoing_monitoring.ClassDiscriminationDrift",
={
inputs"datasets": [vm_reference_ds, vm_monitoring_ds],
"model": vm_xgb_model,
},={
params"drift_pct_threshold": 5,
}, ).log()
run_test("validmind.ongoing_monitoring.ROCCurveDrift",
={
inputs"datasets": [vm_reference_ds, vm_monitoring_ds],
"model": vm_xgb_model,
} ).log()
run_test("validmind.ongoing_monitoring.PredictionProbabilitiesHistogramDrift",
={
inputs"datasets": [vm_reference_ds, vm_monitoring_ds],
"model": vm_xgb_model,
},={
params"drift_pct_threshold": 10,
}, ).log()
run_test("validmind.ongoing_monitoring.CumulativePredictionProbabilitiesDrift",
={
inputs"datasets": [vm_reference_ds, vm_monitoring_ds],
"model": vm_xgb_model,
} ).log()
Scoring
Next we analyze the distribution and stability of credit scores across reference and monitoring datasets. These tests evaluate shifts in score distributions, examine changes in score band populations, and assess the relationship between scores and default rates.
The primary objective is to identify any significant changes in how the model assigns credit scores, which could indicate drift in risk assessment capabilities. The tests examine both the overall score distribution patterns and the specific performance within defined score bands, providing insights into whether the model maintains consistent and reliable risk segmentation.
run_test("validmind.ongoing_monitoring.ScorecardHistogramDrift",
={
inputs"datasets": [vm_reference_ds, vm_monitoring_ds],
},={
params"score_column": "xgb_scores",
"drift_pct_threshold": 20,
}, ).log()
run_test("validmind.ongoing_monitoring.ScoreBandsDrift",
={
inputs"datasets": [vm_reference_ds, vm_monitoring_ds],
"model": vm_xgb_model,
},={
params"score_column": "xgb_scores",
"score_bands": [500, 540, 570],
"drift_pct_threshold": 20,
}, ).log()
Model insights
run_test("validmind.model_validation.sklearn.PermutationFeatureImportance",
={
input_grid"dataset": [vm_reference_ds, vm_monitoring_ds],
"model": [vm_xgb_model]
} ).log()
run_test("validmind.model_validation.FeaturesAUC",
={
input_grid"model": [vm_xgb_model],
"dataset": [vm_reference_ds, vm_monitoring_ds],
}, ).log()
run_test("validmind.model_validation.sklearn.SHAPGlobalImportance",
={
input_grid"model": [vm_xgb_model],
"dataset": [vm_reference_ds, vm_monitoring_ds],
},={
params"kernel_explainer_samples": 10,
"tree_or_linear_explainer_samples": 200,
} ).log()
Diagnostic monitoring
run_test("validmind.model_validation.sklearn.WeakspotsDiagnosis",
={
inputs"datasets": [vm_reference_ds, vm_monitoring_ds],
"model": vm_xgb_model,
}, ).log()
run_test("validmind.model_validation.sklearn.OverfitDiagnosis",
={
inputs"model": vm_xgb_model,
"datasets": [vm_reference_ds, vm_monitoring_ds],
},={
params"cut_off_threshold": 0.04
} ).log()
Robustness monitoring
run_test("validmind.model_validation.sklearn.RobustnessDiagnosis",
={
inputs"datasets": [vm_reference_ds, vm_monitoring_ds],
"model": vm_xgb_model,
},={
params"scaling_factor_std_dev_list": [
0.1,
0.2,
0.3,
0.4,
0.5
],"performance_decay_threshold": 0.05
} ).log()
Performance history
In this section we showcase how to track and visualize the temporal evolution of key model performance metrics, including AUC, F1 score, precision, recall, and accuracy. For demonstration purposes, the section simulates historical performance data by introducing a gradual downward trend and random noise to these metrics over a specified time period. These tests are useful for analyzing the stability and trends in model performance indicators, helping to identify potential degradation or unexpected fluctuations in model behavior over time.
The main goal is to maintain a continuous record of model performance that can be used to detect gradual drift, sudden changes, or cyclical patterns in model effectiveness. This temporal monitoring approach provides early warning signals of potential issues and helps establish whether the model maintains consistent performance within acceptable boundaries throughout its deployment period.
= [metric for metric in list_metrics() if "classification" in metric]
metrics
for metric_id in metrics:
describe_metric(metric_id)
= run_metric(
result "validmind.unit_metrics.classification.ROC_AUC",
={
inputs"model": vm_xgb_model,
"dataset": vm_monitoring_ds,
},
)= result.metric auc
= run_metric(
result "validmind.unit_metrics.classification.Accuracy",
={
inputs"model": vm_xgb_model,
"dataset": vm_monitoring_ds,
},
)= result.metric accuracy
= run_metric(
result "validmind.unit_metrics.classification.Recall",
={
inputs"model": vm_xgb_model,
"dataset": vm_monitoring_ds,
},
)= result.metric recall
= run_metric(
f1 "validmind.unit_metrics.classification.F1",
={
inputs"model": vm_xgb_model,
"dataset": vm_monitoring_ds,
},
)= result.metric f1
= run_metric(
precision "validmind.unit_metrics.classification.Precision",
={
inputs"model": vm_xgb_model,
"dataset": vm_monitoring_ds,
},
)= result.metric precision
= 10
NUM_DAYS = datetime(2024, 1, 1) # Fixed date: January 1st, 2024
REFERENCE_DATE = REFERENCE_DATE - timedelta(days=NUM_DAYS)
base_date
# Initial values
= {
performance_metrics "AUC Score": auc,
"F1 Score": f1,
"Precision Score": precision,
"Recall Score": recall,
"Accuracy Score": accuracy
}
# Trend parameters
= 0.98 # Slight downward trend (multiply by 0.98 each step)
trend_factor = 0.02 # Random fluctuation of ±2%
noise_scale
for i in range(NUM_DAYS):
= base_date + timedelta(days=i)
recorded_at print(f"\nrecorded_at: {recorded_at}")
# Log each metric with trend and noise
for metric_name, base_value in performance_metrics.items():
# Apply trend and add random noise
= base_value * (trend_factor ** i)
trend = np.random.normal(0, noise_scale * base_value)
noise = max(0, min(1, trend + noise)) # Ensure value stays between 0 and 1
value
log_metric(=metric_name,
key=value,
value=recorded_at.isoformat()
recorded_at
)
print(f"{metric_name:<15}: {value:.4f}")