%pip install -q validmind
Run comparison tests
Use the ValidMind Library’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:
- Find tests
- Initialize a ValidMind dataset
- Initialize a ValidMind model and assign predictions to a dataset
- Run a comparison test with
run_test
function
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 ValidMind Library 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 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.
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="...",
)
Initialize the Python environment
Next, let’s import the necessary libraries and set up your Python environment for data analysis:
import xgboost as xgb
%matplotlib inline
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:
filter="ClassifierPerformance") vm.tests.list_tests(
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:
= "validmind.model_validation.sklearn.ClassifierPerformance"
test_id 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}"
)
= customer_churn.load_data()
raw_df 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
= customer_churn.preprocess(raw_df)
train_df, validation_df, test_df
= vm.init_dataset(
vm_train_ds =train_df,
dataset="train_dataset",
input_id=customer_churn.target_column,
target_column
)
= vm.init_dataset(
vm_test_ds =test_df,
dataset="test_dataset",
input_id=customer_churn.target_column,
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.
= train_df.drop(customer_churn.target_column, axis=1)
x_train = train_df[customer_churn.target_column]
y_train = validation_df.drop(customer_churn.target_column, axis=1)
x_val = validation_df[customer_churn.target_column]
y_val
= xgb.XGBClassifier(early_stopping_rounds=10)
model
model.set_params(=["error", "logloss", "auc"],
eval_metric
)
model.fit(
x_train,
y_train,=[(x_val, y_val)],
eval_set=False,
verbose )
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.init_model(
vm_model_xgb
model,="xgboost",
input_id )
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_model_xgb)
vm_train_ds.assign_predictions(model=vm_model_xgb) vm_test_ds.assign_predictions(model
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:
= vm.tests.run_test(
result "validmind.model_validation.sklearn.ClassifierPerformance",
={
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:
vm_model_xgb
andvm_test_ds
vm_model_rf
andvm_test_ds
vm_model_lr
andvm_test_ds
vm_model_dt
andvm_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
= RandomForestClassifier()
model_rf
model_rf.fit(x_train, y_train)
= vm.init_model(
vm_model_rf
model_rf,="random_forest",
input_id
)
= LogisticRegression()
model_lr
model_lr.fit(x_train, y_train)
= vm.init_model(
vm_model_lr
model_lr,="logistic_regression",
input_id
)
= DecisionTreeClassifier()
model_dt
model_dt.fit(x_train, y_train)
= vm.init_model(
vm_model_dt
model_dt,="decision_tree",
input_id )
You will also need to assign the predictions to the test dataset for the other models:
=vm_model_rf)
vm_test_ds.assign_predictions(model=vm_model_lr)
vm_test_ds.assign_predictions(model=vm_model_dt) vm_test_ds.assign_predictions(model
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.
= vm.tests.run_test(
perf_comparison_result "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 parameters’ values
Now you can run the test with the param_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.
= vm.tests.run_test(
parameter_comparison_result "validmind.model_validation.sklearn.ClassifierPerformance:parameter_grid",
={
input_grid"dataset": [vm_test_ds],
"model": [vm_model_xgb,]
},={
param_grid"average": ["macro", "micro"]
}, )
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.
= vm.tests.run_test(
roc_curve_result "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:
In the ValidMind Platform, go to the Documentation page for the model you registered earlier. (Need more help?
Expand the 3.2. Model Evaluation section.
View the results of the tests you just ran at the end of the section.
="model_evaluation")
perf_comparison_result.log(section_id="model_evaluation") roc_curve_result.log(section_id
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.