{
 "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": [
    "<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:"
   ]
  },
  {
   "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 = \"https://api.prod.validmind.ai/api/v1/tracking\",\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": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "import xgboost as xgb\n",
    "from sklearn.ensemble import RandomForestClassifier\n",
    "\n",
    "from validmind.datasets.credit_risk import lending_club\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": [
    "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."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Split the data\n",
    "train_df, test_df = lending_club.split(fe_df, test_size=0.2)\n",
    "\n",
    "x_train = train_df.drop(lending_club.target_column, axis=1)\n",
    "y_train = train_df[lending_club.target_column]\n",
    "\n",
    "x_test = test_df.drop(lending_club.target_column, axis=1)\n",
    "y_test = test_df[lending_club.target_column]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Define the XGBoost model\n",
    "xgb_model = xgb.XGBClassifier(\n",
    "    n_estimators=50, \n",
    "    random_state=42, \n",
    "    early_stopping_rounds=10\n",
    ")\n",
    "xgb_model.set_params(\n",
    "    eval_metric=[\"error\", \"logloss\", \"auc\"],\n",
    ")\n",
    "\n",
    "# Fit the model\n",
    "xgb_model.fit(\n",
    "    x_train, \n",
    "    y_train,\n",
    "    eval_set=[(x_test, y_test)],\n",
    "    verbose=False\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Define the Random Forest model\n",
    "rf_model = RandomForestClassifier(\n",
    "    n_estimators=50, \n",
    "    random_state=42,\n",
    ")\n",
    "\n",
    "# Fit the model\n",
    "rf_model.fit(x_train, y_train)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id='toc6_1_'></a>\n",
    "\n",
    "### Compute probabilities"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [],
   "source": [
    "train_xgb_prob = xgb_model.predict_proba(x_train)[:, 1]\n",
    "test_xgb_prob = xgb_model.predict_proba(x_test)[:, 1]\n",
    "\n",
    "train_rf_prob = rf_model.predict_proba(x_train)[:, 1]\n",
    "test_rf_prob = rf_model.predict_proba(x_test)[:, 1]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id='toc6_2_'></a>\n",
    "\n",
    "### Compute binary predictions"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [],
   "source": [
    "cut_off_threshold = 0.3\n",
    "\n",
    "train_xgb_binary_predictions = (train_xgb_prob > cut_off_threshold).astype(int)\n",
    "test_xgb_binary_predictions = (test_xgb_prob > cut_off_threshold).astype(int)\n",
    "\n",
    "train_rf_binary_predictions = (train_rf_prob > cut_off_threshold).astype(int)\n",
    "test_rf_binary_predictions = (test_rf_prob > cut_off_threshold).astype(int)"
   ]
  },
  {
   "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": 13,
   "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": 14,
   "metadata": {},
   "outputs": [],
   "source": [
    "vm_xgb_model = vm.init_model(\n",
    "    xgb_model,\n",
    "    input_id=\"xgb_model\",\n",
    ")\n",
    "\n",
    "vm_rf_model = vm.init_model(\n",
    "    rf_model,\n",
    "    input_id=\"rf_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": 15,
   "metadata": {},
   "outputs": [],
   "source": [
    "# XGBoost\n",
    "vm_train_ds.assign_predictions(\n",
    "    model=vm_xgb_model,\n",
    "    prediction_values=train_xgb_binary_predictions,\n",
    "    prediction_probabilities=train_xgb_prob,\n",
    ")\n",
    "\n",
    "vm_test_ds.assign_predictions(\n",
    "    model=vm_xgb_model,\n",
    "    prediction_values=test_xgb_binary_predictions,\n",
    "    prediction_probabilities=test_xgb_prob,\n",
    ")\n",
    "\n",
    "# Random Forest\n",
    "vm_train_ds.assign_predictions(\n",
    "    model=vm_rf_model,\n",
    "    prediction_values=train_rf_binary_predictions,\n",
    "    prediction_probabilities=train_rf_prob,\n",
    ")\n",
    "\n",
    "vm_test_ds.assign_predictions(\n",
    "    model=vm_rf_model,\n",
    "    prediction_values=test_rf_binary_predictions,\n",
    "    prediction_probabilities=test_rf_prob,\n",
    ")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Compute credit risk 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": [
    "train_xgb_scores = lending_club.compute_scores(train_xgb_prob)\n",
    "test_xgb_scores = lending_club.compute_scores(test_xgb_prob)\n",
    "\n",
    "# Assign scores to the datasets\n",
    "vm_train_ds.add_extra_column(\"xgb_scores\", train_xgb_scores)\n",
    "vm_test_ds.add_extra_column(\"xgb_scores\", test_xgb_scores)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Adding custom context to the LLM descriptions\n",
    "\n",
    "To enable the LLM descriptions context, you need to set the `VALIDMIND_LLM_DESCRIPTIONS_CONTEXT_ENABLED` environment variable to `1`. This will enable the LLM descriptions context, which will be used to provide additional context to the LLM descriptions. This is a global setting that will affect all tests."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "os.environ[\"VALIDMIND_LLM_DESCRIPTIONS_CONTEXT_ENABLED\"] = \"1\"\n",
    "\n",
    "context = \"\"\"\n",
    "FORMAT FOR THE LLM DESCRIPTIONS: \n",
    "    **<Test Name>** is designed to <begin with a concise overview of what the test does and its primary purpose, \n",
    "    extracted from the test description>.\n",
    "\n",
    "    The test operates by <write a paragraph about the test mechanism, explaining how it works and what it measures. \n",
    "    Include any relevant formulas or methodologies mentioned in the test description.>\n",
    "\n",
    "    The primary advantages of this test include <write a paragraph about the test's strengths and capabilities, \n",
    "    highlighting what makes it particularly useful for specific scenarios.>\n",
    "\n",
    "    Users should be aware that <write a paragraph about the test's limitations and potential risks. \n",
    "    Include both technical limitations and interpretation challenges. \n",
    "    If the test description includes specific signs of high risk, incorporate these here.>\n",
    "\n",
    "    **Key Insights:**\n",
    "\n",
    "    The test results reveal:\n",
    "\n",
    "    - **<insight title>**: <comprehensive description of one aspect of the results>\n",
    "    - **<insight title>**: <comprehensive description of another aspect>\n",
    "    ...\n",
    "\n",
    "    Based on these results, <conclude with a brief paragraph that ties together the test results with the test's \n",
    "    purpose and provides any final recommendations or considerations.>\n",
    "\n",
    "ADDITIONAL INSTRUCTIONS:\n",
    "    Present insights in order from general to specific, with each insight as a single bullet point with bold title.\n",
    "\n",
    "    For each metric in the test results, include in the test overview:\n",
    "    - The metric's purpose and what it measures\n",
    "    - Its mathematical formula\n",
    "    - The range of possible values\n",
    "    - What constitutes good/bad performance\n",
    "    - How to interpret different values\n",
    "\n",
    "    Each insight should progressively cover:\n",
    "    1. Overall scope and distribution\n",
    "    2. Complete breakdown of all elements with specific values\n",
    "    3. Natural groupings and patterns\n",
    "    4. Comparative analysis between datasets/categories\n",
    "    5. Stability and variations\n",
    "    6. Notable relationships or dependencies\n",
    "\n",
    "    Remember:\n",
    "    - Keep all insights at the same level (no sub-bullets or nested structures)\n",
    "    - Make each insight complete and self-contained\n",
    "    - Include specific numerical values and ranges\n",
    "    - Cover all elements in the results comprehensively\n",
    "    - Maintain clear, concise language\n",
    "    - Use only \"- **Title**: Description\" format for insights\n",
    "    - Progress naturally from general to specific observations\n",
    "\n",
    "\"\"\".strip()\n",
    "\n",
    "os.environ[\"VALIDMIND_LLM_DESCRIPTIONS_CONTEXT\"] = context"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id='toc6_5_'></a>\n",
    "\n",
    "### Run the full suite of tests\n",
    "\n",
    "This is where it all comes together: you are now ready to run the documentation tests for the model as defined by the documentation template you looked at earlier.\n",
    "\n",
    "The [`vm.run_documentation_tests`](https://docs.validmind.ai/validmind/validmind.html#run_documentation_tests) function finds and runs every test specified in the template and then uploads all the documentation and test artifacts that get generated to the ValidMind Platform.\n",
    "\n",
    "The function requires information about the inputs to use on every test. These inputs can be passed as an `inputs` argument if we want to use the same inputs for all tests. It's also possible to pass a `config` argument that has information about the `params` and `inputs` that each test requires. The `config` parameter is a dictionary with the following structure:\n",
    "\n",
    "```python\n",
    "config = {\n",
    "    \"<test-id>\": {\n",
    "        \"params\": {\n",
    "            \"param1\": \"value1\",\n",
    "            \"param2\": \"value2\",\n",
    "            ...\n",
    "        },\n",
    "        \"inputs\": {\n",
    "            \"input1\": \"value1\",\n",
    "            \"input2\": \"value2\",\n",
    "            ...\n",
    "        }\n",
    "    },\n",
    "    ...\n",
    "}\n",
    "```\n",
    "\n",
    "Each `<test-id>` above corresponds to the test driven block identifiers shown by `vm.preview_template()`. For this model, we will use the default parameters for all tests, but we'll need to specify the input configuration for each one. The method `get_demo_test_config()` below constructs the default input configuration for our demo."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from validmind.utils import preview_test_config\n",
    "\n",
    "test_config = lending_club.get_demo_test_config(x_test, y_test)\n",
    "preview_test_config(test_config)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now we can pass the input configuration to `vm.run_documentation_tests()` and run the full suite of tests. The variable `full_suite` then holds the result of these tests."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "full_suite = vm.run_documentation_tests(config=test_config)"
   ]
  },
  {
   "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": "validmind-eEL8LtKG-py3.10",
   "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.13"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
