• 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. Code samples
  2. Credit Risk
  3. Document an application scorecard model

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

  • 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
    • Preview the documentation template
  • Load the sample dataset
    • Prepocess the dataset
    • Feature engineering
  • Train the model
    • Compute probabilities
    • Compute binary predictions
  • Document the model
    • Initialize the ValidMind datasets
    • Initialize a model object
    • Assign prediction values and probabilities to the datasets
    • Compute credit risk scores
    • Adding custom context to the LLM descriptions
    • Raw data
    • Pre-processed data
    • Development data
    • Feature selection
    • Model training
    • Model selection
    • Class discrimination
    • Classification accuracy
    • Model diagnosis
    • Model explainability
    • Scoring evaluation
  • Custom tests
    • In-line custom tests
    • Local test provider
  • Next steps
    • Work with your model documentation
    • Discover more learning resources
  • Upgrade ValidMind
  • Edit this page
  • Report an issue
  1. Code samples
  2. Credit Risk
  3. Document an application scorecard model

Document an application scorecard model

Build and document an application scorecard model with the ValidMind Library by using Kaggle's Lending Club sample dataset to build a simple application scorecard.

An application scorecard model is a type of statistical model used in credit scoring to evaluate the creditworthiness of potential borrowers by generating a score based on various characteristics of an applicant — such as credit history, income, employment status, and other relevant financial data.

  • This score helps lenders make decisions about whether to approve or reject loan applications, as well as determine the terms of the loan, including interest rates and credit limits.
  • Application scorecard models enable lenders to manage risk efficiently while making the loan application process faster and more transparent for applicants.

This interactive notebook provides a step-by-step guide for loading a demo dataset, preprocessing the raw data, training a model for testing, setting up test inputs, initializing the required ValidMind objects, running the test, and then logging the results to 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.

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:

%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: Credit Risk Scorecard
    • Use case: Credit Risk - CECL

    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 = "https://api.prod.validmind.ai/api/v1/tracking",
  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
from sklearn.ensemble import RandomForestClassifier

from validmind.tests import run_test
from validmind.datasets.credit_risk import lending_club

%matplotlib inline

Preview the documentation template

A template predefines sections for your model documentation and provides a general outline to follow, making the documentation process much easier.

You'll upload documentation and test results into this template later on. For now, take a look at the structure that the template provides with the vm.preview_template() function from the ValidMind library and note the empty sections:

vm.preview_template()

Load the sample dataset

The sample dataset used here is provided by the ValidMind library. To be able to use it, you'll 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:

df = lending_club.load_data(source="offline")

df.head()

Prepocess the dataset

In the preprocessing step we perform a number of operations to get ready for building our application scorecard.

We use the lending_club.preprocess to simplify preprocessing. This function performs the following operations: - Filters the dataset to include only loans for debt consolidation or credit card purposes - Removes loans classified under the riskier grades "F" and "G" - Excludes uncommon home ownership types and standardizes employment length and loan terms into numerical formats - Discards unnecessary fields and any entries with missing information to maintain a clean and robust dataset for modeling

preprocess_df = lending_club.preprocess(df)
preprocess_df.head()

Feature engineering

In the feature engineering phase, we apply specific transformations to optimize the dataset for predictive modeling in our application scorecard.

Using the ending_club.feature_engineering() function, we conduct the following operations: - WoE encoding: Converts both numerical and categorical features into Weight of Evidence (WoE) values. WoE is a statistical measure used in scorecard modeling that quantifies the relationship between a predictor variable and the binary target variable. It calculates the ratio of the distribution of good outcomes to the distribution of bad outcomes for each category or bin of a feature. This transformation helps to ensure that the features are predictive and consistent in their contribution to the model. - Integration of WoE bins: Ensures that the WoE transformed values are integrated throughout the dataset, replacing the original feature values while excluding the target variable from this transformation. This transformation is used to maintain a consistent scale and impact of each variable within the model, which helps make the predictions more stable and accurate.

fe_df = lending_club.feature_engineering(preprocess_df)
fe_df.head()

Train the model

In this section, we focus on constructing and refining our predictive model. - We begin by dividing our data, which is based on Weight of Evidence (WoE) features, into training and testing sets (train_df, test_df). - With lending_club.split, we employ a simple random split, randomly allocating data points to each set to ensure a mix of examples in both.

# Split the data
train_df, test_df = lending_club.split(fe_df, test_size=0.2)

x_train = train_df.drop(lending_club.target_column, axis=1)
y_train = train_df[lending_club.target_column]

x_test = test_df.drop(lending_club.target_column, axis=1)
y_test = test_df[lending_club.target_column]
# Define the XGBoost model
xgb_model = xgb.XGBClassifier(
    n_estimators=50, 
    random_state=42, 
    early_stopping_rounds=10
)
xgb_model.set_params(
    eval_metric=["error", "logloss", "auc"],
)

# Fit the model
xgb_model.fit(
    x_train, 
    y_train,
    eval_set=[(x_test, y_test)],
    verbose=False
)
# Define the Random Forest model
rf_model = RandomForestClassifier(
    n_estimators=50, 
    random_state=42,
)

# Fit the model
rf_model.fit(x_train, y_train)

Compute probabilities

train_xgb_prob = xgb_model.predict_proba(x_train)[:, 1]
test_xgb_prob = xgb_model.predict_proba(x_test)[:, 1]

train_rf_prob = rf_model.predict_proba(x_train)[:, 1]
test_rf_prob = rf_model.predict_proba(x_test)[:, 1]

Compute binary predictions

cut_off_threshold = 0.3

train_xgb_binary_predictions = (train_xgb_prob > cut_off_threshold).astype(int)
test_xgb_binary_predictions = (test_xgb_prob > cut_off_threshold).astype(int)

train_rf_binary_predictions = (train_rf_prob > cut_off_threshold).astype(int)
test_rf_binary_predictions = (test_rf_prob > cut_off_threshold).astype(int)

Document the model

To document the model with the ValidMind Library, you'll need to: 1. Preprocess the raw dataset 2. Initialize some training and test datasets 3. Initialize a model object you can use for testing 4. Run the full suite of tests

Initialize the ValidMind datasets

Before you can run tests, you must first initialize a ValidMind dataset object using the init_dataset function from the ValidMind (vm) module.

This function takes a number of arguments:

  • dataset: The 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.

With all datasets ready, you can now initialize the raw, processed, training and test datasets (raw_df, preprocessed_df, fe_df, train_df and test_df) created earlier into their own dataset objects using vm.init_dataset():

vm_raw_dataset = vm.init_dataset(
    dataset=df,
    input_id="raw_dataset",
    target_column=lending_club.target_column,
)

vm_preprocess_dataset = vm.init_dataset(
    dataset=preprocess_df,
    input_id="preprocess_dataset",
    target_column=lending_club.target_column,
)

vm_fe_dataset = vm.init_dataset(
    dataset=fe_df,
    input_id="fe_dataset",
    target_column=lending_club.target_column,
)

vm_train_ds = vm.init_dataset(
    dataset=train_df,
    input_id="train_dataset",
    target_column=lending_club.target_column,
)

vm_test_ds = vm.init_dataset(
    dataset=test_df,
    input_id="test_dataset",
    target_column=lending_club.target_column,
)

Initialize a model object

You will also need to 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_xgb_model = vm.init_model(
    xgb_model,
    input_id="xgb_model",
)

vm_rf_model = vm.init_model(
    rf_model,
    input_id="rf_model",
)

Assign prediction values and probabilities to the datasets

With our model now trained, we'll move on to assigning both the predictive probabilities coming directly from the model's predictions, and the binary prediction after applying the cutoff threshold described in the previous steps. - These tasks are achieved through the use of the assign_predictions() method associated with the VM dataset object. - This method links the model's class prediction values and probabilities to our VM train and test datasets.

# XGBoost
vm_train_ds.assign_predictions(
    model=vm_xgb_model,
    prediction_values=train_xgb_binary_predictions,
    prediction_probabilities=train_xgb_prob,
)

vm_test_ds.assign_predictions(
    model=vm_xgb_model,
    prediction_values=test_xgb_binary_predictions,
    prediction_probabilities=test_xgb_prob,
)

# Random Forest
vm_train_ds.assign_predictions(
    model=vm_rf_model,
    prediction_values=train_rf_binary_predictions,
    prediction_probabilities=train_rf_prob,
)

vm_test_ds.assign_predictions(
    model=vm_rf_model,
    prediction_values=test_rf_binary_predictions,
    prediction_probabilities=test_rf_prob,
)

Compute credit risk scores

In this phase, we translate model predictions into actionable scores using probability estimates generated by our trained model.

train_xgb_scores = lending_club.compute_scores(train_xgb_prob)
test_xgb_scores = lending_club.compute_scores(test_xgb_prob)

# Assign scores to the datasets
vm_train_ds.add_extra_column("xgb_scores", train_xgb_scores)
vm_test_ds.add_extra_column("xgb_scores", test_xgb_scores)

Adding custom context to the LLM descriptions

To enable the LLM descriptions context, you need to set the VALIDMIND_LLM_DESCRIPTIONS_CONTEXT_ENABLED environment variable to 1. This will enable the LLM descriptions context, which will be used to provide additional context to the LLM descriptions. This is a global setting that will affect all tests.

import os
os.environ["VALIDMIND_LLM_DESCRIPTIONS_CONTEXT_ENABLED"] = "1"

context = """
FORMAT FOR THE LLM DESCRIPTIONS: 
    **<Test Name>** is designed to <begin with a concise overview of what the test does and its primary purpose, 
    extracted from the test description>.

    The test operates by <write a paragraph about the test mechanism, explaining how it works and what it measures. 
    Include any relevant formulas or methodologies mentioned in the test description.>

    The primary advantages of this test include <write a paragraph about the test's strengths and capabilities, 
    highlighting what makes it particularly useful for specific scenarios.>

    Users should be aware that <write a paragraph about the test's limitations and potential risks. 
    Include both technical limitations and interpretation challenges. 
    If the test description includes specific signs of high risk, incorporate these here.>

    **Key Insights:**

    The test results reveal:

    - **<insight title>**: <comprehensive description of one aspect of the results>
    - **<insight title>**: <comprehensive description of another aspect>
    ...

    Based on these results, <conclude with a brief paragraph that ties together the test results with the test's 
    purpose and provides any final recommendations or considerations.>

ADDITIONAL INSTRUCTIONS:
    Present insights in order from general to specific, with each insight as a single bullet point with bold title.

    For each metric in the test results, include in the test overview:
    - The metric's purpose and what it measures
    - Its mathematical formula
    - The range of possible values
    - What constitutes good/bad performance
    - How to interpret different values

    Each insight should progressively cover:
    1. Overall scope and distribution
    2. Complete breakdown of all elements with specific values
    3. Natural groupings and patterns
    4. Comparative analysis between datasets/categories
    5. Stability and variations
    6. Notable relationships or dependencies

    Remember:
    - Keep all insights at the same level (no sub-bullets or nested structures)
    - Make each insight complete and self-contained
    - Include specific numerical values and ranges
    - Cover all elements in the results comprehensively
    - Maintain clear, concise language
    - Use only "- **Title**: Description" format for insights
    - Progress naturally from general to specific observations

""".strip()

os.environ["VALIDMIND_LLM_DESCRIPTIONS_CONTEXT"] = context

Raw data

run_test(
    "validmind.data_validation.DatasetDescription:raw_data",
    inputs={
        "dataset": vm_raw_dataset,
    },
).log()
run_test(
    "validmind.data_validation.DescriptiveStatistics:raw_data",
    inputs={
        "dataset": vm_raw_dataset,
    }
).log()
run_test(
    "validmind.data_validation.MissingValues:raw_data",
    inputs={
        "dataset": vm_raw_dataset,
    },
    params={
        "min_threshold": 1
    }
).log()
run_test(
    "validmind.data_validation.ClassImbalance:raw_data",
    inputs={
        "dataset": vm_raw_dataset,
    },
    params={
        "min_percent_threshold": 10
    }
).log()
run_test(
    "validmind.data_validation.Duplicates:raw_data",
    inputs={
        "dataset": vm_raw_dataset,
    },
    params={
        "min_threshold": 1
    }
).log()
run_test(
    "validmind.data_validation.HighCardinality:raw_data",
    inputs={
        "dataset": vm_raw_dataset,
    },
    params={
        "num_threshold": 100,
        "percent_threshold": 0.1,
        "threshold_type": "percent"
    }
).log()
run_test(
    "validmind.data_validation.Skewness:raw_data",
    inputs={
        "dataset": vm_raw_dataset,
    },
    params={
        "max_threshold": 1
    }
).log()
run_test(
    "validmind.data_validation.UniqueRows:raw_data",
    inputs={
        "dataset": vm_raw_dataset,
    },
    params={
        "min_percent_threshold": 1
    }
).log()
run_test(
    "validmind.data_validation.TooManyZeroValues:raw_data",
    inputs={
        "dataset": vm_raw_dataset,
    },
    params={
        "max_percent_threshold": 0.03
    }
).log()
run_test(
    "validmind.data_validation.IQROutliersTable:raw_data",
    inputs={
        "dataset": vm_raw_dataset,
    },
    params={
        "threshold": 5
    }
).log()

Pre-processed data

run_test(
    "validmind.data_validation.DescriptiveStatistics:preprocessed_data",
    inputs={
        "dataset": vm_preprocess_dataset,
    }
).log()
run_test(
    "validmind.data_validation.TabularDescriptionTables:preprocessed_data",
    inputs={
        "dataset": vm_preprocess_dataset
    },
).log()
run_test(
    "validmind.data_validation.MissingValues:preprocessed_data",
    inputs={
        "dataset": vm_preprocess_dataset,
    },
    params={
        "min_threshold": 1
    }
).log()
run_test(
    "validmind.data_validation.TabularNumericalHistograms:preprocessed_data",
    inputs={
        "dataset": vm_preprocess_dataset
    },
).log()
run_test(
    "validmind.data_validation.TabularCategoricalBarPlots:preprocessed_data",
    inputs={
        "dataset": vm_preprocess_dataset
    },
).log()
run_test(
    "validmind.data_validation.TargetRateBarPlots:preprocessed_data",
    inputs={
        "dataset": vm_preprocess_dataset
    },
    params={
        "default_column": lending_club.target_column,
    },
).log()

Development data

run_test(
    "validmind.data_validation.DescriptiveStatistics:development_data",
    input_grid={
        "dataset": [vm_train_ds, vm_test_ds],
    }
).log()
run_test(
    "validmind.data_validation.TabularDescriptionTables:development_data",
    input_grid={
        "dataset": [vm_train_ds, vm_test_ds],
    },
).log()
run_test(
    "validmind.data_validation.ClassImbalance:development_data",
    input_grid={
        "dataset": [vm_train_ds, vm_test_ds],
    },
    params={
        "min_percent_threshold": 10
    }
).log()
run_test(
    "validmind.data_validation.UniqueRows:development_data",
    input_grid={
        "dataset": [vm_train_ds, vm_test_ds],
    },
    params={
        "min_percent_threshold": 1
    }
).log()
run_test(
    "validmind.data_validation.TabularNumericalHistograms:development_data",
    input_grid={
        "dataset": [vm_train_ds, vm_test_ds],
    },
).log()

Feature selection

run_test(
    "validmind.data_validation.MutualInformation:development_data",
    input_grid  ={
        "dataset": [vm_train_ds, vm_test_ds],
    },
    params={
        "min_threshold": 0.01,
    },
).log()
run_test(
    "validmind.data_validation.PearsonCorrelationMatrix:development_data",
    input_grid={
        "dataset": [vm_train_ds, vm_test_ds],
    }
).log()
run_test(
    "validmind.data_validation.HighPearsonCorrelation:development_data",
    input_grid={
        "dataset": [vm_train_ds, vm_test_ds],
    },
    params={
        "max_threshold": 0.3,
        "top_n_correlations": 10
    }
).log()
run_test(
    "validmind.data_validation.WOEBinTable",
    input_grid={
        "dataset": [vm_preprocess_dataset]
    },
    params={
        "breaks_adj": lending_club.breaks_adj,
    },
).log()
run_test(
    "validmind.data_validation.WOEBinPlots",
    input_grid={
        "dataset": [vm_preprocess_dataset]
    },
    params={
        "breaks_adj": lending_club.breaks_adj,
    },
).log()

Model training

run_test(
    "validmind.data_validation.DatasetSplit",
    inputs={
        "datasets": [vm_train_ds, vm_test_ds],
    },
).log()
run_test(
    "validmind.model_validation.ModelMetadata",
    input_grid={
        "model": [vm_xgb_model, vm_rf_model],
    },
).log()
run_test(
    "validmind.model_validation.sklearn.ModelParameters",
    input_grid={
        "model": [vm_xgb_model, vm_rf_model],
    },
).log()

Model selection

run_test(
    "validmind.model_validation.statsmodels.GINITable",
    input_grid={
        "dataset": [vm_train_ds, vm_test_ds],
        "model": [vm_xgb_model, vm_rf_model],
    },
).log()
run_test(
    "validmind.model_validation.sklearn.ClassifierPerformance",
    input_grid={
        "dataset": [vm_train_ds, vm_test_ds],
        "model": [vm_xgb_model, vm_rf_model],
    },
).log()
run_test(
    "validmind.model_validation.sklearn.TrainingTestDegradation:XGBoost",
    inputs={
        "datasets": [vm_train_ds, vm_test_ds],
        "model": vm_xgb_model,
    },
    params={
        "max_threshold": 0.1
    }
).log()
run_test(
    "validmind.model_validation.sklearn.TrainingTestDegradation:RandomForest",
    inputs={
        "datasets": [vm_train_ds, vm_test_ds],
        "model": vm_rf_model,
    },
    params={
        "max_threshold": 0.1
    }
).log()
run_test(
    "validmind.model_validation.sklearn.HyperParametersTuning",
    inputs={
        "model": vm_xgb_model,
        "dataset": vm_train_ds,
    },
    params={
        "param_grid": {'n_estimators': [50, 100]},
        "scoring": ['roc_auc', 'recall'],
        "fit_params": {'eval_set': [(x_test, y_test)], 'verbose': False},
        "thresholds": [0.3, 0.5],
    }
).log()

Class discrimination

run_test(
    "validmind.model_validation.sklearn.ROCCurve",
    input_grid={
        "dataset": [vm_train_ds, vm_test_ds],
        "model": [vm_xgb_model],
    },
).log()
run_test(
    "validmind.model_validation.sklearn.MinimumROCAUCScore",
    input_grid={
        "dataset": [vm_train_ds, vm_test_ds],
        "model": [vm_xgb_model],
    },
    params={
        "min_threshold": 0.5
    }
).log()
run_test(
    "validmind.model_validation.statsmodels.PredictionProbabilitiesHistogram",
    input_grid={
        "dataset": [vm_train_ds, vm_test_ds],
        "model": [vm_xgb_model],
    },
).log()
run_test(
    "validmind.model_validation.statsmodels.CumulativePredictionProbabilities",
    input_grid={
        "model": [vm_xgb_model],
        "dataset": [vm_train_ds, vm_test_ds],
    },
).log()
run_test(
    "validmind.model_validation.sklearn.PopulationStabilityIndex",
    inputs={
        "datasets": [vm_train_ds, vm_test_ds],
        "model": vm_xgb_model,
    },
    params={
        "num_bins": 10,
        "mode": "fixed"
    }
).log()

Classification accuracy

run_test(
    "validmind.model_validation.sklearn.ClassifierThresholdOptimization",
    inputs={
        "dataset": vm_train_ds,
        "model": vm_xgb_model
    },
    params={
        "target_recall": 0.8 # Find a threshold that achieves a recall of 80%
    }
).log()
run_test(
    "validmind.model_validation.sklearn.CalibrationCurve",
    input_grid={
        "dataset": [vm_train_ds, vm_test_ds],
        "model": [vm_xgb_model],
    },
).log()
run_test(
    "validmind.model_validation.sklearn.ConfusionMatrix",
    input_grid={
        "dataset": [vm_train_ds, vm_test_ds],
        "model": [vm_xgb_model],
    },
).log()
run_test(
    "validmind.model_validation.sklearn.MinimumAccuracy",
    input_grid={
        "dataset": [vm_train_ds, vm_test_ds],
        "model": [vm_xgb_model],
    },
    params={
        "min_threshold": 0.7
    }
).log()
run_test(
    "validmind.model_validation.sklearn.MinimumF1Score",
    input_grid={
        "dataset": [vm_train_ds, vm_test_ds],
        "model": [vm_xgb_model],
    },
    params={
        "min_threshold": 0.5
    }
).log()
run_test(
    "validmind.model_validation.sklearn.PrecisionRecallCurve",
    input_grid={
        "dataset": [vm_train_ds, vm_test_ds],
        "model": [vm_xgb_model]
    },
).log()

Model diagnosis

run_test(
    "validmind.model_validation.sklearn.WeakspotsDiagnosis",
    inputs={
        "datasets": [vm_train_ds, vm_test_ds],
        "model": vm_xgb_model,
    },
).log()
run_test(
    "validmind.model_validation.sklearn.OverfitDiagnosis",
    inputs={
        "model": vm_xgb_model,
        "datasets": [vm_train_ds, vm_test_ds],
    },
    params={
        "cut_off_threshold": 0.04
    }
).log()
run_test(
    "validmind.model_validation.sklearn.RobustnessDiagnosis",
    inputs={
        "datasets": [vm_train_ds, vm_test_ds],
        "model": vm_xgb_model,
    },
    params={
        "scaling_factor_std_dev_list": [
            0.1,
            0.2,
            0.3,
            0.4,
            0.5
        ],
        "performance_decay_threshold": 0.05
    }
).log()

Model explainability

run_test(
    "validmind.model_validation.sklearn.PermutationFeatureImportance",
    input_grid={
        "dataset": [vm_train_ds, vm_test_ds],
        "model": [vm_xgb_model]
    }
).log()
run_test(
    "validmind.model_validation.FeaturesAUC",
    input_grid={
        "model": [vm_xgb_model],
        "dataset": [vm_train_ds, vm_test_ds],
    },
).log()
run_test(
    "validmind.model_validation.sklearn.SHAPGlobalImportance",
    input_grid={
        "model": [vm_xgb_model],
        "dataset": [vm_train_ds, vm_test_ds],
    },
    params={
        "kernel_explainer_samples": 10,
        "tree_or_linear_explainer_samples": 200,
    }
).log()

Scoring evaluation

run_test(
    "validmind.model_validation.statsmodels.ScorecardHistogram",
    input_grid={
        "dataset": [vm_train_ds, vm_test_ds],
    },
    params={
        "score_column": "xgb_scores",
    },
).log()
run_test(
    "validmind.data_validation.ScoreBandDefaultRates",
    input_grid={
        "dataset": [vm_train_ds],
        "model": [vm_xgb_model],
    },
    params = {
        "score_column": "xgb_scores",
        "score_bands": [500, 540, 570]
    }
).log()
run_test(
    "validmind.model_validation.sklearn.ScoreProbabilityAlignment",
    input_grid={
        "dataset": [vm_train_ds],
        "model": [vm_xgb_model],
    },
    params={
        "score_column": "xgb_scores",
    },
).log()

Custom tests

Custom tests extend the functionality of ValidMind, allowing you to document any model or use case with added flexibility.

ValidMind provides a comprehensive set of tests out-of-the-box to evaluate and document your models and datasets. We recognize there will be cases where the default tests do not support a model or dataset, or specific documentation is needed. In these cases, you can create and use your own custom code to accomplish what you need. To streamline custom code integration, we support the creation of custom test functions.

In-line custom tests

The @vm.test decorator is doing the work of creating a wrapper around the function that will allow it to be run by the ValidMind Library. It also registers the test so it can be found by the ID my_custom_tests.ScoreToOdds". The function score_to_odds_analysis takes three arguments dataset, score_column, and score_bands. This is a VMDataset and the rest are parameters that can be passed in.

import numpy as np
import pandas as pd
import plotly.graph_objects as go


@vm.test("my_custom_tests.ScoreToOdds")
def score_to_odds_analysis(dataset, score_column='score', score_bands=[410, 440, 470]):
    """
    Analyzes the relationship between score bands and odds (good:bad ratio).
    Good odds = (1 - default_rate) / default_rate
    
    Higher scores should correspond to higher odds of being good.
    """
    df = dataset.df
    
    # Create score bands
    df['score_band'] = pd.cut(
        df[score_column],
        bins=[-np.inf] + score_bands + [np.inf],
        labels=[f'<{score_bands[0]}'] + 
               [f'{score_bands[i]}-{score_bands[i+1]}' for i in range(len(score_bands)-1)] +
               [f'>{score_bands[-1]}']
    )
    
    # Calculate metrics per band
    results = df.groupby('score_band').agg({
        dataset.target_column: ['mean', 'count']
    })
    
    results.columns = ['Default Rate', 'Total']
    results['Good Count'] = results['Total'] - (results['Default Rate'] * results['Total'])
    results['Bad Count'] = results['Default Rate'] * results['Total']
    results['Odds'] = results['Good Count'] / results['Bad Count']
    
    # Create visualization
    fig = go.Figure()
    
    # Add odds bars
    fig.add_trace(go.Bar(
        name='Odds (Good:Bad)',
        x=results.index,
        y=results['Odds'],
        marker_color='blue'
    ))
    
    fig.update_layout(
        title='Score-to-Odds Analysis',
        yaxis=dict(title='Odds Ratio (Good:Bad)'),
        showlegend=False
    )
    
    return fig
run_test(
    "my_custom_tests.ScoreToOdds",
    inputs={
        "dataset": vm_test_ds,
    },
    params={
        "score_column": "xgb_scores",
        "score_bands": [500, 540, 570],
    },
).log()

Local test provider

The ValidMind Library offers the ability to extend the built-in library of tests with custom tests. A test "Provider" is a Python class that gets registered with the ValidMind Library and loads tests based on a test ID, for example my_test_provider.my_test_id. The built-in suite of tests that ValidMind offers is technically its own test provider. You can use one the built-in test provider offered by ValidMind (validmind.tests.test_providers.LocalTestProvider) or you can create your own. More than likely, you'll want to use the LocalTestProvider to add a directory of custom tests but there's flexibility to be able to load tests from any source.

from validmind.tests import LocalTestProvider

# Define the folder where your tests are located
tests_folder = "custom_tests"

# initialize the test provider with the tests folder we created earlier
my_test_provider = LocalTestProvider(tests_folder)

vm.tests.register_test_provider(
    namespace="my_test_provider",
    test_provider=my_test_provider,
)

Now that we have our test provider set up, we can run any test that's located in our tests folder by using the run_test() method. This function is your entry point to running single tests in the ValidMind Library. It takes a test ID and runs the test associated with that ID. For our custom tests, the test ID will be the namespace specified when registering the provider, followed by the path to the test file relative to the tests folder. For example, the Confusion Matrix test we created earlier will have the test ID my_test_provider.ConfusionMatrix. You could organize the tests in subfolders, say classification and regression, and the test ID for the Confusion Matrix test would then be my_test_provider.classification.ConfusionMatrix.

run_test(
    "my_test_provider.ScoreBandDiscriminationMetrics",
    inputs={
        "dataset": vm_test_ds,
        "model": vm_xgb_model,
    },
    params={
        "score_column": "xgb_scores",
        "score_bands": [500, 540, 570],
    }
).log(section_id="interpretability_insights")

Next steps

You can look at the results of this test suite 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

  1. In the ValidMind Platform, go to the Documentation page for the model you registered earlier. (Need more help?)

  2. Expand the following sections and take a look around:

    • 2. Data Preparation
    • 3. Model Development

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 (hint: some of the tests in 2.3. Feature Selection and Engineering look like they need some attention), view guidelines, collaborate with validators, and submit your model documentation for approval when it's ready.

Discover more learning resources

We offer many 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.

Document a credit risk model
Implement custom tests

© Copyright 2025 ValidMind Inc. All Rights Reserved.

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

  • Privacy Policy

  • Terms of Use