• 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 a credit risk 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

  • 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
    • Preview the documentation template
  • Load the sample dataset
    • Prepocess the dataset
  • Train the model
    • Compute probabilities
    • Compute binary predictions
  • Postprocess the dataset
  • Document the model
    • Initialize the ValidMind datasets
    • Initialize a model object
    • Assign predictions
    • Run tests
  • 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 a credit risk model

Document a credit risk 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.

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
    • 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 predictions
    • Run tests
      • Data description
      • Data quality
      • Correlations
      • Model training
      • Model validation
      • Model explainability
      • Bias and fairness
  • Next steps
    • Work with your model documentation
    • 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.

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="...",
    # 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:

%pip -q install aequitas fairlearn vl-convert-python
import pandas as pd

from sklearn.ensemble import RandomForestClassifier
from sklearn.preprocessing import OneHotEncoder, StandardScaler
from sklearn.pipeline import Pipeline
from sklearn.impute import SimpleImputer
from sklearn.compose import ColumnTransformer
from sklearn.compose import make_column_selector as selector

from validmind.tests import run_test

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

from validmind.datasets.credit_risk import lending_club_bias as demo_dataset

df = demo_dataset.load_data()

df.head()

Prepocess the dataset

In the preprocessing step we perform a number of operations to get ready for building our credit decision model.

We will in this example, create new feature, fill missing values and encode categorical variables.

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

Train the model

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

# Split the data into training and testing sets
train_df, test_df = demo_dataset.split(preprocess_df)

X_train = train_df.drop(demo_dataset.target_column, axis=1)
y_train = train_df[demo_dataset.target_column]
X_test = test_df.drop(demo_dataset.target_column, axis=1)
y_test = test_df[demo_dataset.target_column]
# Train a Random Forest Classifier
model = RandomForestClassifier(n_estimators=50, random_state=42)
model.fit(X_train, y_train)

# Print feature importances
feature_importances = pd.DataFrame({
    'feature': X_train.columns,
    'importance': model.feature_importances_
}).sort_values('importance', ascending=False)

print("Feature Importances:")
print(feature_importances)

# Print model parameters
print("\nModel Parameters:")
print(model.get_params())

# Print basic model information
print(f"\nNumber of trees: {model.n_estimators}")

Compute probabilities

train_probabilities = model.predict_proba(X_train)[:,1]
test_probabilities = model.predict_proba(X_test)[:,1]

Compute binary predictions

cut_off_threshold = 0.5
train_binary_predictions = (train_probabilities > cut_off_threshold).astype(int)
test_binary_predictions = (test_probabilities > cut_off_threshold).astype(int)

Postprocess the dataset

# Save the original labels for the protected classes for visualizations and investigation of biased outcomes
protected_classes_df = df[demo_dataset.protected_classes]

train_df = train_df.merge(
    protected_classes_df,
    left_index=True,
    right_index=True,
)

test_df = test_df.merge(
    protected_classes_df,
    left_index=True,
    right_index=True,
)

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, training and test datasets created earlier into their own dataset objects using vm.init_dataset():

# Extract feature columns
feature_columns = train_df.drop(
    columns=[demo_dataset.target_column] + demo_dataset.protected_classes
).columns.tolist()
feature_columns
vm_raw_ds= vm.init_dataset(
    dataset=df,
    input_id="raw_dataset",
    target_column=demo_dataset.target_column,
)

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

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

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_model = vm.init_model(
    model,
    input_id="random_forest_model",
)

Assign predictions

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.

vm_train_ds.assign_predictions(
    model=vm_model,
    prediction_values=train_binary_predictions,
    prediction_probabilities=train_probabilities,
)

vm_test_ds.assign_predictions(
    model=vm_model,
    prediction_values=test_binary_predictions,
    prediction_probabilities=test_probabilities,
)

Run tests

Data description

test = vm.tests.run_test(
    "validmind.data_validation.DatasetDescription",
    inputs={
        "dataset": "raw_dataset",
    },
)
test.log()
test = vm.tests.run_test(
    "validmind.data_validation.DescriptiveStatistics",
    inputs={
        "dataset": "raw_dataset",
    },
)
test.log()
test = vm.tests.run_test(
    "validmind.data_validation.TabularNumericalHistograms",
    inputs={
        "dataset": "raw_dataset"
    },
)
test.log()
test = vm.tests.run_test(
    "validmind.data_validation.TargetRateBarPlots",
    inputs={
        "dataset": "raw_dataset"
    },
    params={
        "default_column": demo_dataset.target_column,
        "columns": None,
    },
)
test.log()

Data quality

test = vm.tests.run_test(
    "validmind.data_validation.ClassImbalance",
    inputs={
        "dataset": "raw_dataset",
    },
    params={
        "min_percent_threshold": 10
    }
)
test.log()
test = vm.tests.run_test(
    "validmind.data_validation.Duplicates",
    inputs={
        "dataset": "raw_dataset",
    },
    params={
        "min_threshold": 1
    }
)
test.log()
test = vm.tests.run_test(
    "validmind.data_validation.HighCardinality",
    inputs={
        "dataset": "raw_dataset",
    },
    params={
        "num_threshold": 100,
        "percent_threshold": 0.1,
        "threshold_type": "percent"
    }
)
test.log()
test = vm.tests.run_test(
    "validmind.data_validation.MissingValues",
    inputs={
        "dataset": "raw_dataset",
    },
    params={
        "min_threshold": 1,
    }
)
test.log()
test = vm.tests.run_test(
    "validmind.data_validation.Skewness",
    inputs={
        "dataset": "raw_dataset",
    },
    params={
        "max_threshold": 1,
    }
)
test.log()
test = vm.tests.run_test(
    "validmind.data_validation.UniqueRows",
    inputs={
        "dataset": "raw_dataset",
    },
    params={
        "min_percent_threshold": 1,
    }
)
test.log()
test = vm.tests.run_test(
    "validmind.data_validation.TooManyZeroValues",
    inputs={
        "dataset": "raw_dataset",
    },
    params={
        "max_percent_threshold": 0.03,
    }
)
test.log()
test = vm.tests.run_test(
    "validmind.data_validation.IQROutliersTable",
    inputs={
        "dataset": "raw_dataset",
    },
    params={
        "threshold": 1.5,
    }
)
test.log()
test = vm.tests.run_test(
    "validmind.data_validation.IQROutliersBarPlot",
    inputs={
        "dataset": "raw_dataset",
    },
    params={
        "threshold": 1.5,
        "fig_width": 800,
    }
)
test.log()

Correlations

test = vm.tests.run_test(
    "validmind.data_validation.PearsonCorrelationMatrix",
    inputs={
        "dataset": "raw_dataset",
    },
)
test.log()
test = vm.tests.run_test(
    "validmind.data_validation.HighPearsonCorrelation",
    inputs={
        "dataset": "raw_dataset",
    },
    params={
        "max_threshold": 0.3
    }
)
test.log()

Model training

test = vm.tests.run_test(
    "validmind.model_validation.ModelMetadata",
    inputs={
        "model": "random_forest_model",
    },
)
test.log()
test = vm.tests.run_test(
    "validmind.data_validation.DatasetSplit",
    inputs={
        "datasets": ["train_dataset", "test_dataset"],
    },
)
test.log()

Model validation

test = vm.tests.run_test(
    "validmind.model_validation.sklearn.PopulationStabilityIndex",
    inputs={
        "model": "random_forest_model",
        "datasets": ["train_dataset", "test_dataset"],
    },
    params={
        "num_bins": 10,
        "mode": "fixed"
    }
)
test.log()
test = vm.tests.run_test(
    "validmind.model_validation.sklearn.ConfusionMatrix",
    inputs={
        "model": "random_forest_model",
        "dataset": "test_dataset",
    },
)
test.log()
test = vm.tests.run_test(
    "validmind.model_validation.sklearn.ClassifierPerformance:in_sample",
    inputs={
        "model": "random_forest_model",
        "dataset": "train_dataset",
    },
)
test.log()
test = vm.tests.run_test(
    "validmind.model_validation.sklearn.ClassifierPerformance:out_of_sample",
    inputs={
        "model": "random_forest_model",
        "dataset": "test_dataset",
    },
)
test.log()
test = vm.tests.run_test(
    "validmind.model_validation.sklearn.PrecisionRecallCurve",
    inputs={
        "model": "random_forest_model",
        "dataset": "test_dataset",
    },
)
test.log()
test = vm.tests.run_test(
    "validmind.model_validation.sklearn.ROCCurve",
    inputs={
        "model": "random_forest_model",
        "dataset": "test_dataset",
    },
)
test.log()
test = vm.tests.run_test(
    "validmind.model_validation.sklearn.TrainingTestDegradation",
    inputs={
        "model": "random_forest_model",
        "datasets": ["train_dataset", "test_dataset"],
    },
    params={
        "metrics": ["accuracy", "precision", "recall", "f1"],
        "max_threshold": 0.1
    }
)
test.log()
test = vm.tests.run_test(
    "validmind.model_validation.sklearn.MinimumAccuracy",
    inputs={
        "model": "random_forest_model",
        "dataset": "test_dataset",
    },
    params={
        "min_threshold": 0.7
    }
)
test.log()
test = vm.tests.run_test(
    "validmind.model_validation.sklearn.MinimumF1Score",
    inputs={
        "model": "random_forest_model",
        "dataset": "test_dataset",
    },
    params={
        "min_threshold": 0.7
    }
)
test.log()
test = vm.tests.run_test(
    "validmind.model_validation.sklearn.MinimumROCAUCScore",
    inputs={
        "model": "random_forest_model",
        "dataset": "test_dataset",
    },
    params={
        "min_threshold": 0.5
    }
)
test.log()
test = vm.tests.run_test(
    "validmind.model_validation.statsmodels.GINITable",
    input_grid={
        "dataset": [vm_train_ds, vm_test_ds],
        "model": [vm_model],
    },
)
test.log()
test = vm.tests.run_test(
    "validmind.model_validation.statsmodels.PredictionProbabilitiesHistogram",
    input_grid={
        "dataset": [vm_train_ds, vm_test_ds],
        "model": [vm_model],
    },
)
test.log()
test = vm.tests.run_test(
    "validmind.model_validation.statsmodels.CumulativePredictionProbabilities",
    input_grid={
        "model": [vm_model],
        "dataset": [vm_train_ds, vm_test_ds],
    },
)
test.log()

Model explainability

test = vm.tests.run_test(
    "validmind.model_validation.sklearn.PermutationFeatureImportance",
    inputs={
        "model": "random_forest_model",
        "dataset": "test_dataset",
    },
    params={
        "fontsize": None,
        "figure_height": 1000
    }
)
test.log()
test = vm.tests.run_test(
"validmind.model_validation.sklearn.SHAPGlobalImportance",
inputs={
    "model": "random_forest_model",
    "dataset": "train_dataset",
    },
    params={
        "kernel_explainer_samples": 10,
        "tree_or_linear_explainer_samples": 200
    }
)
test.log()
test = vm.tests.run_test(
    "validmind.model_validation.sklearn.WeakspotsDiagnosis",
    inputs={
        "model": "random_forest_model",
        "datasets": ["train_dataset", "test_dataset"],
    },
    params={
        "features_columns": None,
        "thresholds": {
            "accuracy": 0.75,
            "precision": 0.5,
            "recall": 0.5,
            "f1": 0.7
        }
    }
)
test.log()
test = vm.tests.run_test(
    "validmind.model_validation.sklearn.OverfitDiagnosis",
    inputs={
        "model": "random_forest_model",
        "datasets": ["train_dataset", "test_dataset"],
    },
    params={
        "metric": None,
        "cut_off_threshold": 0.04
    }
)
test.log()
test = vm.tests.run_test(
    "validmind.model_validation.sklearn.RobustnessDiagnosis",
    inputs={
        "model": "random_forest_model",
        "datasets": ["train_dataset", "test_dataset"],
    },
    params={
        "metric": None,
        "scaling_factor_std_dev_list": [0.1, 0.2, 0.3, 0.4, 0.5],
        "performance_decay_threshold": 0.05
    }
)
test.log()

Bias and fairness

test = run_test(
    "validmind.data_validation.ProtectedClassesDescription",
    inputs={
        "dataset": "test_dataset"
    },
    params={
        'protected_classes': demo_dataset.protected_classes
    })
test.log()

Now we are going to focus our analysis on the fairness metric(s) of interest in this case study: FNR/FPR across different groups. The aequitas plot module exposes the disparities_metrics() plot, which displays both the disparities and the group-wise metric results side by side.

test = run_test(
    "validmind.data_validation.ProtectedClassesDisparity",
    inputs={
        "dataset": "test_dataset",
        "model": "random_forest_model"
    },
    params={
        "protected_classes": demo_dataset.protected_classes,
        "disparity_tolerance": 1.25,
        "metrics": ["fnr", "fpr", "tpr"]
    }
)
test.log()
run_test(
    "validmind.data_validation.ProtectedClassesCombination",
    inputs={
        "dataset": "test_dataset",
        "model": "random_forest_model"
    },
    params={
        "protected_classes": demo_dataset.protected_classes
    }
).log()

The following code defines a preprocessing Pipeline that handles both numeric and categorical features. Numeric data is imputed and scaled, while categorical data is imputed with the most frequent value and one-hot encoded. The pipelines are then combined using a ColumnTransformer and integrated with a classifier.

# Define a pipeline for numeric features
numeric_transformer = Pipeline(
    steps=[
        ("impute", SimpleImputer()),  # Impute missing values
        ("scaler", StandardScaler()),  # Scale numeric features
    ]
)

# Define a pipeline for categorical features
categorical_transformer = Pipeline(
    [
        ("impute", SimpleImputer(strategy="most_frequent")),  # Impute missing values with most frequent
        ("ohe", OneHotEncoder(handle_unknown="ignore")),  # One-hot encode categorical features
    ]
)

# Combine numeric and categorical pipelines
preprocessor = ColumnTransformer(
    transformers=[
        ("num", numeric_transformer, selector(dtype_exclude="category")),  # Apply numeric transformer to non-categorical columns
        ("cat", categorical_transformer, selector(dtype_include="category")),  # Apply categorical transformer to categorical columns
    ]
)

# Create the full pipeline including preprocessing and classification
pipeline = Pipeline(
    steps=[
        ("preprocessor", preprocessor),  # Apply the preprocessor
        (
            "classifier",
            model,  # Use the previously defined model for classification
        ),
    ]
)
sensitive_features = ['Gender_encoded','Race_encoded','Marital_Status_encoded']

run_test(
    "validmind.data_validation.ProtectedClassesThresholdOptimizer",
    inputs={
        "dataset": vm_test_ds
    },
    params={
        "pipeline":pipeline,
        "protected_classes": sensitive_features,
        "X_train":X_train,
        "y_train":y_train,
    },
).log()

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 an application scorecard model
Document an application scorecard model

© Copyright 2025 ValidMind Inc. All Rights Reserved.

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

  • Privacy Policy

  • Terms of Use