%pip install -q validmind
Run dataset based tests
Use the ValidMind Developer Framework’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:
- Find tests
- Initialize a ValidMind dataset
- Pass the dataset to the
run_test
fuction for any test that takes adataset
input
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 developer framework 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 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 nowKey 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.
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 Developer Framework. To install it:
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:
In a browser, log into the Platform UI.
In the left sidebar, navigate to Model Inventory and click + Register new model.
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.
- Documentation template:
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(="https://api.prod.validmind.ai/api/v1/tracking",
api_host="...",
api_key="...",
api_secret="...",
project )
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:
filter="PearsonCorrelationMatrix") vm.tests.list_tests(
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:
= "validmind.data_validation.PearsonCorrelationMatrix"
test_id 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
= make_classification(
X, y =10000,
n_samples=10,
n_features=[0.1],
weights=42,
random_state
)
X.shape
y.shape
= pd.DataFrame(X, columns=[f"feature_{i}" for i in range(X.shape[1])])
df "target"] = y
df[ 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.init_dataset(
vm_dataset
df,="my_demo_dataset",
input_id="target",
target_column )
Run tests with the dataset
You can now call run_test
with the new vm_dataset
object as input:
= vm.tests.run_test(
result
test_id,={"dataset": vm_dataset},
inputs )
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())
=["binary_classification", "tabular_data"]) vm.tests.list_tests(tags
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:
"validmind.data_validation.ClassImbalance") vm.tests.describe_test(
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.
= vm.tests.run_test(
result "validmind.data_validation.ClassImbalance",
={"dataset": vm_dataset},
inputs
)
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.
= vm.tests.run_test(
result "validmind.data_validation.ClassImbalance:custom_threshold",
={"dataset": vm_dataset},
inputs={"min_percent_threshold": 20},
params
)
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:
In the Platform UI, go to the Documentation page for the model you registered earlier.
Expand the 2.1. Data Description section.
Hover between any existing content blocks to reveal the + button.
Click on the + button and choose Test-Driven Block. This will open a dialog where you can select:
- Type:
Threshold Test
- 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.
- Type:
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.