• About
  • Get Started
  • Guides
  • ValidMind Library
    • ValidMind Library
    • Supported Models
    • QuickStart Notebook

    • TESTING
    • Run Tests & Test Suites
    • Test Descriptions
    • Test Sandbox (BETA)

    • CODE SAMPLES
    • All Code Samples · LLM · NLP · Time Series · Etc.
    • Download Code Samples · notebooks.zip
    • Try it on JupyterHub

    • REFERENCE
    • ValidMind Library Python API
  • Support
  • Training
  • Releases
  • Documentation
    • About ​ValidMind
    • Get Started
    • Guides
    • Support
    • Releases

    • Python Library
    • ValidMind Library

    • ValidMind Academy
    • Training Courses
  • Log In
    • Public Internet
    • ValidMind Platform · US1
    • ValidMind Platform · CA1

    • Private Link
    • Virtual Private ValidMind (VPV)

    • Which login should I use?
  1. Code samples
  2. Ongoing Monitoring
  3. Ongoing Monitoring for Application Scorecard

EU AI Act Compliance — Read our original regulation brief on how the EU AI Act aims to balance innovation with safety and accountability, setting standards for responsible AI use

  • ValidMind Library
  • Supported models

  • QuickStart
  • Quickstart for model documentation
  • Install and initialize ValidMind Library
  • Store model credentials in .env files

  • Model Development
  • 1 — Set up ValidMind Library
  • 2 — Start model development process
  • 3 — Integrate custom tests
  • 4 — Finalize testing & documentation

  • Model Validation
  • 1 — Set up ValidMind Library for validation
  • 2 — Start model validation process
  • 3 — Developing a challenger model
  • 4 — Finalize validation & reporting

  • Model Testing
  • Run tests & test suites
    • Add context to LLM-generated test descriptions
    • Configure dataset features
    • Document multiple results for the same test
    • Explore test suites
    • Explore tests
    • Dataset Column Filters when Running Tests
    • Load dataset predictions
    • Log metrics over time
    • Run individual documentation sections
    • Run documentation tests with custom configurations
    • Run tests with multiple datasets
    • Intro to Unit Metrics
    • Understand and utilize RawData in ValidMind tests
    • Introduction to ValidMind Dataset and Model Objects
    • Run Tests
      • Run dataset based tests
      • Run comparison tests
  • Test descriptions
    • Data Validation
      • ACFandPACFPlot
      • ADF
      • AutoAR
      • AutoMA
      • AutoStationarity
      • BivariateScatterPlots
      • BoxPierce
      • ChiSquaredFeaturesTable
      • ClassImbalance
      • DatasetDescription
      • DatasetSplit
      • DescriptiveStatistics
      • DickeyFullerGLS
      • Duplicates
      • EngleGrangerCoint
      • FeatureTargetCorrelationPlot
      • HighCardinality
      • HighPearsonCorrelation
      • IQROutliersBarPlot
      • IQROutliersTable
      • IsolationForestOutliers
      • JarqueBera
      • KPSS
      • LaggedCorrelationHeatmap
      • LJungBox
      • MissingValues
      • MissingValuesBarPlot
      • MutualInformation
      • PearsonCorrelationMatrix
      • PhillipsPerronArch
      • ProtectedClassesCombination
      • ProtectedClassesDescription
      • ProtectedClassesDisparity
      • ProtectedClassesThresholdOptimizer
      • RollingStatsPlot
      • RunsTest
      • ScatterPlot
      • ScoreBandDefaultRates
      • SeasonalDecompose
      • ShapiroWilk
      • Skewness
      • SpreadPlot
      • TabularCategoricalBarPlots
      • TabularDateTimeHistograms
      • TabularDescriptionTables
      • TabularNumericalHistograms
      • TargetRateBarPlots
      • TimeSeriesDescription
      • TimeSeriesDescriptiveStatistics
      • TimeSeriesFrequency
      • TimeSeriesHistogram
      • TimeSeriesLinePlot
      • TimeSeriesMissingValues
      • TimeSeriesOutliers
      • TooManyZeroValues
      • UniqueRows
      • WOEBinPlots
      • WOEBinTable
      • ZivotAndrewsArch
      • Nlp
        • CommonWords
        • Hashtags
        • LanguageDetection
        • Mentions
        • PolarityAndSubjectivity
        • Punctuations
        • Sentiment
        • StopWords
        • TextDescription
        • Toxicity
    • Model Validation
      • BertScore
      • BleuScore
      • ClusterSizeDistribution
      • ContextualRecall
      • FeaturesAUC
      • MeteorScore
      • ModelMetadata
      • ModelPredictionResiduals
      • RegardScore
      • RegressionResidualsPlot
      • RougeScore
      • TimeSeriesPredictionsPlot
      • TimeSeriesPredictionWithCI
      • TimeSeriesR2SquareBySegments
      • TokenDisparity
      • ToxicityScore
      • Embeddings
        • ClusterDistribution
        • CosineSimilarityComparison
        • CosineSimilarityDistribution
        • CosineSimilarityHeatmap
        • DescriptiveAnalytics
        • EmbeddingsVisualization2D
        • EuclideanDistanceComparison
        • EuclideanDistanceHeatmap
        • PCAComponentsPairwisePlots
        • StabilityAnalysisKeyword
        • StabilityAnalysisRandomNoise
        • StabilityAnalysisSynonyms
        • StabilityAnalysisTranslation
        • TSNEComponentsPairwisePlots
      • Ragas
        • AnswerCorrectness
        • AspectCritic
        • ContextEntityRecall
        • ContextPrecision
        • ContextPrecisionWithoutReference
        • ContextRecall
        • Faithfulness
        • NoiseSensitivity
        • ResponseRelevancy
        • SemanticSimilarity
      • Sklearn
        • AdjustedMutualInformation
        • AdjustedRandIndex
        • CalibrationCurve
        • ClassifierPerformance
        • ClassifierThresholdOptimization
        • ClusterCosineSimilarity
        • ClusterPerformanceMetrics
        • CompletenessScore
        • ConfusionMatrix
        • FeatureImportance
        • FowlkesMallowsScore
        • HomogeneityScore
        • HyperParametersTuning
        • KMeansClustersOptimization
        • MinimumAccuracy
        • MinimumF1Score
        • MinimumROCAUCScore
        • ModelParameters
        • ModelsPerformanceComparison
        • OverfitDiagnosis
        • PermutationFeatureImportance
        • PopulationStabilityIndex
        • PrecisionRecallCurve
        • RegressionErrors
        • RegressionErrorsComparison
        • RegressionPerformance
        • RegressionR2Square
        • RegressionR2SquareComparison
        • RobustnessDiagnosis
        • ROCCurve
        • ScoreProbabilityAlignment
        • SHAPGlobalImportance
        • SilhouettePlot
        • TrainingTestDegradation
        • VMeasure
        • WeakspotsDiagnosis
      • Statsmodels
        • AutoARIMA
        • CumulativePredictionProbabilities
        • DurbinWatsonTest
        • GINITable
        • KolmogorovSmirnov
        • Lilliefors
        • PredictionProbabilitiesHistogram
        • RegressionCoeffs
        • RegressionFeatureSignificance
        • RegressionModelForecastPlot
        • RegressionModelForecastPlotLevels
        • RegressionModelSensitivityPlot
        • RegressionModelSummary
        • RegressionPermutationFeatureImportance
        • ScorecardHistogram
    • Ongoing Monitoring
      • CalibrationCurveDrift
      • ClassDiscriminationDrift
      • ClassificationAccuracyDrift
      • ClassImbalanceDrift
      • ConfusionMatrixDrift
      • CumulativePredictionProbabilitiesDrift
      • FeatureDrift
      • PredictionAcrossEachFeature
      • PredictionCorrelation
      • PredictionProbabilitiesHistogramDrift
      • PredictionQuantilesAcrossFeatures
      • ROCCurveDrift
      • ScoreBandsDrift
      • ScorecardHistogramDrift
      • TargetPredictionDistributionPlot
    • Prompt Validation
      • Bias
      • Clarity
      • Conciseness
      • Delimitation
      • NegativeInstruction
      • Robustness
      • Specificity
  • Test sandbox beta

  • Notebooks
  • Code samples
    • Capital Markets
      • Quickstart for knockout option pricing model documentation
      • Quickstart for Heston option pricing model using QuantLib
    • Credit Risk
      • Document an application scorecard model
      • Document an application scorecard model
      • Document an application scorecard model
      • Document a credit risk model
      • Document an application scorecard model
    • Custom Tests
      • Implement custom tests
      • Integrate external test providers
    • Model Validation
      • Validate an application scorecard model
    • Nlp and Llm
      • Sentiment analysis of financial data using a large language model (LLM)
      • Summarization of financial data using a large language model (LLM)
      • Sentiment analysis of financial data using Hugging Face NLP models
      • Summarization of financial data using Hugging Face NLP models
      • Automate news summarization using LLMs
      • Prompt validation for large language models (LLMs)
      • RAG Model Benchmarking Demo
      • RAG Model Documentation Demo
    • Ongoing Monitoring
      • Ongoing Monitoring for Application Scorecard
      • Quickstart for ongoing monitoring of models with ValidMind
    • Regression
      • Document a California Housing Price Prediction regression model
    • Time Series
      • Document a time series forecasting model
      • Document a time series forecasting model

  • Reference
  • ValidMind Library Python API

On this page

  • About ValidMind
    • Before you begin
    • New to ValidMind?
    • Key concepts
  • Install the ValidMind Library
  • Initialize the ValidMind Library
    • Get your code snippet
  • Initialize the Python environment
    • Preview the monitoring template
  • Load the reference and monitoring datasets
  • Train the model
    • Initialize the ValidMind datasets
    • Initialize a model object
    • Assign prediction values and probabilities to the datasets
    • Compute credit risk scores
    • Adding custom context to the LLM descriptions
    • Monitoring data description
    • Target and feature drift
    • Classification accuracy
    • Class discrimination
    • Scoring
    • Model insights
    • Diagnostic monitoring
    • Robustness monitoring
    • Performance history
  • Edit this page
  • Report an issue
  1. Code samples
  2. Ongoing Monitoring
  3. Ongoing Monitoring for Application Scorecard

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 documentation on the ValidMind Library, we recommend you begin by exploring the available resources in this section. There, you can learn more about documenting models and running tests, as well as find code samples and our Python Library API reference.

For access to all features available in this notebook, create a free ValidMind account.

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:

%pip install -q validmind

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

  1. In a browser, log in to ValidMind.

  2. In the left sidebar, navigate to Model Inventory and click + Register Model.

  3. 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.

  4. 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(
  api_host = "https://api.prod.validmind.ai/api/v1/tracking",
  api_key = "...",
  api_secret = "...",
  model = "...",
  monitoring = True
)

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.

df = lending_club.load_data(source="offline")
df.head()
preprocess_df = lending_club.preprocess(df)
preprocess_df.head()
fe_df = lending_club.feature_engineering(preprocess_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
train_df, test_df = lending_club.split(fe_df, test_size=0.2)

x_train = train_df.drop(lending_club.target_column, axis=1)
y_train = train_df[lending_club.target_column]

x_test = test_df.drop(lending_club.target_column, axis=1)
y_test = test_df[lending_club.target_column]
# Define the XGBoost model
xgb_model = xgb.XGBClassifier(
    n_estimators=50, 
    random_state=42, 
    early_stopping_rounds=10
)
xgb_model.set_params(
    eval_metric=["error", "logloss", "auc"],
)

# Fit the model
xgb_model.fit(
    x_train, 
    y_train,
    eval_set=[(x_test, y_test)],
    verbose=False
)

# Compute probabilities
train_xgb_prob = xgb_model.predict_proba(x_train)[:, 1]
test_xgb_prob = xgb_model.predict_proba(x_test)[:, 1]

# Compute binary predictions
cut_off_threshold = 0.3
train_xgb_binary_predictions = (train_xgb_prob > cut_off_threshold).astype(int)
test_xgb_binary_predictions = (test_xgb_prob > cut_off_threshold).astype(int)

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_reference_ds = vm.init_dataset(
    dataset=train_df,
    input_id="reference_dataset",
    target_column=lending_club.target_column,
)

vm_monitoring_ds = vm.init_dataset(
    dataset=test_df,
    input_id="monitoring_dataset",
    target_column=lending_club.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_xgb_model = vm.init_model(
    xgb_model,
    input_id="xgb_model",
)

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(
    model=vm_xgb_model,
    prediction_values=train_xgb_binary_predictions,
    prediction_probabilities=train_xgb_prob,
)

vm_monitoring_ds.assign_predictions(
    model=vm_xgb_model,
    prediction_values=test_xgb_binary_predictions,
    prediction_probabilities=test_xgb_prob,
)

Compute credit risk scores

In this phase, we translate model predictions into actionable scores using probability estimates generated by our trained model.

train_xgb_scores = lending_club.compute_scores(train_xgb_prob)
test_xgb_scores = lending_club.compute_scores(test_xgb_prob)

# Assign scores to the datasets
vm_reference_ds.add_extra_column("xgb_scores", train_xgb_scores)
vm_monitoring_ds.add_extra_column("xgb_scores", test_xgb_scores)

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
os.environ["VALIDMIND_LLM_DESCRIPTIONS_CONTEXT_ENABLED"] = "1"

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()

os.environ["VALIDMIND_LLM_DESCRIPTIONS_CONTEXT"] = context

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.

  1. 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.
  2. 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.

metrics = [metric for metric in list_metrics() if "classification" in metric]

for metric_id in metrics:
    describe_metric(metric_id)
result = run_metric(
    "validmind.unit_metrics.classification.ROC_AUC",
    inputs={
        "model": vm_xgb_model,
        "dataset": vm_monitoring_ds,
    },
)
auc = result.metric
result = run_metric(
    "validmind.unit_metrics.classification.Accuracy",
    inputs={
        "model": vm_xgb_model,
        "dataset": vm_monitoring_ds,
    },
)
accuracy = result.metric
result = run_metric(
    "validmind.unit_metrics.classification.Recall",
    inputs={
        "model": vm_xgb_model,
        "dataset": vm_monitoring_ds,
    },
)
recall = result.metric
f1 = run_metric(
    "validmind.unit_metrics.classification.F1",
    inputs={
        "model": vm_xgb_model,
        "dataset": vm_monitoring_ds,
    },
)
f1 = result.metric
precision = run_metric(
    "validmind.unit_metrics.classification.Precision",
    inputs={
        "model": vm_xgb_model,
        "dataset": vm_monitoring_ds,
    },
)
precision = result.metric
NUM_DAYS = 10
REFERENCE_DATE = datetime(2024, 1, 1)  # Fixed date: January 1st, 2024
base_date = REFERENCE_DATE - timedelta(days=NUM_DAYS)


# Initial values
performance_metrics = {
    "AUC Score": auc,
    "F1 Score": f1,
    "Precision Score": precision,
    "Recall Score": recall,
    "Accuracy Score": accuracy
}

# Trend parameters
trend_factor = 0.98  # Slight downward trend (multiply by 0.98 each step)
noise_scale = 0.02   # Random fluctuation of ±2%


for i in range(NUM_DAYS):
    recorded_at = base_date + timedelta(days=i)
    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
        trend = base_value * (trend_factor ** i)
        noise = np.random.normal(0, noise_scale * base_value)
        value = max(0, min(1, trend + noise))  # Ensure value stays between 0 and 1
        
        log_metric(
            key=metric_name,
            value=value,
            recorded_at=recorded_at.isoformat()
        )
        
        print(f"{metric_name:<15}: {value:.4f}")
RAG Model Documentation Demo
Quickstart for ongoing monitoring of models with ValidMind

© Copyright 2025 ValidMind Inc. All Rights Reserved.

  • Edit this page
  • Report an issue
Cookie Preferences
  • validmind.com

  • Privacy Policy

  • Terms of Use