{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Document an application scorecard model\n",
    "\n",
    "Build and document an *application scorecard model* with the ValidMind Library by using Kaggle's [Lending Club](https://www.kaggle.com/datasets/devanshi23/loan-data-2007-2014/data) sample dataset to build a simple application scorecard.\n",
    "\n",
    "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. \n",
    "\n",
    "- 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. \n",
    "- Application scorecard models enable lenders to manage risk efficiently while making the loan application process faster and more transparent for applicants.\n",
    "\n",
    "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."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Contents    \n",
    "- [About ValidMind](#toc1_)    \n",
    "  - [Before you begin](#toc1_1_)    \n",
    "  - [New to ValidMind?](#toc1_2_)    \n",
    "  - [Key concepts](#toc1_3_)    \n",
    "- [Install the ValidMind Library](#toc2_)    \n",
    "- [Initialize the ValidMind Library](#toc3_)    \n",
    "  - [Get your code snippet](#toc3_1_)  \n",
    "- [Initialize the Python environment](#toc4_)    \n",
    "  - [Preview the documentation template](#toc4_1_)    \n",
    "- [Load the sample dataset](#toc5_)    \n",
    "  - [Prepocess the dataset](#toc5_1_)    \n",
    "  - [Feature engineering](#toc5_2_)    \n",
    "- [Train the model](#toc6_)    \n",
    "  - [Compute probabilities](#toc6_1_)    \n",
    "  - [Compute binary predictions](#toc6_2_)    \n",
    "  - [Compute scores](#toc6_3_)    \n",
    "- [Document the model](#toc7_)    \n",
    "  - [Initialize the ValidMind datasets](#toc7_1_)    \n",
    "  - [Initialize a model object](#toc7_2_)    \n",
    "  - [Assign prediction values and probabilities to the datasets](#toc7_3_)    \n",
    "  - [Assign scores to the datasets](#toc7_4_)    \n",
    "  - [Data validation](#toc7_5_)    \n",
    "    - [Run tests for raw data tests](#toc7_5_1_)    \n",
    "    - [Run tests for preprocessed data](#toc7_5_2_)    \n",
    "    - [Run tests for WoE analysis](#toc7_5_3_)    \n",
    "  - [Model validation](#toc7_6_)    \n",
    "    - [Run tests for model training](#toc7_6_1_)    \n",
    "    - [Run tests for model evaluation](#toc7_6_2_)    \n",
    "    - [Run tests for model explainability](#toc7_6_3_)    \n",
    "- [Next steps](#toc8_)    \n",
    "  - [Work with your model documentation](#toc8_1_)    \n",
    "  - [Discover more learning resources](#toc8_2_)\n",
    "- [Upgrade ValidMind](#toc9_)    \n",
    "\n",
    "<!-- vscode-jupyter-toc-config\n",
    "\tnumbering=false\n",
    "\tanchor=true\n",
    "\tflat=false\n",
    "\tminLevel=2\n",
    "\tmaxLevel=4\n",
    "\t/vscode-jupyter-toc-config -->\n",
    "<!-- THIS CELL WILL BE REPLACED ON TOC UPDATE. DO NOT WRITE YOUR TEXT IN THIS CELL -->"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id='toc1_'></a>\n",
    "\n",
    "## About ValidMind\n",
    "ValidMind is a suite of tools for managing model risk, including risk associated with AI and statistical models.\n",
    "\n",
    "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.\n",
    "\n",
    "<a id='toc1_1_'></a>\n",
    "\n",
    "### Before you begin\n",
    "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.\n",
    "\n",
    "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](https://docs.python.org/3/installing/index.html).\n",
    "\n",
    "<a id='toc1_2_'></a>\n",
    "\n",
    "### New to ValidMind?\n",
    "If you haven't already seen our documentation on the [ValidMind Library](https://docs.validmind.ai/developer/validmind-library.html), 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.\n",
    "\n",
    "<div class=\"alert alert-block alert-info\" style=\"background-color: #B5B5B510; color: black; border: 1px solid #083E44; border-left-width: 5px; box-shadow: 2px 2px 4px rgba(0, 0, 0, 0.2);border-radius: 5px;\"><span style=\"color: #083E44;\"><b>For access to all features available in this notebook, create a free ValidMind account.</b></span>\n",
    "<br></br>\n",
    "Signing up is FREE — <a href=\"https://docs.validmind.ai/guide/configuration/register-with-validmind.html\" style=\"color: #DE257E;\"><b>Register with ValidMind</b></a></div>\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id='toc1_3_'></a>\n",
    "\n",
    "### Key concepts\n",
    "\n",
    "**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.\n",
    "\n",
    "**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.\n",
    "\n",
    "**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.\n",
    "\n",
    "**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.\n",
    "\n",
    "**Inputs**: Objects to be evaluated and documented in the ValidMind Library. They can be any of the following:\n",
    "\n",
    "- **model**: A single model that has been initialized in ValidMind with [`vm.init_model()`](https://docs.validmind.ai/validmind/validmind.html#init_model).\n",
    "- **dataset**: Single dataset that has been initialized in ValidMind with [`vm.init_dataset()`](https://docs.validmind.ai/validmind/validmind.html#init_dataset).\n",
    "- **models**: A list of ValidMind models - usually this is used when you want to compare multiple models in your custom test.\n",
    "- **datasets**: A list of ValidMind datasets - usually this is used when you want to compare multiple datasets in your custom test. See this [example](https://docs.validmind.ai/notebooks/how_to/run_tests_that_require_multiple_datasets.html) for more information.\n",
    "\n",
    "**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.\n",
    "\n",
    "**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.\n",
    "\n",
    "**Test suites**: Collections of tests designed to run together to automate and generate model documentation end-to-end for specific use-cases.\n",
    "\n",
    "Example: The [`classifier_full_suite`](https://docs.validmind.ai/validmind/validmind/test_suites/classifier.html#ClassifierFullSuite) test suite runs tests from the [`tabular_dataset`](https://docs.validmind.ai/validmind/validmind/test_suites/tabular_datasets.html) and [`classifier`](https://docs.validmind.ai/validmind/validmind/test_suites/classifier.html) test suites to fully document the data and model sections for binary classification model use-cases."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id='toc2_'></a>\n",
    "\n",
    "## Install the ValidMind Library\n",
    "\n",
    "To install the library:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%pip install -q validmind"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id='toc3_'></a>\n",
    "\n",
    "## Initialize the ValidMind Library\n",
    "\n",
    "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.\n",
    "\n",
    "<a id='toc3_1_'></a>\n",
    "\n",
    "### Get your code snippet\n",
    "\n",
    "1. In a browser, [log in to ValidMind](https://docs.validmind.ai/guide/configuration/log-in-to-validmind.html).\n",
    "\n",
    "2. In the left sidebar, navigate to **Model Inventory** and click **+ Register Model**.\n",
    "\n",
    "3. Enter the model details and click **Continue**. ([Need more help?](https://docs.validmind.ai/guide/model-inventory/register-models-in-inventory.html))\n",
    "\n",
    "   For example, to register a model for use with this notebook, select:\n",
    "\n",
    "   - Documentation template: `Credit Risk Scorecard`\n",
    "   - Use case: `Credit Risk - CECL`\n",
    "\n",
    "   You can fill in other options according to your preference.\n",
    "\n",
    "4. Go to **Getting Started** and click **Copy snippet to clipboard**.\n",
    "\n",
    "Next, [load your model identifier credentials from an `.env` file](https://docs.validmind.ai/developer/model-documentation/store-credentials-in-env-file.html) or replace the placeholder with your own code snippet:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Load your model identifier credentials from an `.env` file\n",
    "\n",
    "%load_ext dotenv\n",
    "%dotenv .env\n",
    "\n",
    "# Or replace with your code snippet\n",
    "\n",
    "import validmind as vm\n",
    "\n",
    "vm.init(\n",
    "    # api_host=\"...\",\n",
    "    # api_key=\"...\",\n",
    "    # api_secret=\"...\",\n",
    "    # model=\"...\",\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id='toc4_'></a>\n",
    "\n",
    "## Initialize the Python environment\n",
    "\n",
    "Next, let's import the necessary libraries and set up your Python environment for data analysis:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import statsmodels.api as sm\n",
    "\n",
    "%matplotlib inline"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id='toc4_1_'></a>\n",
    "\n",
    "### Preview the documentation template\n",
    "\n",
    "A template predefines sections for your model documentation and provides a general outline to follow, making the documentation process much easier.\n",
    "\n",
    "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:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "vm.preview_template()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id='toc5_'></a>\n",
    "\n",
    "## Load the sample dataset\n",
    "\n",
    "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](https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.html), a two-dimensional tabular data structure that makes use of rows and columns:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Import the sample dataset from the library\n",
    "\n",
    "from validmind.datasets.credit_risk import lending_club\n",
    "\n",
    "df = lending_club.load_data(source=\"offline\")\n",
    "\n",
    "df.head()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id='toc5_1_'></a>\n",
    "\n",
    "### Prepocess the dataset\n",
    "\n",
    "In the preprocessing step we perform a number of operations to get ready for building our application scorecard. \n",
    "\n",
    "We use the `lending_club.preprocess` to simplify preprocessing. This function performs the following operations: \n",
    "- Filters the dataset to include only loans for debt consolidation or credit card purposes\n",
    "- Removes loans classified under the riskier grades \"F\" and \"G\"\n",
    "- Excludes uncommon home ownership types and standardizes employment length and loan terms into numerical formats\n",
    "- Discards unnecessary fields and any entries with missing information to maintain a clean and robust dataset for modeling"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "preprocess_df = lending_club.preprocess(df)\n",
    "preprocess_df.head()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id='toc5_2_'></a>\n",
    "\n",
    "### Feature engineering\n",
    "\n",
    "In the feature engineering phase, we apply specific transformations to optimize the dataset for predictive modeling in our application scorecard. \n",
    "\n",
    "Using the `ending_club.feature_engineering()` function, we conduct the following operations:\n",
    "- **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.\n",
    "- **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."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "fe_df = lending_club.feature_engineering(preprocess_df)\n",
    "fe_df.head()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id='toc6_'></a>\n",
    "\n",
    "## Train the model\n",
    "\n",
    "In this section, we focus on constructing and refining our predictive model. \n",
    "- We begin by dividing our data, which is based on Weight of Evidence (WoE) features, into training and testing sets (`train_df`, `test_df`). \n",
    "- 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.\n",
    "- Additionally, by setting `add_constant=True`, we include an intercept term in our model.\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "train_df, test_df = lending_club.split(fe_df, add_constant=True)\n",
    "\n",
    "x_train = train_df.drop(lending_club.target_column, axis=1)\n",
    "y_train = train_df[lending_club.target_column]\n",
    "x_test = test_df.drop(lending_club.target_column, axis=1)\n",
    "y_test = test_df[lending_club.target_column]\n",
    "\n",
    "# Define the model\n",
    "model = sm.GLM(y_train, x_train, family=sm.families.Binomial())\n",
    "\n",
    "# Fit the model\n",
    "model = model.fit()\n",
    "model.summary()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id='toc6_1_'></a>\n",
    "\n",
    "### Compute probabilities"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "train_probabilities = model.predict(x_train)\n",
    "test_probabilities = model.predict(x_test)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id='toc6_2_'></a>\n",
    "\n",
    "### Compute binary predictions"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "cut_off_threshold = 0.5\n",
    "train_binary_predictions = (train_probabilities > cut_off_threshold).astype(int)\n",
    "test_binary_predictions = (test_probabilities > cut_off_threshold).astype(int)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id='toc6_3_'></a>\n",
    "\n",
    "### Compute scores\n",
    "\n",
    "In this phase, we translate model predictions into actionable scores using probability estimates generated by our trained model. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Compute scores from the probabilities\n",
    "train_scores = lending_club.compute_scores(train_probabilities)\n",
    "test_scores = lending_club.compute_scores(test_probabilities)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id='toc7_'></a>\n",
    "\n",
    "## Document the model\n",
    "\n",
    "To document the model with the ValidMind Library, you'll need to:\n",
    "1. Preprocess the raw dataset\n",
    "2. Initialize some training and test datasets\n",
    "3. Initialize a model object you can use for testing\n",
    "4. Run the full suite of tests"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id='toc7_1_'></a>\n",
    "\n",
    "### Initialize the ValidMind datasets\n",
    "\n",
    "Before you can run tests, you must first initialize a ValidMind dataset object using the [`init_dataset`](https://docs.validmind.ai/validmind/validmind.html#init_dataset) function from the ValidMind (`vm`) module.\n",
    "\n",
    "This function takes a number of arguments:\n",
    "\n",
    "- `dataset`: The dataset that you want to provide as input to tests.\n",
    "- `input_id`: A unique identifier that allows tracking what inputs are used when running each individual test.\n",
    "- `target_column`: A required argument if tests require access to true values. This is the name of the target column in the dataset.\n",
    "\n",
    "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()`](https://docs.validmind.ai/validmind/validmind.html#init_dataset):"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "vm_raw_dataset = vm.init_dataset(\n",
    "    dataset=df,\n",
    "    input_id=\"raw_dataset\",\n",
    "    target_column=lending_club.target_column,\n",
    ")\n",
    "\n",
    "vm_preprocess_dataset = vm.init_dataset(\n",
    "    dataset=preprocess_df,\n",
    "    input_id=\"preprocess_dataset\",\n",
    "    target_column=lending_club.target_column,\n",
    ")\n",
    "\n",
    "vm_fe_dataset = vm.init_dataset(\n",
    "    dataset=fe_df,\n",
    "    input_id=\"fe_dataset\",\n",
    "    target_column=lending_club.target_column,\n",
    ")\n",
    "\n",
    "vm_train_ds = vm.init_dataset(\n",
    "    dataset=train_df,\n",
    "    input_id=\"train_dataset\",\n",
    "    target_column=lending_club.target_column,\n",
    ")\n",
    "\n",
    "vm_test_ds = vm.init_dataset(\n",
    "    dataset=test_df,\n",
    "    input_id=\"test_dataset\",\n",
    "    target_column=lending_club.target_column,\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id='toc7_2_'></a>\n",
    "\n",
    "### Initialize a model object\n",
    "\n",
    "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()`](https://docs.validmind.ai/validmind/validmind.html#init_model):"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "vm_model = vm.init_model(\n",
    "    model,\n",
    "    input_id=\"glm_model\",\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id='toc7_3_'></a>\n",
    "\n",
    "### Assign prediction values and probabilities to the datasets\n",
    "\n",
    "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. \n",
    "- These tasks are achieved through the use of the `assign_predictions()` method associated with the VM `dataset` object.\n",
    "- This method links the model's class prediction values and probabilities to our VM train and test datasets."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "vm_train_ds.assign_predictions(\n",
    "    model=vm_model,\n",
    "    prediction_values=train_binary_predictions,\n",
    "    prediction_probabilities=train_probabilities,\n",
    ")\n",
    "\n",
    "vm_test_ds.assign_predictions(\n",
    "    model=vm_model,\n",
    "    prediction_values=test_binary_predictions,\n",
    "    prediction_probabilities=test_probabilities,\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id='toc7_4_'></a>\n",
    "\n",
    "### Assign scores to the datasets\n",
    "\n",
    "Credit scorecards revolve around scores computed from model predictions rather than raw predictions, so let's compute some scores!\n",
    "\n",
    "- 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.\n",
    "- This approach allows us to append scores directly to our data, maintaining a streamlined and coherent dataset ready for analysis."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "vm_train_ds.add_extra_column(\"glm_scores\", train_scores)\n",
    "vm_test_ds.add_extra_column(\"glm_scores\", test_scores)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id='toc7_5_'></a>\n",
    "\n",
    "### Data validation\n",
    "\n",
    "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. \n",
    "\n",
    "In this section, we use tests to collect evidence across raw, preprocessed, and feature-engineered datasets."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id='toc7_5_1_'></a>\n",
    "\n",
    "#### Run tests for raw data tests\n",
    "\n",
    "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:\n",
    "\n",
    "- **Tabular description tables:** Statistical summary for each variable\n",
    "- **Missing values bar plot:** Plots presence of any missing data\n",
    "\n",
    "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 ValidMind Platform."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "test = vm.tests.run_test(\n",
    "    \"validmind.data_validation.TabularDescriptionTables:raw_dataset\",\n",
    "    input_grid={\n",
    "        \"dataset\": [vm_raw_dataset],\n",
    "    },\n",
    ")\n",
    "test.log()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "test = vm.tests.run_test(\n",
    "    \"validmind.data_validation.MissingValuesBarPlot:raw_dataset\",\n",
    "    input_grid={\n",
    "        \"dataset\": [vm_raw_dataset]\n",
    "    },\n",
    ")\n",
    "test.log()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id='toc7_5_2_'></a>\n",
    "\n",
    "#### Run tests for preprocessed data\n",
    "\n",
    "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:\n",
    "\n",
    "- **Tabular description tables:** Checking structural integrity after preprocessing\n",
    "- **IQR outliers table:** Searching for statistical anomalies that may impact results\n",
    "- **Class imbalance:** Investigating the proportionality of outcome classes\n",
    "- **Tabular numerical histograms:** Visualizing distributions for numerical variables\n",
    "- **Tabular categorical bar plots:** Analyzing frequencies of categorical variables\n",
    "- **Target rate bar plots:** Examining the distribution of the target variable across categories\n",
    "- **Pearson correlation matrix:** Identifying linear relationships between variables\n",
    "\n",
    "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.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "test = vm.tests.run_test(\n",
    "    \"validmind.data_validation.TabularDescriptionTables:preprocess_dataset\",\n",
    "    input_grid={\n",
    "        \"dataset\": [vm_preprocess_dataset]\n",
    "    },\n",
    ")\n",
    "test.log()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "test = vm.tests.run_test(\n",
    "    \"validmind.data_validation.IQROutliersTable\",\n",
    "    input_grid={\n",
    "        \"dataset\": [vm_preprocess_dataset]\n",
    "    },\n",
    ")\n",
    "test.log()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "test = vm.tests.run_test(\n",
    "    \"validmind.data_validation.ClassImbalance\",\n",
    "    input_grid={\n",
    "        \"dataset\": [vm_preprocess_dataset]\n",
    "    },\n",
    ")\n",
    "test.log()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "test = vm.tests.run_test(\n",
    "    \"validmind.data_validation.TabularNumericalHistograms\",\n",
    "    input_grid={\n",
    "        \"dataset\": [vm_preprocess_dataset]\n",
    "    },\n",
    ")\n",
    "test.log()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "test = vm.tests.run_test(\n",
    "    \"validmind.data_validation.TabularCategoricalBarPlots\",\n",
    "    input_grid={\n",
    "        \"dataset\": [vm_preprocess_dataset]\n",
    "    },\n",
    ")\n",
    "test.log()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "test = vm.tests.run_test(\n",
    "    \"validmind.data_validation.TargetRateBarPlots\",\n",
    "    input_grid={\n",
    "        \"dataset\": [vm_preprocess_dataset]\n",
    "    },\n",
    "    params={\n",
    "        \"default_column\": lending_club.target_column,\n",
    "        \"columns\": None,\n",
    "    },\n",
    ")\n",
    "test.log()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "test = vm.tests.run_test(\n",
    "    \"validmind.data_validation.PearsonCorrelationMatrix\",\n",
    "    input_grid={\n",
    "        \"dataset\": [vm_preprocess_dataset]\n",
    "    },\n",
    ")\n",
    "test.log()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "test = vm.tests.run_test(\n",
    "    \"validmind.data_validation.HighPearsonCorrelation\",\n",
    "    input_grid={\n",
    "        \"dataset\": [vm_preprocess_dataset]\n",
    "    },\n",
    ")\n",
    "test.log()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id='toc7_5_3_'></a>\n",
    "\n",
    "#### Run tests for WoE analysis\n",
    "\n",
    "To ensure data segmentation aligns with predictive value, we perform detailed tests on the following:\n",
    "\n",
    "- **WOE bin table:** This test checks the bins and their corresponding Weight of Evidence values, ensuring accuracy and relevance.\n",
    "- **WOE bin plots:** These plots display the distribution of WoE across the data spectrum, providing a visual assessment of alignment and consistency."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "test = vm.tests.run_test(\n",
    "    \"validmind.data_validation.WOEBinTable\",\n",
    "    input_grid={\n",
    "        \"dataset\": [vm_preprocess_dataset]\n",
    "    },\n",
    "    params={\n",
    "        \"breaks_adj\": lending_club.breaks_adj,\n",
    "    },\n",
    ")\n",
    "test.log()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "test = vm.tests.run_test(\n",
    "    \"validmind.data_validation.WOEBinPlots\",\n",
    "    input_grid={\n",
    "        \"dataset\": [vm_preprocess_dataset]\n",
    "    },\n",
    "    params={\n",
    "        \"breaks_adj\": lending_club.breaks_adj,\n",
    "    },\n",
    ")\n",
    "test.log()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id='toc7_6_'></a>\n",
    "\n",
    "### Model validation\n",
    "\n",
    "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? \n",
    "\n",
    "Tests are applied to both training and evaluation stages to ensure robustness and accuracy."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id='toc7_6_1_'></a>\n",
    "\n",
    "#### Run tests for model training\n",
    "\n",
    "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. \n",
    "\n",
    "These tests assist us with this inspection:\n",
    "\n",
    "- **Dataset split:** Assesses the distribution of data across training and testing sets\n",
    "- **Regression coeffs plot:** Visual inspection of the model's coefficients\n",
    "- **Regression models coeffs:** Detailed evaluation of the regression coefficients' values\n",
    "\n",
    "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."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "test = vm.tests.run_test(\n",
    "    \"validmind.data_validation.DatasetSplit\",\n",
    "    inputs={\n",
    "        \"datasets\": [vm_train_ds, vm_test_ds],\n",
    "    },\n",
    ")\n",
    "test.log()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "test = vm.tests.run_test(\n",
    "    \"validmind.model_validation.statsmodels.RegressionCoeffs\",\n",
    "    input_grid={\n",
    "        \"model\": [vm_model]\n",
    "    },\n",
    ")\n",
    "test.log()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id='toc7_6_2_'></a>\n",
    "\n",
    "#### Run tests for model evaluation\n",
    "\n",
    "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. \n",
    "\n",
    "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: \n",
    "\n",
    "- **Classifier performance:** Summarizing logistic regression metrics\n",
    "- **GINI table:** Assessing the discriminatory power of the model\n",
    "- **Confusion matrix:** Understanding classification accuracy\n",
    "- **ROC curve:** Plotting the trade-off between sensitivity and specificity\n",
    "- **Prediction probabilities histogram:** Distributing predictions to visualize outcomes\n",
    "- **Cumulative prediction probabilities:** Cumulative probability analysis for predictions\n",
    "- **Scorecard histogram:** Evaluating the distribution of scorecard points"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "test = vm.tests.run_test(\n",
    "    \"validmind.model_validation.sklearn.ClassifierPerformance\",\n",
    "    input_grid={\n",
    "        \"dataset\": [vm_train_ds, vm_test_ds],\n",
    "        \"model\": [vm_model],\n",
    "    },\n",
    ")\n",
    "test.log()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "test = vm.tests.run_test(\n",
    "    \"validmind.model_validation.statsmodels.GINITable\",\n",
    "    input_grid={\n",
    "        \"dataset\": [vm_train_ds, vm_test_ds],\n",
    "        \"model\": [vm_model],\n",
    "    },\n",
    ")\n",
    "test.log()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "test = vm.tests.run_test(\n",
    "    \"validmind.model_validation.sklearn.ConfusionMatrix\",\n",
    "    input_grid={\n",
    "        \"dataset\": [vm_train_ds, vm_test_ds],\n",
    "        \"model\": [vm_model],\n",
    "    },\n",
    ")\n",
    "test.log()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "test = vm.tests.run_test(\n",
    "    \"validmind.model_validation.sklearn.ROCCurve\",\n",
    "    input_grid={\n",
    "        \"dataset\": [vm_train_ds, vm_test_ds],\n",
    "        \"model\": [vm_model],\n",
    "    },\n",
    ")\n",
    "test.log()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "test = vm.tests.run_test(\n",
    "    \"validmind.model_validation.statsmodels.PredictionProbabilitiesHistogram\",\n",
    "    input_grid={\n",
    "        \"dataset\": [vm_train_ds, vm_test_ds],\n",
    "        \"model\": [vm_model],\n",
    "    },\n",
    ")\n",
    "test.log()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "test = vm.tests.run_test(\n",
    "    \"validmind.model_validation.statsmodels.CumulativePredictionProbabilities\",\n",
    "    input_grid={\n",
    "        \"model\": [vm_model],\n",
    "        \"dataset\": [vm_train_ds, vm_test_ds],\n",
    "    },\n",
    ")\n",
    "test.log()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "test = vm.tests.run_test(\n",
    "    \"validmind.model_validation.statsmodels.ScorecardHistogram\",\n",
    "    input_grid={\n",
    "        \"dataset\": [vm_train_ds, vm_test_ds],\n",
    "    },\n",
    "    params={\n",
    "        \"score_column\": \"glm_scores\",\n",
    "    },\n",
    ")\n",
    "test.log()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id='toc7_6_3_'></a>\n",
    "\n",
    "#### Run tests for model explainability\n",
    "\n",
    "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. \n",
    "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.\n",
    "\n",
    "Here are the key tests we deploy to analyze the model's explainability after evaluating its overall performance:\n",
    "\n",
    "- **Regression permutation feature importance:** Identifies which features most significantly affect the model's predictions by observing changes in performance when feature values are shuffled\n",
    "- **Features AUC:** Determines the discriminative power of each feature, showcasing how well each can independently predict the outcome"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "test = vm.tests.run_test(\n",
    "    \"validmind.model_validation.statsmodels.RegressionPermutationFeatureImportance\",\n",
    "    input_grid={\n",
    "        \"model\": [vm_model],\n",
    "        \"dataset\": [vm_train_ds, vm_test_ds],\n",
    "    },\n",
    ")\n",
    "test.log()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "test = vm.tests.run_test(\n",
    "    \"validmind.model_validation.FeaturesAUC\",\n",
    "    input_grid={\n",
    "        \"model\": [vm_model],\n",
    "        \"dataset\": [vm_train_ds, vm_test_ds],\n",
    "    },\n",
    ")\n",
    "test.log()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id='toc8_'></a>\n",
    "\n",
    "## Next steps\n",
    "\n",
    "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.\n",
    "\n",
    "<a id='toc8_1_'></a>\n",
    "\n",
    "### Work with your model documentation\n",
    "\n",
    "1. In the ValidMind Platform, go to the **Documentation** page for the model you registered earlier. ([Need more help?](https://docs.validmind.ai/guide/model-documentation/working-with-model-documentation.html))\n",
    "\n",
    "2. Expand the following sections and take a look around:\n",
    "\n",
    "   - **2. Data Preparation**\n",
    "   - **3. Model Development**\n",
    "\n",
    "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.\n",
    "\n",
    "<a id='toc8_2_'></a>\n",
    "\n",
    "### Discover more learning resources\n",
    "\n",
    "We offer many interactive notebooks to help you document models:\n",
    "\n",
    "- [Run tests & test suites](https://docs.validmind.ai/developer/model-testing/testing-overview.html)\n",
    "- [Code samples](https://docs.validmind.ai/developer/samples-jupyter-notebooks.html)\n",
    "\n",
    "Or, visit our [documentation](https://docs.validmind.ai/) to learn more about ValidMind."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id='toc9_'></a>\n",
    "\n",
    "## Upgrade ValidMind\n",
    "\n",
    "<div class=\"alert alert-block alert-info\" style=\"background-color: #B5B5B510; color: black; border: 1px solid #083E44; border-left-width: 5px; box-shadow: 2px 2px 4px rgba(0, 0, 0, 0.2);border-radius: 5px;\">After installing ValidMind, you’ll want to periodically make sure you are on the latest version to access any new features and other enhancements.</div>\n",
    "\n",
    "Retrieve the information for the currently installed version of ValidMind:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%pip show validmind"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "If the version returned is lower than the version indicated in our [production open-source code](https://github.com/validmind/validmind-library/blob/prod/validmind/__version__.py), restart your notebook and run:\n",
    "\n",
    "```bash\n",
    "%pip install --upgrade validmind\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You may need to restart your kernel after running the upgrade package for changes to be applied."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.14"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
