Run comparison tests

Use the ValidMind Developer Framework’s run_test function to run built-in or custom tests that take any combination of datasets or models as inputs. Comparison tests allow you to run existing test over different groups of inputs and produces a single consolidated list of outputs in the form of text, tables, and images that get populated in model documentation.

You’ll learn how to:

We recommended that you first complete the Explore tests and the Run dataset based tests notebooks to understand the basics of how to find and describe all the available tests in the developer framework and how to run tests before moving on to this guide.

This interactive notebook provides a step-by-step guide for listing and filtering available tests, building a sample dataset, training a model, initializing the required ValidMind objects, running a comparison test, and then logging the results to ValidMind.

Contents

About ValidMind

ValidMind is a platform for managing model risk, including risk associated with AI and statistical models.

You use the ValidMind Developer Framework to automate documentation and validation tests, and then use the ValidMind AI Risk Platform UI 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 Developer Framework, we recommend you begin by exploring the available resources in this section. There, you can learn more about documenting models, find code samples, or read our developer reference.

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

Signing up is FREE — Sign up now

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.

Tests: A function contained in the ValidMind Developer Framework, 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 with ValidMind to be used in the platform.

Inputs: Objects to be evaluated and documented in the ValidMind framework. 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 client library

The client library provides Python support for the ValidMind Developer Framework. To install it:

%pip install -q validmind

Initialize the client library

ValidMind generates a unique code snippet for each registered model to connect with your developer environment. You initialize the client 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 into the Platform UI.

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

  3. Enter the model details below and click Continue. (Need more help?)

    • Documentation template: Binary Classification
    • Use case: Marketing - Attrition/Churn Management

    You can fill in the other options according to your preference.

  4. Go to Getting Started and click Copy snippet to clipboard.

Next, replace this placeholder with your own code snippet:

# 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="...",
    project="...",
)

List and filter available tests

Before we run a comparison test, let’s find a suitable test for this demonstration. Let’s assume you want to evaluate the performance results for a model.

In the Explore tests notebook, we learned how to pass a filter to the list_tests function. We’ll do the same here to find the test ID for the confusion matrix:

vm.tests.list_tests(filter="ClassifierPerformance")

From the output, you can see that the test ID for the pearson correlation matrix is validmind.model_validation.sklearn.ClassifierPerformance. The describe_test function gives you more information about the test, including its Required Inputs:

test_id = "validmind.model_validation.sklearn.ClassifierPerformance"
vm.tests.describe_test(test_id)

Since this test requires a dataset and a model , it should throw an error if you were to run it without passing any of those inputs:

try:
    vm.tests.run_test(test_id)
except Exception as e:
    print(e)

Load the sample dataset and run a model test

The sample dataset used here is provided by the ValidMind library. To be able to use it, you need to import the dataset and load it into a pandas DataFrame, a two-dimensional tabular data structure that makes use of rows and columns:

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

Initialize a ValidMind dataset

ValidMind dataset objects provide a wrapper to any type of dataset (NumPy, Pandas, Polars, etc.) so that tests can run transparently regardless of the underlying library. A VM dataset object can be created 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.

Below you can see how to initialize a VM dataset from a Pandas dataset. Since we are going to train a model and run some tests on it, we will create a dataset split from raw_df and initialize a VM dataset for the training and test datasets, which will be used for running comparison tests:

# The test dataset will be used to evaluate the model's performance
train_df, validation_df, test_df = customer_churn.preprocess(raw_df)

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

Train a sample XGBoost model

In the following code snippet you will train an XGBoost model using default parameters. The resulting model object will be passed to the init_model to initialize a ValidMind model object.

import xgboost as xgb

%matplotlib inline

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

Initialize a ValidMind model

Now, you can 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_model_xgb = vm.init_model(
    model,
    input_id="xgboost",
)

Assign predictions to the datasets

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_xgb)
vm_test_ds.assign_predictions(model=vm_model_xgb)

Run the test with one model

You can now call run_test with the new vm_test_ds and vm_model_xgb objects as inputs:

result = vm.tests.run_test(
    test_id,
    inputs={
        "dataset": vm_test_ds,
        "model": vm_model_xgb,
    },
)

Run comparison tests

It is possible to run the same ClassifierPerformance test with multiple models. You could call the run_test() function multiple times passing different inputs, but you can also pass an input_grid object that allows you run a single test for a combination of models and datasets.

As an example, you will train 4 models and run the ClassifierPerformance test for all of them using a single run_test() call. The input_grid object is a dictionary where the keys are the test input identifier and the values are a list of inputs to be used in the test. The following code snippet shows how to run the test for our 4 models:

input_grid = {
    'model': [vm_model_xgb, vm_model_rf, vm_model_lr, vm_model_dt],
    'dataset': [vm_test_ds]
}

This input_grid definition will run the ClassifierPerformance test for the following 4 groups of inputs:

  1. vm_model_xgb and vm_test_ds
  2. vm_model_rf and vm_test_ds
  3. vm_model_lr and vm_test_ds
  4. vm_model_dt and vm_test_ds

Now, let’s train the 3 other models and run the test for all of them:

from sklearn.ensemble import RandomForestClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.tree import DecisionTreeClassifier

model_rf = RandomForestClassifier()
model_rf.fit(x_train, y_train)

vm_model_rf = vm.init_model(
    model_rf,
    input_id="random_forest",
)

model_lr = LogisticRegression()
model_lr.fit(x_train, y_train)

vm_model_lr = vm.init_model(
    model_lr,
    input_id="logistic_regression",
)

model_dt = DecisionTreeClassifier()
model_dt.fit(x_train, y_train)

vm_model_dt = vm.init_model(
    model_dt,
    input_id="decision_tree",
)

You will also need to assign the predictions to the test dataset for the other models:

vm_test_ds.assign_predictions(model=vm_model_rf)
vm_test_ds.assign_predictions(model=vm_model_lr)
vm_test_ds.assign_predictions(model=vm_model_dt)

Run a comparison test with multiple models

Now you can run the test with the input_grid object. Note that we’re adding a small extra identifier to the test ID to differentiate the results in the documentation. This is optional, but it can be useful to differentiate the results when you have multiple tests with the same ID.

perf_comparison_result = vm.tests.run_test(
    "validmind.model_validation.sklearn.ClassifierPerformance:all_models",
    input_grid={
        "dataset": [vm_test_ds],
        "model": [vm_model_xgb, vm_model_rf, vm_model_lr, vm_model_dt],
    },
)

Run a comparison test with multiple datasets

Similarly, you can run a comparison test for multiple datasets, or even multiple datasets and models simultaneously. The input_grid object can be used to run the test for all possible combinations of inputs and the run_test() function will try to combine all results in a single output.

Let’s run a test that plots the ROC curves for the training and test datasets side by side. This is a common scenario when you want to compare the performance of a model on the training and test datasets and visually assess how much performance is lost in the test dataset.

roc_curve_result = vm.tests.run_test(
    "validmind.model_validation.sklearn.ROCCurve:train_vs_test",
    input_grid={
        "dataset": [vm_train_ds, vm_test_ds],
        "model": [vm_model_xgb],
    },
)

Add test results to documentation

Using the .log() method of a result object, you can log the results of a test to the model documentation. This method takes an optional section argument that specifies where the results should be logged in the documentation. The section should be a string that matches the title of a section in the documentation template.

You will log these results in the model_evaluation section of the documentation. After logging the results, you can view the updated documentation in the ValidMind platform following these steps:

  1. In the Platform UI, go to the Documentation page for the model you registered earlier.

  2. Expand the 3.2. Model Evaluation section.

  3. View the results of the tests you just ran at the end of the section.

perf_comparison_result.log(section_id="model_evaluation")
roc_curve_result.log(section_id="model_evaluation")

Next steps

While you can look at the results of this test suite right in the notebook where you ran the code, there is a better way — expand the rest of your documentation in the platform UI and take a look around.

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

Discover more learning resources

In an upcoming companion notebook, you’ll learn how to run tests that require a dataset and model as inputs. This will allow you to generate documentation for model evaluation tests such as ROC-AUC, F1 score, etc.

We also offer many other interactive notebooks to help you document models:

Or, visit our documentation to learn more about ValidMind.