Run dataset based tests

Use the ValidMind Library’s run_test function to run built-in or custom tests that take any dataset or model as input. These tests generate 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 notebook, to understand the basics of how to find and describe all the available tests in the library before moving on to this advanced guide.

This interactive notebook provides a step-by-step guide for listing and filtering available tests, building a sample dataset, initializing the required ValidMind objects, running the 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 Library 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 Library, 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 — 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.

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

Test suites: Collections of tests designed to run together to automate and generate model documentation end-to-end for specific use-cases.

Example: The classifier_full_suite test suite runs tests from the tabular_dataset and classifier test suites to fully document the data and model sections for binary classification model use-cases.

Install the client library

The client library provides Python support for the ValidMind Library. 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 in to ValidMind.

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

List and filter available tests

Before we run a test, let’s find a suitable test for this demonstration. Let’s assume you want to generate the pearson correlation matrix for a dataset. A Pearson correlation matrix is a table that shows the Pearson correlation coefficients between several variables.

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 pearson correlation matrix:

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

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

test_id = "validmind.data_validation.PearsonCorrelationMatrix"
vm.tests.describe_test(test_id)

Since this test requires a dataset, it should throw an error if you were to run it without passing a dataset input:

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

Create a sample dataset

Now, let’s build a sample dataset so you can generate its pearson correlation matrix. The sklearn make_classification function can generate a random dataset for testing:

import pandas as pd
from sklearn.datasets import make_classification

X, y = make_classification(
    n_samples=10000,
    n_features=10,
    weights=[0.1],
    random_state=42,
)
X.shape
y.shape

df = pd.DataFrame(X, columns=[f"feature_{i}" for i in range(X.shape[1])])
df["target"] = y
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 for the sample df you created previously:

vm_dataset = vm.init_dataset(
    df,
    input_id="my_demo_dataset",
    target_column="target",
)

Run tests with the dataset

You can now call run_test with the new vm_dataset object as input:

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

This dataset can also be used for any other test that requires a dataset input.

  • Let’s try to find a class imbalance to understand the distribution of the target column in the dataset.
  • Class imbalance is a common problem in machine learning, particularly in classification tasks, where the number of instances (or data points) in each class isn’t evenly distributed across the available categories.

We’ll use list_tests again to showcase how to filter tests for tabular data:

sorted(vm.tests.list_tags())
vm.tests.list_tests(tags=["binary_classification", "tabular_data"])

Run a test that accepts parameters

The test ID for the class imbalance test is validmind.data_validation.ClassImbalance. If you describe this test you will find that it also accepts some parameters:

vm.tests.describe_test("validmind.data_validation.ClassImbalance")

The min_percent_threshold will allow you configure the threshold for an acceptable class imbalance.

  • Let’s run the test without any parameters to see its output using a default value for the threshold.
  • We also call the log method on the result to send the results of the tests to the ValidMind platform.
result = vm.tests.run_test(
    "validmind.data_validation.ClassImbalance",
    inputs={"dataset": vm_dataset},
)

result.log()

This test passes the pass-fail criteria with the default threshold of 10%.

  • Let’s try to run the test with a threshold of 20% to see if it fails. Notice the use of the ‘custom_threshold’ result_id in the test ID.
  • This allows you to submit individual results for the same test to the platform, as we’ll see in the next section.
result = vm.tests.run_test(
    "validmind.data_validation.ClassImbalance:custom_threshold",
    inputs={"dataset": vm_dataset},
    params={"min_percent_threshold": 20},
)

result.log()

Add test results to documentation

The previous result shows that the test didn’t pass the threshold of 20% for class imbalance. With these results logged, you can now add them to your model documentation:

  1. In the ValidMind Platform UI, go to the Documentation page for the model you registered earlier. (Need more help?

  2. Expand the 2.1. Data Description section.

  3. Hover between any existing content blocks to reveal the + button.

  4. Click on the + button and choose Test-Driven Block. This will open a dialog where you can select:

    1. Type: Threshold Test
    2. Threshold Test: Class Imbalance Custom Threshold Test
    • You can preview the result and then click Insert Block in the bottom-right corner to add it to the documentation.

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.

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.