Document an application scorecard model

Build and document an application scorecard model with the ValidMind Developer Framework 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 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

ValidMind is a platform for managing model risk, including risk associated with AI and statistical models.

You use the ValidMind Developer Framework to automate documentation and validation tests, and then use the ValidMind AI Risk Platform UI to collaborate on model documentation. Together, these products simplify model risk management, facilitate compliance with regulations and institutional standards, and enhance collaboration between yourself and model validators.

Before you begin

This notebook assumes you have basic familiarity with Python, including an understanding of how functions work. If you are new to Python, you can still run the notebook but we recommend further familiarizing yourself with the language.

If you encounter errors due to missing modules in your Python environment, install the modules with pip install, and then re-run the notebook. For more help, refer to Installing Python Modules.

New to ValidMind?

If you haven’t already seen our Get started with the ValidMind Developer Framework, we recommend you begin by exploring the available resources in this section. There, you can learn more about documenting models, find code samples, or read our developer reference.

For access to all features available in this notebook, create a free ValidMind account.

Signing up is FREE — Sign up now

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 Developer Framework, 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 with ValidMind to be used in the platform.

Inputs: Objects to be evaluated and documented in the ValidMind framework. 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 client library

The client library provides Python support for the ValidMind Developer Framework. To install it:

%pip install -q validmind

Initialize the client library

ValidMind generates a unique code snippet for each registered model to connect with your developer environment. You initialize the client 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 into the Platform UI.

  2. In the left sidebar, navigate to Model Inventory and click + Register new 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: Risk Management/CECL

    You can fill in other options according to your preference.

  4. Go to Getting Started and click Copy snippet to clipboard.

Next, replace this placeholder with your own code snippet:

import validmind as vm

vm.init(
  api_host = "https://api.prod.validmind.ai/api/v1/tracking",
  api_key = "...",
  api_secret = "...",
  project = "..."
)

Initialize the Python environment

Next, let’s import the necessary libraries and set up your Python environment for data analysis:

import statsmodels.api as sm

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

# Import the sample dataset from the library

from validmind.datasets.credit_risk import lending_club

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. - Additionally, by setting add_constant=True, we include an intercept term in our model.

train_df, test_df = lending_club.split(fe_df, add_constant=True)

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 model
model = sm.GLM(y_train, x_train, family=sm.families.Binomial())

# Fit the model
model = model.fit()
model.summary()

Compute probabilities

train_probabilities = model.predict(x_train)
test_probabilities = model.predict(x_test)

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)

Compute scores

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

# Compute scores from the probabilities
train_scores = lending_club.compute_scores(train_probabilities)
test_scores = lending_club.compute_scores(test_probabilities)

Document the model

To document the model with the ValidMind Developer Framework, 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_model = vm.init_model(
    model,
    input_id="glm_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.

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,
)

Assign scores to the datasets

Credit scorecards revolve around scores computed from model predictions rather than raw predictions, so let’s compute some scores!

  • To make this process auditable and ensure scores are properly integrated with our datasets, we use the add_extra_column() method from the VM dataset object.
  • This approach allows us to append scores directly to our data, maintaining a streamlined and coherent dataset ready for analysis.
vm_train_ds.add_extra_column("glm_scores", train_scores)
vm_test_ds.add_extra_column("glm_scores", test_scores)

Data validation

During data validation, we ensure that the data we’re working with is accurate, consistent, and ready for empirical analysis. We’re looking for any anomalies that might skew our models or results.

In this section, we use tests to collect evidence across raw, preprocessed, and feature-engineered datasets.

Run tests for raw data tests

We perform initial validation of our raw data to understand its structure and detect any anomalies that could affect the modeling process. At this stage, we use a couple of tests that help us understand the data:

  • Tabular description tables: Statistical summary for each variable
  • Missing values bar plot: Plots presence of any missing data

To ensure we can run this test again against a different dataset, we’ll label these test results with <test_id>:raw_dataset. This will make the results identifiable in the database, allowing us to include them in the UI.

test = vm.tests.run_test(
    "validmind.data_validation.TabularDescriptionTables:raw_dataset",
    inputs={
        "dataset": vm_raw_dataset,
    },
)
test.log()
test = vm.tests.run_test(
    "validmind.data_validation.MissingValuesBarPlot:raw_dataset",
    inputs={
        "dataset": vm_raw_dataset,
    },
)
test.log()

Run tests for preprocessed data

Before the modeling process begins, the data undergoes a final quality validation. To ensure the data is ready for the next data preparation step, we conduct the following tests:

  • Tabular description tables: Checking structural integrity after preprocessing
  • IQR outliers table: Searching for statistical anomalies that may impact results
  • Class imbalance: Investigating the proportionality of outcome classes
  • Tabular numerical histograms: Visualizing distributions for numerical variables
  • Tabular categorical bar plots: Analyzing frequencies of categorical variables
  • Target rate bar plots: Examining the distribution of the target variable across categories
  • Pearson correlation matrix: Identifying linear relationships between variables

Similar to the previous step, we now want to run the same description tables against the preprocessed dataset to identify improvements and observe the effects of our changes on the data. This time, we’ll do this by adding the <test_id>:preprocess_dataset> label to our results.

test = vm.tests.run_test(
    "validmind.data_validation.TabularDescriptionTables:preprocess_dataset",
    inputs={
        "dataset": vm_preprocess_dataset,
    },
)
test.log()
test = vm.tests.run_test(
    "validmind.data_validation.IQROutliersTable",
    inputs={
        "dataset": vm_preprocess_dataset,
    },
)
test.log()
test = vm.tests.run_test(
    "validmind.data_validation.ClassImbalance",
    inputs={
        "dataset": vm_preprocess_dataset,
    },
)
test.log()
test = vm.tests.run_test(
    "validmind.data_validation.TabularNumericalHistograms",
    inputs={
        "dataset": vm_preprocess_dataset,
    },
)
test.log()
test = vm.tests.run_test(
    "validmind.data_validation.TabularCategoricalBarPlots",
    inputs={
        "dataset": vm_preprocess_dataset,
    },
)
test.log()
test = vm.tests.run_test(
    "validmind.data_validation.TargetRateBarPlots",
    inputs={
        "dataset": vm_preprocess_dataset,
    },
    params={
        "default_column": lending_club.target_column,
        "columns": None,
    },
)
test.log()
test = vm.tests.run_test(
    "validmind.data_validation.PearsonCorrelationMatrix",
    inputs={
        "dataset": vm_preprocess_dataset,
    },
)
test.log()
test = vm.tests.run_test(
    "validmind.data_validation.HighPearsonCorrelation",
    inputs={
        "dataset": vm_preprocess_dataset,
    },
)
test.log()

Run tests for WoE analysis

To ensure data segmentation aligns with predictive value, we perform detailed tests on the following:

  • WOE bin table: This test checks the bins and their corresponding Weight of Evidence values, ensuring accuracy and relevance.
  • WOE bin plots: These plots display the distribution of WoE across the data spectrum, providing a visual assessment of alignment and consistency.
test = vm.tests.run_test(
    "validmind.data_validation.WOEBinTable",
    inputs={
        "dataset": vm_preprocess_dataset,
    },
    params={
        "breaks_adj": lending_club.breaks_adj,
    },
)
test.log()
test = vm.tests.run_test(
    "validmind.data_validation.WOEBinPlots",
    inputs={
        "dataset": vm_preprocess_dataset,
    },
    params={
        "breaks_adj": lending_club.breaks_adj,
    },
)
test.log()

Model validation

This phase verifies the model’s predictive power and generalizability. Generalizability is the ability to accurately make future predictions based on past observations — how is this model going to perform when working with real data?

Tests are applied to both training and evaluation stages to ensure robustness and accuracy.

Run tests for model training

After training our model, we’ll want to inspect the model coefficients and some of their statistical properties, such as probability values. A model coefficient is value that represents the weight or effect of an independent variable in a model. This step is crucial as it informs us about the relevance of the features used to train the model. We can also begin making decisions regarding the quality of our model.

These tests assist us with this inspection:

  • Dataset split: Assesses the distribution of data across training and testing sets
  • Regression coeffs plot: Visual inspection of the model’s coefficients
  • Regression models coeffs: Detailed evaluation of the regression coefficients’ values

Note that we use the models interface and pass a model as a list. This is because these tests support multiple models — if you have candidate models, you can use these tests to examine the differences in coefficients across multiple models.

test = vm.tests.run_test(
    "validmind.data_validation.DatasetSplit",
    inputs={
        "datasets": [vm_train_ds, vm_test_ds],
    },
)
test.log()
test = vm.tests.run_test(
    "validmind.model_validation.statsmodels.RegressionCoeffsPlot",
    inputs={
        "models": [vm_model],
    },
)
test.log()
test = vm.tests.run_test(
    "validmind.model_validation.statsmodels.RegressionModelsCoeffs",
    inputs={
        "models": [vm_model],
    },
)
test.log()

Run tests for model evaluation

Once we are satisfied with the trained model after inspecting the coefficients, we elevate our evaluation by examining more detailed performance metrics — such as the confusion matrix, Gini coefficient, and various visualizations. Here we also begin to examine the credit scores, comparing them across the test and training datasets to see how effectively they distinguish between defaulted and non-defaulted customers.

These tests will help us to check whether the calibration of the scorecard is fit for purpose. Below is a list of tests we use to perform a thorough evaluation of both the binary classification model and the scorecard:

  • Classifier performance: Summarizing logistic regression metrics
  • GINI table: Assessing the discriminatory power of the model
  • Confusion matrix: Understanding classification accuracy
  • ROC curve: Plotting the trade-off between sensitivity and specificity
  • Prediction probabilities histogram: Distributing predictions to visualize outcomes
  • Cumulative prediction probabilities: Cumulative probability analysis for predictions
  • Scorecard histogram: Evaluating the distribution of scorecard points
test = vm.tests.run_test(
    "validmind.model_validation.sklearn.ClassifierPerformance:train_dataset",
    inputs={
        "dataset": vm_train_ds,
        "model": vm_model,
    },
)
test.log()
test = vm.tests.run_test(
    "validmind.model_validation.sklearn.ClassifierPerformance:test_dataset",
    inputs={
        "dataset": vm_test_ds,
        "model": vm_model,
    },
)
test.log()
test = vm.tests.run_test(
    "validmind.model_validation.statsmodels.GINITable",
    inputs={
        "datasets": [vm_train_ds, vm_test_ds],
        "model": vm_model,
    },
)
test.log()
test = vm.tests.run_test(
    "validmind.model_validation.sklearn.ConfusionMatrix",
    inputs={
        "dataset": vm_test_ds,
        "model": vm_model,
    },
)
test.log()
test = vm.tests.run_test(
    "validmind.model_validation.sklearn.ROCCurve",
    inputs={
        "model": vm_model,
        "dataset": vm_test_ds,
    },
)
test.log()
test = vm.tests.run_test(
    "validmind.model_validation.statsmodels.PredictionProbabilitiesHistogram",
    inputs={
        "model": vm_model,
        "datasets": [vm_train_ds, vm_test_ds],
    },
)
test.log()
test = vm.tests.run_test(
    "validmind.model_validation.statsmodels.CumulativePredictionProbabilities",
    inputs={
        "model": vm_model,
        "datasets": [vm_train_ds, vm_test_ds],
    },
)
test.log()
test = vm.tests.run_test(
    "validmind.model_validation.statsmodels.ScorecardHistogram",
    inputs={
        "model": vm_model,
        "datasets": [vm_train_ds, vm_test_ds],
    },
    params={
        "score_column": "glm_scores",
    },
)
test.log()

Run tests for model explainability

Following the detailed evaluation of the model through the performance metrics above, we then focus on model explainability to further understand the contributions of individual features. Model explainability is the ability to understand and interpret the decisions made by a machine learning model. This analysis is crucial for ensuring that our credit scoring model is not only effective but also interpretable in practical scenarios.

Here are the key tests we deploy to analyze the model’s explainability after evaluating its overall performance:

  • Regression permutation feature importance: Identifies which features most significantly affect the model’s predictions by observing changes in performance when feature values are shuffled
  • Features AUC: Determines the discriminative power of each feature, showcasing how well each can independently predict the outcome
test = vm.tests.run_test(
    "validmind.model_validation.statsmodels.RegressionPermutationFeatureImportance",
    inputs={
        "model": vm_model,
        "dataset": vm_test_ds,
    },
)
test.log()
test = vm.tests.run_test(
    "validmind.model_validation.FeaturesAUC",
    inputs={
        "model": vm_model,
        "dataset": vm_test_ds,
    },
)
test.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 Platform UI, go to the Documentation page for the model you registered earlier.

  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:

Or, visit our documentation to learn more about ValidMind.