%pip install -q validmind
Quickstart for model documentation
Learn the basics of using ValidMind to document models as part of a model development workflow. Set up the ValidMind Library in your environment, and generate a draft of documentation using ValidMind tests for a binary classification model.
To document a model with the ValidMind Library, we'll:
- Import a sample dataset and preprocess it
- Split the datasets and initialize them for use with ValidMind
- Initialize a model object for use with testing
- Run a full suite of tests as defined by our documentation template, which will send the results of those tests to the ValidMind Platform
Introduction
Model development aims to produce a fit-for-purpose champion model by conducting thorough testing and analysis, supporting the capabilities of the model with evidence in the form of documentation and test results. Model documentation should be clear and comprehensive, ideally following a structure or template covering all aspects of compliance with model risk regulation.
A binary classification model is a type of predictive model used in churn analysis to identify customers who are likely to leave a service or subscription by analyzing various behavioral, transactional, and demographic factors.
- This model helps businesses take proactive measures to retain at-risk customers by offering personalized incentives, improving customer service, or adjusting pricing strategies.
- Effective validation of a churn prediction model ensures that businesses can accurately identify potential churners, optimize retention efforts, and enhance overall customer satisfaction while minimizing revenue loss.
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.
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.
Metrics: A subset of tests that do not have thresholds. In the context of this notebook, metrics and tests can be thought of as interchangeable concepts.
Custom metrics: Custom metrics are functions that you define to evaluate your model or dataset. These functions can be registered with the ValidMind Library to be used in 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 metric.
- datasets: A list of ValidMind datasets - usually this is used when you want to compare multiple datasets in your custom metric. (Learn more: Run tests with multiple datasets)
Parameters: Additional arguments that can be passed when running a ValidMind test, used to pass additional information to a metric, customize its behavior, or provide additional context.
Outputs: Custom metrics 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.
Setting up
Install the ValidMind Library
Python 3.8 <= x <= 3.11
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 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
Then, let's import the necessary libraries and set up your Python environment for data analysis:
- Import Extreme Gradient Boosting (XGBoost) with an alias so that we can reference its functions in later calls. XGBoost is a powerful machine learning library designed for speed and performance, especially in handling structured or tabular data.
- Enable
matplotlib
, a plotting library used for visualizing data. Ensures that any plots you generate will render inline in our notebook output rather than opening in a separate window.
import xgboost as xgb
%matplotlib inline
Getting to know ValidMind
Preview the documentation template
Let's verify that you have connected the ValidMind Library to the ValidMind Platform and that the appropriate template is selected for your model. A template predefines sections for your model documentation and provides a general outline to follow, making the documentation process much easier.
You will upload documentation and test results unique to your model based on this template later on. For now, take a look at the default structure that the template provides with the vm.preview_template()
function from the ValidMind library and note the empty sections:
vm.preview_template()
View model documentation in the ValidMind Platform
Next, let's head to the ValidMind Platform to see the template in action:
In a browser, log in to ValidMind.
In the left sidebar, navigate to Inventory and select the model you registered for this notebook.
Click on the Documentation for your model and note how the structure of the documentation matches our preview above.
Import the sample dataset
First, let's import the public Bank Customer Churn Prediction dataset from Kaggle so that we have something to work with.
In our below example, note that:
- The target column,
Exited
has a value of1
when a customer has churned and0
otherwise. - The ValidMind Library provides a wrapper to automatically load the dataset as a Pandas DataFrame object. A Pandas Dataframe is a two-dimensional tabular data structure that makes use of rows and columns.
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()
Preprocessing the raw dataset
Before running tests with Validmind, we'll need to preprocess our imported dataset. This involves splitting the data and separating the features (inputs) from the targets (outputs).
Split the dataset
Splitting our dataset helps assess how well the model generalizes to unseen data.
Use preprocess()
to split our dataset into three subsets:
- train_df — Used to train the model.
- validation_df — Used to evaluate the model's performance during training.
- test_df — Used later on to asses the model's performance on new, unseen data.
= customer_churn.preprocess(raw_df) train_df, validation_df, test_df
Separate features and targets
To train the model, we need to provide it with:
- Inputs — Features such as customer age, usage, etc.
- Outputs (Expected answers/labels) — in our case, we would like to know whether the customer churned or not.
Here, we'll use x_train
and x_val
to hold the input data (features), and y_train
and y_val
to hold the answers (the target we want to predict):
= 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
Training an XGBoost classifier model
Next, let's create an XGBoost classifier model that will automatically stop training if it doesn’t improve after 10 tries.
Setting a threshold avoids wasting time and helps prevent overfitting by stopping training when further improvement isn’t happening.
= xgb.XGBClassifier(early_stopping_rounds=10) model
Set evaluation metrics
Then, we'll set the evaluation metrics, which tells the model to use three different ways to measure its performance:
- error — Measures how often the model makes incorrect predictions.
- logloss — Indicates how confident the predictions are.
- auc — Evaluates how well the model distinguishes between churn and not churn.
Using multiple metrics gives a more complete picture of how good (or bad) the model is.
model.set_params(=["error", "logloss", "auc"],
eval_metric )
Fit the model
Finally, our actual training step — where the model learns patterns from the data, so it can make predictions later:
- The model is trained on
x_train
andy_train
, and evaluates its performance usingx_val
andy_val
to check if it’s learning well. - To turn off printed output while training, we'll set
verbose
toFalse
.
model.fit(
x_train,
y_train,=[(x_val, y_val)],
eval_set=False,
verbose )
Initialize the ValidMind datasets
Before you can run tests with your preprocessed datasets, you must first initialize a ValidMind Dataset
object using the init_dataset
function from the ValidMind (vm
) module. This step is always necessary every time you want to connect a dataset to documentation and produce test results through ValidMind, but you only need to do it once per dataset.
For this example, we'll pass in the following 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.class_labels
— An optional value to map predicted classes to class labels.
# Initialize the raw dataset
= vm.init_dataset(
vm_raw_dataset =raw_df,
dataset="raw_dataset",
input_id=customer_churn.target_column,
target_column=customer_churn.class_labels,
class_labels
)
# Initialize the training dataset
= vm.init_dataset(
vm_train_ds =train_df,
dataset="train_dataset",
input_id=customer_churn.target_column,
target_column
)
# Initialize the testing dataset
= vm.init_dataset(
vm_test_ds =test_df,
dataset="test_dataset",
input_id=customer_churn.target_column
target_column )
Initialize a model object
You'll also need to initialize a ValidMind model object (vm_model
) that can be passed to other functions for analysis and tests on the data for our model.
You simply initialize this model object with vm.init_model()
:
= vm.init_model(
vm_model
model,="model",
input_id )
Assign predictions
Once the model has been registered, you can assign model predictions to the training and testing datasets.
- The
assign_predictions()
method from theDataset
object can link existing predictions to any number of models. - This method links the model's class prediction values and probabilities to our
vm_train_ds
andvm_test_ds
datasets.
If no prediction values are passed, the method will compute predictions automatically:
vm_train_ds.assign_predictions(=vm_model,
model
)
vm_test_ds.assign_predictions(=vm_model,
model )
Run the full suite of tests
This is where it all comes together — you are now ready to run the documentation tests for the model as defined by the documentation template you looked at earlier.
The vm.run_documentation_tests
function finds and runs every test specified in the template and then uploads all the documentation and test artifacts that get generated to the ValidMind Platform:
The function requires information about the inputs to use on every test. These inputs can be passed as an
inputs
argument if we want to use the same inputs for all tests.It's also possible to pass a
config
argument that has information about theparams
andinputs
that each test requires. Theconfig
parameter is a dictionary with the following structure:= { config "<test-id>": { "params": { "param1": "value1", "param2": "value2", ... },"inputs": { "input1": "value1", "input2": "value2", ... } }, ... }
Each
<test-id>
above corresponds to the test driven block identifiers shown byvm.preview_template()
. For this model, we will use the default parameters for all tests, but we'll need to specify the input configuration for each one. The methodget_demo_test_config()
below constructs the default input configuration for our demo.
from validmind.utils import preview_test_config
= customer_churn.get_demo_test_config()
test_config preview_test_config(test_config)
Now we can pass the input configuration to vm.run_documentation_tests()
and run the full suite of tests.
The variable full_suite
then holds the result of these tests:
= vm.run_documentation_tests(config=test_config) full_suite
In summary
In this notebook, you learned how to:
Next steps
You can look at the output produced by the ValidMind Library right in the notebook where you ran the code, as you would expect. But there is a better way — use the ValidMind Platform to work with your model documentation.
Work with your model documentation
From the Inventory in the ValidMind Platform, go to the model you registered earlier. (Need more help?)
In the left sidebar that appears for your model, click Documentation.
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. Learn more ...
Discover more learning resources
For a more in-depth introduction to using the ValidMind Library for development, check out our introductory development series and the accompanying interactive training:
We also offer many 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.