%pip install -q validmind
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:
- 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 ValidMind 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 suite of tools 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 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 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.
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 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.
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 ValidMind Library
To install the library:
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
In a browser, log in to ValidMind.
In the left sidebar, navigate to Model Inventory and click + Register Model.
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.
- Documentation template:
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="...",
# 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:
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 ValidMind 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 ValidMind Platform, go to the Documentation page for the model you registered earlier. (Need more help?
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 ValidMind Platform 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
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.