• Documentation
    • About ​ValidMind
    • Get Started
    • Guides
    • Support
    • Releases

    • ValidMind Library
    • Python API
    • Public REST API

    • Training Courses
  • Log In
  1. Use library features
  2. Metrics
  3. Log metrics over time
  • ValidMind Library
  • Supported records and frameworks

  • Quickstart
  • Quickstart for documentation
  • Quickstart for validation
  • Install and initialize ValidMind
    • Install and initialize the library
    • Install and initialize the library for R
    • Use an HTTP proxy with the library
  • Store credentials in .env files

  • End-to-End Tutorials
  • Development
    • 1 — Set up ValidMind Library
    • 2 — Start the development process
    • 3 — Integrate custom tests
    • 4 — Finalize testing & documentation
  • Validation
    • 1 — Set up ValidMind Library for validation
    • 2 — Start the validation process
    • 3 — Developing a challenger
    • 4 — Finalize validation & reporting

  • How-To
  • Run tests & test suites
    • Explore tests
      • Explore tests
      • Explore test suites
    • Run tests
      • Run dataset-based tests
      • Run comparison tests
      • Configuring tests
        • Configure judge LLM and judge embeddings
        • Customize test result descriptions
        • Enable PII detection in tests
        • Dataset Column Filters when Running Tests
        • Run tests with multiple datasets
        • Understand and utilize RawData in ValidMind tests
      • Using tests in documentation
        • Document multiple results for the same test
        • Run individual documentation sections
        • Run documentation tests with custom configurations
    • Custom tests
      • Implement custom tests
      • Integrate external test providers
  • Use library features
    • Data and datasets
      • Introduction to ValidMind Dataset and Model Objects
      • Dataset inputs
        • Configure dataset features
        • Load dataset predictions
    • Metrics
      • Log metrics over time
      • Intro to Unit Metrics
    • Qualitative text
      • Generate qualitative text with the ValidMind library
    • Scoring
      • Intro to Assign Scores

  • Notebooks
  • Code samples
    • Agents
      • Document an agentic AI system
    • Capital markets
      • Quickstart for knockout option pricing model documentation
      • Quickstart for Heston option pricing model using QuantLib
    • Code explainer
      • Quickstart for model code documentation
    • Credit risk
      • Document an application scorecard model
      • Document an application scorecard model
      • Document a credit risk model
      • Document an application scorecard model
      • Document an Excel-based 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
    • Validation
      • Validate an application scorecard model

  • Reference
  • ​ValidMind test sandbox
  • ValidMind Library Python API
  • ValidMind Public REST API

On this page

  • About ValidMind
    • Before you begin
    • New to ValidMind?
    • Key concepts
  • Setting up
    • Install the ValidMind Library
    • Initialize the ValidMind Library
    • Initialize the Python environment
  • Load demo model
  • Logging metrics
    • Run unit metrics
    • Log unit metrics over time
    • Pass thresholds
    • Log multiple metrics with custom thresholds
    • Add acceptable performance flag
  • Next steps
    • Work with your documentation
    • Discover more learning resources
  • Upgrade ValidMind
  • Edit this page
  • Report an issue
  1. Use library features
  2. Metrics
  3. Log metrics over time

Log metrics over time

Learn how to track and visualize the temporal evolution of key record (model) performance metrics with ValidMind.

While this notebook uses a traditional binary classification model to demonstrate, the same principles apply to logging performance metrics over time for any record (model) type registered with ValidMind — including agentic AI systems, generative LLM applications, and beyond. For example:

  • Key model performance metrics such as AUC, F1 score, precision, recall, and accuracy, 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.
  • By monitoring these metrics systematically, teams can detect early warning signs of model drift and take proactive measures to maintain model reliability.
  • Unit metrics in ValidMind provide a standardized way to compute and track individual performance measures, making it easy to monitor specific aspects of model behavior.

Log metrics over time with the ValidMind Library's log_metric() function and visualize them in your documentation using the Metric Over Time block within the ValidMind Platform. This integration enables seamless tracking of record performance, supporting custom thresholds and facilitating the automation of alerts based on logged metrics.

Metrics over time are most commonly associated with the continued monitoring of a records's performance once it is deployed.

While you are able to add Metric Over Time blocks to documentation, we recommend first enabling ongoing monitoring for your record to maximize the potential of your performance data.

About ValidMind

ValidMind is a suite of tools for managing risk, including risk associated with AI and statistical models.

You use the ValidMind Library to automate documentation and validation tests, and then use the ValidMind Platform to collaborate on documentation. Together, these products simplify risk management, facilitate compliance with regulations and institutional standards, and enhance collaboration between yourself and 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 records such as 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, you'll need access to a ValidMind account.

Register with ValidMind

Key concepts

record: A tool tracked in the ValidMind inventory, such as a model. Records include traditional statistical models, legacy systems, artificial intelligence/machine learning models, large language models (LLMs), agentic AI systems, and other documentable items that benefit from oversight, testing, and lifecycle management.

model: SR 26-2 (which supersedes SR 11-7) defines a model as a "complex quantitative method, system, or approach that applies statistical, economic, or financial theories to process input data into quantitative estimates." Simple arithmetic, deterministic rule-based processes, or software without statistical, economic, or financial theories underpinning their design or use are generally outside SR 26-2’s definition of a model. Within ValidMind, a model is a type of record tracked in the inventory.

documentation, model documentation: A structured and detailed document pertaining to a record, encompassing key components such as its underlying assumptions, methodologies, data sources, inputs, performance metrics, evaluations, limitations, and intended uses. Within the realm of risk management, this documentation serves to ensure transparency, adherence to regulatory requirements, and a clear understanding of potential risks associated with the record's application.

document template: Lays out the structure of documents, segmented into various sections and sub-sections, and functions as a test suite specifying the tests that should be run, and how the results should be displayed. Document templates help automate your development, validation, monitoring, and other risk management processes. Document templates are available for default ValidMind document types as well as custom document types.

documentation template: A default ValidMind document type that serves as a standardized framework for developing and documenting records, including sections designated for record details, data descriptions, test results, and performance metrics. By outlining required documentation and recommended analyses, document templates ensure consistency and completeness across documentation and help guide developers through a systematic development process while promoting comparability and traceability of development outcomes.

test: A function contained in the ValidMind Library, designed to run a specific quantitative test on the dataset or record. Test results are logged to the ValidMind Platform, where they are attached to documents. Tests are the building blocks of ValidMind, used to evaluate and document records and datasets, and can be run individually or as part of a suite defined by your templates.

test suite: A collection of tests designed to run together to automate and generate documentation end-to-end for specific use cases. (Learn more: test_suites)

metric: A subset of tests that do not have thresholds. In the context of this notebook, metrics and tests can be thought of as interchangeable concepts.

custom test: Functions that you define to evaluate your record or dataset. These functions can be registered with the ValidMind Library to be used in the ValidMind Platform.

inputs: Objects to be evaluated and documented in the ValidMind Library. They can be any of the following:

  • model: A single record that has been initialized in ValidMind with init_model(). Despite the naming convention, model objects can be any type of record you want to test, document, validate, or monitor with ValidMind.
  • dataset: A single dataset that has been initialized in ValidMind with init_dataset().
  • models: A list of ValidMind records - usually this is used when you want to compare multiple records in your custom tests.
  • datasets: A list of ValidMind datasets - usually this is used when you want to compare multiple datasets in your custom tests. (Learn more: Run tests with multiple datasets)

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.

Setting up

Install the ValidMind Library

To install the library:

%pip install -q validmind

Initialize the ValidMind Library

Register sample model

Let's first register a sample record (model) for use with this notebook:

  1. In a browser, log in to ValidMind.

  2. In the left sidebar, select Inventory.

  3. Under the RECORD TYPE drop-down, select Model and click + Register Model. (Learn more: Register records in the inventory)

  4. Enter the model details and click Next > to continue to assignment of inventory record stakeholders.

  5. Select your own name under the RECORD OWNER drop-down.

  6. Click Register Model to add the model to your inventory.

Apply documentation template

Once you've registered your model, let's select a documentation template. A template predefines sections for your documentation and provides a general outline to follow, making the documentation process much easier.

  1. In the left sidebar that appears for your model, click Documents and select Development.

    If you cannot locate your Development document, make sure Development type documents are enabled for model records and create a new document. (Learn more: Manage documents)

  2. Under TEMPLATE, select Credit Risk Scorecard.

  3. Click Use Template to apply the template.

Get your code snippet

Initialize the ValidMind Library with the code snippet unique to each record per document, ensuring your test results are uploaded to the correct record and automatically populated in the right document in the ValidMind Platform when you run the Library.

  1. On the left sidebar that appears for your model, select Getting Started and select Development from the DOCUMENT drop-down menu.

  2. Click Copy snippet to clipboard.

  3. 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="...",
    # api_key="...",
    # api_secret="...",
    # model="...",
    document="documentation",
)

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.unit_metrics import list_metrics, describe_metric, run_metric
from validmind.api_client import log_metric

%matplotlib inline

Load demo model

We'll use a classification model trained on customer churn data to demonstrate ValidMind's metric logging capabilities.

  • We'll employ a built-in classification dataset, process it through train-validation-test splits, and train an XGBoost classifier.
  • The trained model and datasets are then initialized in ValidMind's framework, enabling us to track and monitor various performance metrics in the following sections.
# Import the sample dataset from the library

from validmind.datasets.classification import customer_churn

print(
    f"Loaded demo dataset with: \n\n\t• Target column: '{customer_churn.target_column}' \n\t• Class labels: {customer_churn.class_labels}"
)

raw_df = customer_churn.load_data()
raw_df.head()
train_df, validation_df, test_df = customer_churn.preprocess(raw_df)

x_train = train_df.drop(customer_churn.target_column, axis=1)
y_train = train_df[customer_churn.target_column]
x_val = validation_df.drop(customer_churn.target_column, axis=1)
y_val = validation_df[customer_churn.target_column]

model = xgb.XGBClassifier(early_stopping_rounds=10)
model.set_params(
    eval_metric=["error", "logloss", "auc"],
)
model.fit(
    x_train,
    y_train,
    eval_set=[(x_val, y_val)],
    verbose=False,
)

Once the datasets and model are prepared for validation, let's initialize the ValidMind dataset and model, specifying features and targets columns.

  • The property input_id allows users to uniquely identify each dataset and model.
  • This allows for the creation of multiple versions of datasets and models, enabling us to compute metrics by specifying which versions we want to use as inputs.
vm_raw_dataset = vm.init_dataset(
    dataset=raw_df,
    input_id="raw_dataset",
    target_column=customer_churn.target_column,
    class_labels=customer_churn.class_labels,
)

vm_train_ds = vm.init_dataset(
    dataset=train_df,
    input_id="train_dataset",
    target_column=customer_churn.target_column,
)

vm_test_ds = vm.init_dataset(
    dataset=test_df, input_id="test_dataset", target_column=customer_churn.target_column
)

# Initialize the ValidMind model object wrapper so that it can be passed as input to tests or test suites
# ValidMind model objects can be any type of record you want to test, document, validate, or monitor
vm_model = vm.init_model(
    model,
    input_id="model",
)

We can now use the assign_predictions() method from the Dataset object to link existing predictions to any model.

If no prediction values are passed, the method will compute predictions automatically:

vm_train_ds.assign_predictions(
    model=vm_model,
)

vm_test_ds.assign_predictions(
    model=vm_model,
)

Logging metrics

Next, we'll use ValidMind to track the temporal evolution of key model performance metrics.

We'll set appropriate thresholds for each metric, enable automated alerting when performance drifts beyond acceptable boundaries, and demonstrate how these thresholds can be customized based on business requirements and risk tolerance levels.

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

for metric_id in metrics:
    describe_metric(metric_id)

Run unit metrics

Compute individual metrics using ValidMind's unit metrics — single-value metrics that can be computed on a dataset and model. Use the run_metric() function from the validmind.unit_metrics module to calculate these metrics.

The run_metric() function has a signature similar to run_test() from the validmind.tests module, but is specifically designed for unit metrics and takes the following arguments:

  • metric_id: The unique identifier for the metric (for example, validmind.unit_metrics.classification.ROC_AUC)
  • inputs: A dictionary containing the input dataset and model or their respective input IDs
  • params: A dictionary containing keyword arguments for the unit metric (optional, accepts any kwargs from the underlying sklearn implementation)

run_metric() returns and displays a result object similar to a regular ValidMind test, but only shows the unit metric value. While this result object has a .log() method for logging to the ValidMind Platform, in this use case we'll use unit metrics to compute performance metrics and then log them over time using the log_metric() function from the validmind.api_client module.

result = run_metric(
    "validmind.unit_metrics.classification.ROC_AUC",
    inputs={
        "model": vm_model,
        "dataset": vm_test_ds,
    },
)
auc = result.metric
result = run_metric(
    "validmind.unit_metrics.classification.Accuracy",
    inputs={
        "model": vm_model,
        "dataset": vm_test_ds,
    },
)
accuracy = result.metric
result = run_metric(
    "validmind.unit_metrics.classification.Recall",
    inputs={
        "model": vm_model,
        "dataset": vm_test_ds,
    },
)
recall = result.metric
f1 = run_metric(
    "validmind.unit_metrics.classification.F1",
    inputs={
        "model": vm_model,
        "dataset": vm_test_ds,
    },
)
f1 = result.metric
precision = run_metric(
    "validmind.unit_metrics.classification.Precision",
    inputs={
        "model": vm_model,
        "dataset": vm_test_ds,
    },
)
precision = result.metric

Log unit metrics over time

Using the log_metric() function from the validmind.api_client module, let's log the unit metrics over time. This function takes the following arguments:

  • key: The name of the metric to log
  • value: The value of the metric to log
  • recorded_at: The timestamp of the metric to log — useful for logging historic predictions
  • thresholds: A dictionary containing the thresholds for the metric to log
  • params: A dictionary containing the keyword arguments for the unit metric (in this case, none are required, but we can pass any kwargs that the underlying sklearn implementation accepts)
log_metric(
    key="AUC Score",
    value=auc,
    # If `recorded_at` is not included, the time at function run is logged
    recorded_at=datetime(2024, 1, 1), 
)

To visualize the logged metric, we'll use the Metrics Over Time block in the ValidMind Platform:

  • After adding this visualization block to your documentation or ongoing monitoring report (as shown in the image below), you'll be able to review your logged metrics plotted over time.
  • In this example, since we've only logged a single data point, the visualization shows just one measurement.
  • As you continue logging metrics, the graph will populate with more points, enabling you to track trends and patterns.

Metric Over Time block AUC Score

Pass thresholds

We can pass thresholds to the log_metric() function to enhance the metric over time:

  • This is useful for visualizing the metric over time and identifying potential issues.
  • The metric visualization component provides a dynamic way to monitor and contextualize metric values through customizable thresholds.
  • These thresholds appear as horizontal reference lines on the chart.
  • The system always displays the most recent threshold configuration, meaning that if you update threshold values in your client application, the visualization will reflect these changes immediately.

When a metric is logged without thresholds or with an empty threshold dictionary, the reference lines gracefully disappear from the chart, though the metric line itself remains visible.

Thresholds are highly flexible in their implementation. You can define them with any meaningful key names (such as low_risk, maximum, target, or acceptable_range) in your metric data, and the visualization will adapt accordingly.

log_metric(
    key="AUC Score",
    value=auc,
    recorded_at=datetime(2024, 1, 1),
    thresholds={
        "min_auc": 0.7,
    }
)

AUC Score

AUC Score
log_metric(
    key="AUC Score",
    value=auc,
    recorded_at=datetime(2024, 1, 1),
    thresholds={
        "high_risk": 0.6,
        "medium_risk": 0.7,
        "low_risk": 0.8,
    }
)

AUC Score

AUC Score

Log multiple metrics with custom thresholds

The following code snippet shows an example of how to set up and log multiple performance metrics with custom thresholds for each metric:

  • Using AUC, F1, Precision, Recall, and Accuracy scores as examples, it demonstrates how to define different risk levels (high, medium, low) appropriate for each metric's expected range.
  • The code simulates 10 days of metric history by applying a gradual decay and random noise to help visualize how metrics might drift over time in a production environment.
NUM_DAYS = 10
REFERENCE_DATE = datetime(2024, 1, 1)  # Fixed date: January 1st, 2024
base_date = REFERENCE_DATE - timedelta(days=NUM_DAYS)

# Initial values with their specific thresholds
performance_metrics = {
    "AUC Score": {
        "value": auc,
        "thresholds": {
            "high_risk": 0.7,
            "medium_risk": 0.8,
            "low_risk": 0.9,
        }
    },
    "F1 Score": {
        "value": f1,
        "thresholds": {
            "high_risk": 0.5,
            "medium_risk": 0.6,
            "low_risk": 0.7,
        }
    },
    "Precision Score": {
        "value": precision,
        "thresholds": {
            "high_risk": 0.6,
            "medium_risk": 0.7,
            "low_risk": 0.8,
        }
    },
    "Recall Score": {
        "value": recall,
        "thresholds": {
            "high_risk": 0.4,
            "medium_risk": 0.5,
            "low_risk": 0.6,
        }
    },
    "Accuracy Score": {
        "value": accuracy,
        "thresholds": {
            "high_risk": 0.75,
            "medium_risk": 0.8,
            "low_risk": 0.85,
        }
    }
}

# Trend parameters
trend_factor = 0.98  # Slight downward trend
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, metric_info in performance_metrics.items():
        base_value = metric_info["value"]
        thresholds = metric_info["thresholds"]
        
        # 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(),
            thresholds=thresholds
        )
        
        print(f"{metric_name:<15}: {value:.4f} (Thresholds: {thresholds})")

AUC Score Accuracy Score Precision Score Recall Score F1 Score

Add acceptable performance flag

The passed parameter in the log_metric() function allows you to explicitly mark whether a specific metric value should be considered "Satisfactory" or "Requires Attention": - When passed=True: A green "Satisfactory" badge appears on the chart, indicating the metric value meets your acceptance criteria. - When passed=False: A yellow "Requires Attention" badge appears, highlighting potential concerns that may require investigation.

In the example below, the passed=True parameter adds a green "Satisfactory" badge to the GINI Score metric visualization, instantly indicating that the 0.75 value meets acceptable performance standards by being above the medium_risk threshold of 0.6:

log_metric(
    key="GINI Score",
    value=0.75,
    recorded_at=datetime(2025, 6, 7),
    thresholds = {
        "high_risk": 0.5,
        "medium_risk": 0.6,
        "low_risk": 0.8,
    },
    passed=True
)

GINI Score

GINI Score

In this example, the passed=False parameter adds a yellow "Requires Attention" badge to the GINI Score metric visualization, immediately highlighting that the value of 0.5 fails to meet acceptable performance standards by not exceeding the medium_risk threshold of 0.6:

log_metric(
    key="GINI Score",
    value=0.5,
    recorded_at=datetime(2025, 6, 9),
    thresholds = {
        "high_risk": 0.5,
        "medium_risk": 0.6,
        "low_risk": 0.8,
    },
    passed=False
)

GINI Score

GINI Score

Here, a custom function passed_fn determines the badge status automatically, displaying a green "Satisfactory" badge for the 0.65 GINI Score because it exceeds the medium_risk threshold of 0.6, enabling programmatic evaluation of metric performance based on predefined business rules:

gini = 0.65

thresholds = {
    "high_risk": 0.5,
    "medium_risk": 0.6,
    "low_risk": 0.8,
}

def passed_fn(value):
    return value > thresholds["medium_risk"]

log_metric(
    key="GINI Score",
    value=gini, 
    recorded_at=datetime(2025, 6, 10),
    thresholds=thresholds,
    passed=passed_fn(gini)
)

GINI Score

GINI Score

Next steps

You can look at the results of this test suite right in the notebook where you ran the code, as you would expect. But there is a better way — use the ValidMind Platform to work with your documentation.

Work with your documentation

  1. From the Inventory in the ValidMind Platform, go to the model you registered earlier. (Learn more: Working with the inventory)

  2. In the left sidebar that appears for your model, click Development under Documents.

What you see is the full draft of your documentation in a more easily consumable version. From here, you can make qualitative edits to documentation, view guidelines, collaborate with validators, and submit your documentation for approval when it's ready. (Learn more: Working with documentation)

Discover more learning resources

We also offer many interactive notebooks to help you use the ValidMind Library to streamline your work:

  • Run tests & test suites
  • Use ValidMind Library features
  • Code samples by use case

Or, visit our documentation to learn more about ValidMind.

Upgrade ValidMind

After installing ValidMind, you’ll want to periodically make sure you are on the latest version to access any new features and other enhancements.

Retrieve the information for the currently installed version of ValidMind:

%pip show validmind

If the version returned is lower than the version indicated in our production open-source code, restart your notebook and run:

%pip install --upgrade validmind

You may need to restart your kernel after running the upgrade package for changes to be applied.


Copyright © 2023-2026 ValidMind Inc. All rights reserved.
Refer to LICENSE for details.
SPDX-License-Identifier: AGPL-3.0 AND ValidMind Commercial

Load dataset predictions
Intro to Unit Metrics
  • ValidMind Logo
    ©
    Copyright 2026 ValidMind Inc.
    All Rights Reserved.
    Cookie preferences
    Legal
  • Get started
    • Development
    • Validation
    • Setup & admin
  • Guides
    • Access
    • Configuration
    • Integrations
    • Workflows
    • Inventory
    • Documents & templates
    • Documentation
    • Validation
    • Reporting
    • Monitoring
    • Attestation
  • ValidMind Library
    • Quickstarts
    • Development tutorial
    • Validation tutorial
    • Run tests & test suites
    • Use library features
    • Code samples
    • Python API
    • Public REST API
  • Training
    • Learning paths
    • Courses
    • Videos
  • Support
    • Troubleshooting
    • FAQ
    • Get help
  • Edit this page
  • Report an issue
  • Community
    • GitHub
    • LinkedIn
    • Events
    • Blog