• About
  • Get Started
  • Guides
  • ValidMind Library
    • ValidMind Library
    • Supported Models
    • QuickStart Notebook

    • TESTING
    • Run Tests & Test Suites
    • Test Descriptions
    • Test Sandbox (BETA)

    • CODE SAMPLES
    • All Code Samples · LLM · NLP · Time Series · Etc.
    • Download Code Samples · notebooks.zip
    • Try it on JupyterHub

    • REFERENCE
    • ValidMind Library Python API
  • Support
  • Training
  • Releases
  • Documentation
    • About ​ValidMind
    • Get Started
    • Guides
    • Support
    • Releases

    • Python Library
    • ValidMind Library

    • ValidMind Academy
    • Training Courses
  • Log In
    • Public Internet
    • ValidMind Platform · US1
    • ValidMind Platform · CA1

    • Private Link
    • Virtual Private ValidMind (VPV)

    • Which login should I use?
  1. Run tests & test suites
  2. Run Tests
  3. Run comparison tests

EU AI Act Compliance — Read our original regulation brief on how the EU AI Act aims to balance innovation with safety and accountability, setting standards for responsible AI use

  • ValidMind Library
  • Supported models

  • QuickStart
  • Quickstart for model documentation
  • Install and initialize ValidMind Library
  • Store model credentials in .env files

  • Model Development
  • 1 — Set up ValidMind Library
  • 2 — Start model development process
  • 3 — Integrate custom tests
  • 4 — Finalize testing & documentation

  • Model Validation
  • 1 — Set up ValidMind Library for validation
  • 2 — Start model validation process
  • 3 — Developing a challenger model
  • 4 — Finalize validation & reporting

  • Model Testing
  • Run tests & test suites
    • Add context to LLM-generated test descriptions
    • Configure dataset features
    • Document multiple results for the same test
    • Explore test suites
    • Explore tests
    • Dataset Column Filters when Running Tests
    • Load dataset predictions
    • Log metrics over time
    • Run individual documentation sections
    • Run documentation tests with custom configurations
    • Run tests with multiple datasets
    • Intro to Unit Metrics
    • Understand and utilize RawData in ValidMind tests
    • Introduction to ValidMind Dataset and Model Objects
    • Run Tests
      • Run dataset based tests
      • Run comparison tests
  • Test descriptions
    • Data Validation
      • ACFandPACFPlot
      • ADF
      • AutoAR
      • AutoMA
      • AutoStationarity
      • BivariateScatterPlots
      • BoxPierce
      • ChiSquaredFeaturesTable
      • ClassImbalance
      • DatasetDescription
      • DatasetSplit
      • DescriptiveStatistics
      • DickeyFullerGLS
      • Duplicates
      • EngleGrangerCoint
      • FeatureTargetCorrelationPlot
      • HighCardinality
      • HighPearsonCorrelation
      • IQROutliersBarPlot
      • IQROutliersTable
      • IsolationForestOutliers
      • JarqueBera
      • KPSS
      • LaggedCorrelationHeatmap
      • LJungBox
      • MissingValues
      • MissingValuesBarPlot
      • MutualInformation
      • PearsonCorrelationMatrix
      • PhillipsPerronArch
      • ProtectedClassesCombination
      • ProtectedClassesDescription
      • ProtectedClassesDisparity
      • ProtectedClassesThresholdOptimizer
      • RollingStatsPlot
      • RunsTest
      • ScatterPlot
      • ScoreBandDefaultRates
      • SeasonalDecompose
      • ShapiroWilk
      • Skewness
      • SpreadPlot
      • TabularCategoricalBarPlots
      • TabularDateTimeHistograms
      • TabularDescriptionTables
      • TabularNumericalHistograms
      • TargetRateBarPlots
      • TimeSeriesDescription
      • TimeSeriesDescriptiveStatistics
      • TimeSeriesFrequency
      • TimeSeriesHistogram
      • TimeSeriesLinePlot
      • TimeSeriesMissingValues
      • TimeSeriesOutliers
      • TooManyZeroValues
      • UniqueRows
      • WOEBinPlots
      • WOEBinTable
      • ZivotAndrewsArch
      • Nlp
        • CommonWords
        • Hashtags
        • LanguageDetection
        • Mentions
        • PolarityAndSubjectivity
        • Punctuations
        • Sentiment
        • StopWords
        • TextDescription
        • Toxicity
    • Model Validation
      • BertScore
      • BleuScore
      • ClusterSizeDistribution
      • ContextualRecall
      • FeaturesAUC
      • MeteorScore
      • ModelMetadata
      • ModelPredictionResiduals
      • RegardScore
      • RegressionResidualsPlot
      • RougeScore
      • TimeSeriesPredictionsPlot
      • TimeSeriesPredictionWithCI
      • TimeSeriesR2SquareBySegments
      • TokenDisparity
      • ToxicityScore
      • Embeddings
        • ClusterDistribution
        • CosineSimilarityComparison
        • CosineSimilarityDistribution
        • CosineSimilarityHeatmap
        • DescriptiveAnalytics
        • EmbeddingsVisualization2D
        • EuclideanDistanceComparison
        • EuclideanDistanceHeatmap
        • PCAComponentsPairwisePlots
        • StabilityAnalysisKeyword
        • StabilityAnalysisRandomNoise
        • StabilityAnalysisSynonyms
        • StabilityAnalysisTranslation
        • TSNEComponentsPairwisePlots
      • Ragas
        • AnswerCorrectness
        • AspectCritic
        • ContextEntityRecall
        • ContextPrecision
        • ContextPrecisionWithoutReference
        • ContextRecall
        • Faithfulness
        • NoiseSensitivity
        • ResponseRelevancy
        • SemanticSimilarity
      • Sklearn
        • AdjustedMutualInformation
        • AdjustedRandIndex
        • CalibrationCurve
        • ClassifierPerformance
        • ClassifierThresholdOptimization
        • ClusterCosineSimilarity
        • ClusterPerformanceMetrics
        • CompletenessScore
        • ConfusionMatrix
        • FeatureImportance
        • FowlkesMallowsScore
        • HomogeneityScore
        • HyperParametersTuning
        • KMeansClustersOptimization
        • MinimumAccuracy
        • MinimumF1Score
        • MinimumROCAUCScore
        • ModelParameters
        • ModelsPerformanceComparison
        • OverfitDiagnosis
        • PermutationFeatureImportance
        • PopulationStabilityIndex
        • PrecisionRecallCurve
        • RegressionErrors
        • RegressionErrorsComparison
        • RegressionPerformance
        • RegressionR2Square
        • RegressionR2SquareComparison
        • RobustnessDiagnosis
        • ROCCurve
        • ScoreProbabilityAlignment
        • SHAPGlobalImportance
        • SilhouettePlot
        • TrainingTestDegradation
        • VMeasure
        • WeakspotsDiagnosis
      • Statsmodels
        • AutoARIMA
        • CumulativePredictionProbabilities
        • DurbinWatsonTest
        • GINITable
        • KolmogorovSmirnov
        • Lilliefors
        • PredictionProbabilitiesHistogram
        • RegressionCoeffs
        • RegressionFeatureSignificance
        • RegressionModelForecastPlot
        • RegressionModelForecastPlotLevels
        • RegressionModelSensitivityPlot
        • RegressionModelSummary
        • RegressionPermutationFeatureImportance
        • ScorecardHistogram
    • Ongoing Monitoring
      • CalibrationCurveDrift
      • ClassDiscriminationDrift
      • ClassificationAccuracyDrift
      • ClassImbalanceDrift
      • ConfusionMatrixDrift
      • CumulativePredictionProbabilitiesDrift
      • FeatureDrift
      • PredictionAcrossEachFeature
      • PredictionCorrelation
      • PredictionProbabilitiesHistogramDrift
      • PredictionQuantilesAcrossFeatures
      • ROCCurveDrift
      • ScoreBandsDrift
      • ScorecardHistogramDrift
      • TargetPredictionDistributionPlot
    • Prompt Validation
      • Bias
      • Clarity
      • Conciseness
      • Delimitation
      • NegativeInstruction
      • Robustness
      • Specificity
  • Test sandbox beta

  • Notebooks
  • Code samples
    • Capital Markets
      • Quickstart for knockout option pricing model documentation
      • Quickstart for Heston option pricing model using QuantLib
    • Credit Risk
      • Document an application scorecard model
      • Document an application scorecard model
      • Document an application scorecard model
      • Document a credit risk model
      • Document an application scorecard model
    • Custom Tests
      • Implement custom tests
      • Integrate external test providers
    • Model Validation
      • Validate an application scorecard model
    • Nlp and Llm
      • Sentiment analysis of financial data using a large language model (LLM)
      • Summarization of financial data using a large language model (LLM)
      • Sentiment analysis of financial data using Hugging Face NLP models
      • Summarization of financial data using Hugging Face NLP models
      • Automate news summarization using LLMs
      • Prompt validation for large language models (LLMs)
      • RAG Model Benchmarking Demo
      • RAG Model Documentation Demo
    • Ongoing Monitoring
      • Ongoing Monitoring for Application Scorecard
      • Quickstart for ongoing monitoring of models with ValidMind
    • Regression
      • Document a California Housing Price Prediction regression model
    • Time Series
      • Document a time series forecasting model
      • Document a time series forecasting model

  • Reference
  • ValidMind Library Python API

On this page

  • Contents
  • About ValidMind
    • Before you begin
    • New to ValidMind?
    • Key concepts
  • Install the ValidMind Library
  • Initialize the ValidMind Library
    • Get your code snippet
  • Initialize the Python environment
  • List and filter available tests
  • Load the sample dataset and run a model test
    • Initialize a ValidMind dataset
    • Train a sample XGBoost model
    • Initialize a ValidMind model
    • Assign predictions to the datasets
    • Run the test with one model
  • Run comparison tests
    • Run a comparison test with multiple models
    • Run a comparison test with multiple datasets
  • Add test results to documentation
  • Next steps
    • Discover more learning resources
  • Upgrade ValidMind
  • Edit this page
  • Report an issue
  1. Run tests & test suites
  2. Run Tests
  3. Run comparison tests

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
    • Before you begin
    • New to ValidMind?
    • Key concepts
  • Install the ValidMind Library
  • Initialize the ValidMind Library
    • Get your code snippet
  • List and filter available tests
  • Load the sample dataset and run a model test
    • Initialize a ValidMind dataset
    • Train a sample XGBoost model
    • Initialize a ValidMind model
    • Assign predictions to the datasets
    • Run the test with one model
  • Run comparison tests
    • Run a comparison test with multiple models
    • Run a comparison test with multiple parameters' values
    • Run a classifier performance comparison test
  • Add test results to documentation
  • Next steps
    • Discover more learning resources
  • Upgrade ValidMind

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 documentation on the ValidMind Library, we recommend you begin by exploring the available resources in this section. There, you can learn more about documenting models and running tests, as well as find code samples and our Python Library API 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 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:

%pip install -q validmind

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

  1. In a browser, log in to ValidMind.

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

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

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

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.

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(
    "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:

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

parameter_comparison_result = vm.tests.run_test(
    "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.

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 ValidMind Platform, go to the Documentation page for the model you registered earlier. (Need more help?

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

  • Run tests & test suites
  • Code samples

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.

Run dataset based tests
Test descriptions

© Copyright 2025 ValidMind Inc. All Rights Reserved.

  • Edit this page
  • Report an issue
Cookie Preferences
  • validmind.com

  • Privacy Policy

  • Terms of Use