{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Document multiple results for the same test\n",
    "\n",
    "Documentation templates facilitate the presentation of multiple unique test results for a single test. \n",
    "\n",
    "Consider various scenarios where you may intend to showcase results of the same test with diverse inputs:\n",
    "\n",
    "- **Comparing test results with varied parameter values:** Illustrate model performance by contrasting test results achieved with different parameter values to identify optimal settings.\n",
    "- **Displaying test results with distinct datasets:** Showcase test versatility by presenting results on diverse datasets, such as providing confusion matrices for both training and test data.\n",
    "- **Model comparison:** Conduct a comprehensive model evaluation by comparing tests like `ROC curve` and `Accuracy` to discern and select the superior-performing model.\n",
    "\n",
    "This interactive notebook guides you through the process of documenting a model with the ValidMind Library. It uses the [Bank Customer Churn Prediction](https://www.kaggle.com/code/kmalit/bank-customer-churn-prediction/data) sample dataset from Kaggle to train a simple classification model. As part of the notebook, you will learn how to render more than one unique test result for the same test while exploring how the documentation process works:\n",
    "\n",
    "- Initializing the ValidMind Library\n",
    "- Loading a sample dataset provided by the library to train a simple classification model\n",
    "- Running a ValidMind test suite to quickly generate documentation about the data and model\n"
   ]
  },
  {
   "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",
    "- [Update the customer churn demo template](#toc4_)    \n",
    "- [Initialize the Python environment](#toc5_)    \n",
    "  - [Preview the documentation template](#toc5_1_)    \n",
    "- [Load the sample dataset](#toc6_)    \n",
    "  - [Initialize a ValidMind dataset object](#toc6_1_)    \n",
    "- [Document the model](#toc7_)    \n",
    "  - [Prepare datasets](#toc7_1_)    \n",
    "  - [Initialize the training and test datasets](#toc7_2_)    \n",
    "  - [Run documentation tests](#toc7_3_)    \n",
    "  - [Run the individual tests using the `run_test`](#toc7_4_)    \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",
    "\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",
    "\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",
    "\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",
    "\n",
    "<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.\n"
   ]
  },
  {
   "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: `Binary classification`\n",
    "   - Use case: `Marketing/Sales - Attrition/Churn Management`\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:\n"
   ]
  },
  {
   "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",
    "## Update the customer churn demo template\n",
    "\n",
    "Before you initialize the ValidMind Library by running the notebook, edit the **Binary classification** template to make a copy of a test of interest and update it with different `result_id` fields for each entry:\n",
    "\n",
    "- Go to **Settings > Templates** and click on the **Binary classification** template. Let's say we want to show `Skewness` results for `training` and `test` datasets.\n",
    "\n",
    "To do this we replace\n",
    "\n",
    "```yaml\n",
    "- content_type: test\n",
    "  content_id: validmind.data_validation.Skewness\n",
    "```\n",
    "\n",
    "with\n",
    "\n",
    "```yaml\n",
    "- content_type: test\n",
    "  content_id: validmind.data_validation.Skewness:training_data\n",
    "- content_type: test\n",
    "  content_id: validmind.data_validation.Skewness:test_data\n",
    "```\n",
    "\n",
    "This way, we can show two results of the same test in the model document. Here, the `training_data` and `test_data` could be any string. However, they should be unique for the same test.\n",
    "\n",
    "- Click on **Prepare new version**, provide some version notes and click on **Save new version** to save a new version of this template.\n",
    "- Next, we need to swap our model documentation to use this new version of the template. Follow the steps on [Swap documentation templates](https://docs.validmind.ai/guide/model-documentation/swap-documentation-templates.html) to swap the template of our customer churn model.\n",
    "\n",
    "In the following sections we provide more context on how these `content_id` fields mentioned earlier get mapped to the actual tests.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id='toc5_'></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:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import xgboost as xgb\n",
    "\n",
    "from sklearn.metrics import accuracy_score\n",
    "from sklearn.model_selection import train_test_split\n",
    "\n",
    "%matplotlib inline"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id='toc5_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 will 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. You will see two blocks with different result IDs for skewness.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "vm.preview_template()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id='toc6_'></a>\n",
    "\n",
    "## Load the sample dataset\n",
    "\n",
    "The sample dataset used here is provided by the ValidMind library, along with a second, different dataset (`taiwan_credit`) you can try as well.\n",
    "\n",
    "To be able to use either sample dataset, you 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:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Import the sample dataset from the library\n",
    "\n",
    "from validmind.datasets.classification import customer_churn as demo_dataset\n",
    "\n",
    "df = demo_dataset.load_data()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id='toc6_1_'></a>\n",
    "\n",
    "### Initialize a ValidMind dataset object\n",
    "\n",
    "Before you can run a test suite, which are a collection of 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 raw dataset that you want to analyze\n",
    "- `target_column` — the name of the target column in the dataset\n",
    "- `class_labels` — the list of class labels used for classification model training\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "vm_dataset = vm.init_dataset(\n",
    "    input_id=\"raw_dataset\",\n",
    "    dataset=df,\n",
    "    target_column=demo_dataset.target_column,\n",
    "    class_labels=demo_dataset.class_labels,\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id='toc7_'></a>\n",
    "\n",
    "## Document the model\n",
    "\n",
    "As part of documenting the model with the ValidMind Library, you need to preprocess the raw dataset, initialize some training and test datasets, initialize a model object you can use for testing, and then run the full suite of tests.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id='toc7_1_'></a>\n",
    "\n",
    "### Prepare datasets\n",
    "\n",
    "DataFrame (df) preprocessing is simplified by employing `demo_dataset.preprocess` to partition it into distinct datasets (`train_df`, `validation_df`, and `test_df`)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "train_df, validation_df, test_df = demo_dataset.preprocess(df)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id='toc7_2_'></a>\n",
    "\n",
    "### Initialize the training and test datasets\n",
    "\n",
    "With the datasets ready, you can now initialize the training and test datasets (`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):\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "vm_train_ds = vm.init_dataset(\n",
    "    input_id=\"train_dataset\", dataset=train_df, target_column=demo_dataset.target_column\n",
    ")\n",
    "\n",
    "vm_test_ds = vm.init_dataset(\n",
    "    input_id=\"test_dataset\", dataset=test_df, target_column=demo_dataset.target_column\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id='toc7_3_'></a>\n",
    "\n",
    "### Run documentation tests\n",
    "\n",
    "Now specify `inputs` and `params` for individual tests using `config` parameter. The results for the both the datasets will be visible in the documentation. The `inputs` in the config get priority over global `inputs` in the `run_documentation_tests`.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "config = {\n",
    "    \"validmind.data_validation.Skewness:training_data\": {\n",
    "        \"params\": {\"max_threshold\": 1},\n",
    "        \"inputs\": {\"dataset\": vm_train_ds},\n",
    "    },\n",
    "    \"validmind.data_validation.Skewness:test_data\": {\n",
    "        \"params\": {\"max_threshold\": 1.5},\n",
    "        \"inputs\": {\"dataset\": vm_test_ds},\n",
    "    },\n",
    "}\n",
    "\n",
    "tests_suite = vm.run_documentation_tests(\n",
    "    inputs={\n",
    "        \"dataset\": vm_dataset,\n",
    "    },\n",
    "    config=config,\n",
    "    section=[\"data_preparation\"],\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id='toc7_4_'></a>\n",
    "\n",
    "### Run the individual tests using the `run_test`\n",
    "\n",
    "Now run the `Skewness` tests for training and test datasets. The results for the both the datasets will be visible in the documentation.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "test = vm.tests.run_test(\n",
    "    test_id=\"validmind.data_validation.Skewness:training_data\",\n",
    "    params={\"max_threshold\": 1},\n",
    "    inputs={\"dataset\": vm_train_ds},\n",
    ")\n",
    "test.log()\n",
    "\n",
    "test = vm.tests.run_test(\n",
    "    test_id=\"validmind.data_validation.Skewness:test_data\",\n",
    "    params={\"max_threshold\": 1.5},\n",
    "    inputs={\n",
    "        \"dataset\": 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. From the **Model Inventory** in the ValidMind Platform, go to the model you registered earlier. ([Need more help?](https://docs.validmind.ai/guide/model-inventory/working-with-model-inventory.html))\n",
    "\n",
    "2. Click and expand the **Model Development** section.\n",
    "\n",
    "3. Expand the **2. Data Preparation** section and take a look around.\n",
    "\n",
    "   You can now see the skewness tests results of training and test datasets in the `Data Preparation` section.\n",
    "\n",
    "From here, you can also make qualitative edits to model documentation, view guidelines, collaborate with validators, and submit your model documentation for approval when it's ready. [Learn more ...](https://docs.validmind.ai/guide/model-documentation/working-with-model-documentation.html)\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": {
  "colab": {
   "provenance": []
  },
  "gpuClass": "standard",
  "kernelspec": {
   "display_name": "validmind-1QuffXMV-py3.9",
   "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.8.13"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
