{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Quickstart for ongoing monitoring of models with ValidMind\n",
    "\n",
    "Welcome! In this quickstart guide, you'll learn how to seamlessly monitor your production models using the ValidMind Platform.\n",
    "\n",
    "We'll walk you through the process of initializing the ValidMind Library, loading a sample dataset and model, and running a monitoring test suite to quickly generate documentation about your new data and model.\n",
    "\n",
    "This notebook utilizes the [Bank Customer Churn Prediction](https://www.kaggle.com/code/kmalit/bank-customer-churn-prediction/data) dataset from Kaggle to train a simple classification model for demonstration purposes."
   ]
  },
  {
   "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 monitoring template](#toc4_1_)    \n",
    "- [Load the reference and monitoring datasets](#toc5_)    \n",
    "  - [Load the production model](#toc5_1_)    \n",
    "  - [Initialize the ValidMind datasets](#toc5_2_)    \n",
    "  - [Initialize a model object](#toc5_3_)    \n",
    "  - [Assign predictions to the datasets](#toc5_4_)    \n",
    "  - [Run the ongoing monitoring tests](#toc5_5_)    \n",
    "  - [Conduct target and feature drift testing](#toc5_6_)    \n",
    "    - [Feature drift tests](#toc5_6_1_)    \n",
    "  - [Model performance monitoring tests](#toc5_7_)    \n",
    "- [Next steps](#toc6_)    \n",
    "  - [Discover more learning resources](#toc6_1_)\n",
    "- [Upgrade ValidMind](#toc7_)    \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, validation, monitoring 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",
    "**Model monitoring documentation**: A comprehensive and structured record of a production model, including key elements such as data sources, inputs, performance metrics, and periodic evaluations. This documentation ensures transparency and visibility of the model's performance in the production environment.\n",
    "\n",
    "**Monitoring documentation template**: Similar to documentation template, The monitoring documentation template functions as a test suite and lays out the structure of model monitoring documentation, segmented into various sections and sub-sections. Monitoring documentation templates define the structure of your model monitoring 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."
   ]
  },
  {
   "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: `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:"
   ]
  },
  {
   "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",
    "    monitoring = True\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:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import xgboost as xgb\n",
    "import validmind as vm\n",
    "import pandas as pd\n",
    "import numpy as np\n",
    "import seaborn as sns\n",
    "import matplotlib.pyplot as plt\n",
    "from validmind.tests import run_test\n",
    "\n",
    "%matplotlib inline"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id='toc4_1_'></a>\n",
    "\n",
    "### Preview the monitoring template\n",
    "\n",
    "A template predefines sections for your model monitoring 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:\n"
   ]
  },
  {
   "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 reference and monitoring datasets\n",
    "\n",
    "The sample dataset used here is provided by the ValidMind library. For demonstration purposes we'll use the training, test and validation dataset splits as `training`, `reference` and `monitoring` datasets."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from validmind.datasets.classification import customer_churn\n",
    "\n",
    "raw_df = customer_churn.load_data()\n",
    "\n",
    "train_df, reference_df, monitor_df = customer_churn.preprocess(raw_df)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id='toc5_1_'></a>\n",
    "\n",
    "### Load the production model\n",
    "\n",
    "We will also load a pre-trained model for demonstration purposes. This is a simple XGBoost model trained on the Bank Customer Churn Prediction dataset."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import xgboost as xgb\n",
    "\n",
    "# Load the saved model\n",
    "model = xgb.XGBClassifier()\n",
    "model.load_model(\"xgboost_model.model\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id='toc5_2_'></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 raw 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",
    "- `class_labels` — An optional value to map predicted classes to class labels.\n",
    "\n",
    "With all datasets ready, you can now initialize training, reference(test) and monitor datasets (`train_df`, `reference_df` and `monitor_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",
    "    dataset=train_df,\n",
    "    input_id=\"train_df\",\n",
    "    target_column=customer_churn.target_column,\n",
    ")\n",
    "\n",
    "vm_reference_ds = vm.init_dataset(\n",
    "    dataset=reference_df,\n",
    "    input_id=\"reference_df\",\n",
    "    target_column=customer_churn.target_column,\n",
    ")\n",
    "\n",
    "vm_monitor_ds = vm.init_dataset(\n",
    "    dataset=monitor_df,\n",
    "    input_id=\"monitor_dataset\",\n",
    "    target_column=customer_churn.target_column,\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id='toc5_3_'></a>\n",
    "\n",
    "### Initialize a model object\n",
    "\n",
    "Additionally, you'll 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):\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "vm_model = vm.init_model(\n",
    "    model,\n",
    "    input_id=\"model\",\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id='toc5_4_'></a>\n",
    "\n",
    "### Assign predictions to the datasets\n",
    "\n",
    "We can now use the `assign_predictions()` method from the Dataset object to link existing predictions to any model. If no prediction values are passed, the method will compute predictions automatically:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "vm_train_ds.assign_predictions(\n",
    "    model=vm_model,\n",
    ")\n",
    "\n",
    "vm_reference_ds.assign_predictions(\n",
    "    model=vm_model,\n",
    ")\n",
    "\n",
    "vm_monitor_ds.assign_predictions(\n",
    "    model=vm_model,\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id='toc5_5_'></a>\n",
    "\n",
    "### Run the ongoing monitoring tests\n",
    "\n",
    "Before we start the testing procedure, let's take a look at the expected tests that are pre-configured:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "test_list = vm.get_test_suite().get_default_config()\n",
    "for l in test_list:\n",
    "    print(l)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let's run the first test in the list. Note that you can use `vm.tests.describe_test()` to get information about the inputs required for the test:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "vm.tests.describe_test(\"validmind.model_validation.ModelMetadata\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "As you can see, the `ModelMetadata` only requires a model input. Let's run the test and log the results into the monitoring document with the `.log()` method:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "test_result = vm.tests.run_test(\n",
    "    \"validmind.model_validation.ModelMetadata\",\n",
    "    model=vm_model,\n",
    ").log()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let's run the tests needed to determine data quality of the monitoring dataset:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "data_qual = vm.get_test_suite(\n",
    "    section=\"prediction_data_description\"\n",
    ").get_default_config()\n",
    "\n",
    "# Run all of the necessary data quality checks where the monitoring dataset is the basis\n",
    "for l in data_qual:\n",
    "    vm.tests.run_test(\n",
    "        l,\n",
    "        inputs={\"dataset\": vm_monitor_ds},\n",
    "        show=False,\n",
    "    ).log()\n",
    "    print(\"Completed test: {0}\".format(l))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "To view the results of the model metadata and data quality tests, navigate to **Ongoing Monitoring** in the left sidebar of the model in the ValidMind Platform and click on the following sections:\n",
    "\n",
    "- 1. Model Monitoring Overview > **1.2. Model Details**\n",
    "- 2. Data Quality & Drift Assessment > **2.1. Prediction Data Description**"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Next, let's run *comparison tests*, which will allow comparing differences between the training dataset and monitoring datasets. To run a test in comparison mode, you only need to pass an `input_grid` parameter to the `run_test()` method instead of `inputs`.\n",
    "\n",
    "For more information about comparison tests, see this [notebook](../../how_to/run_tests/2_run_comparison_tests.ipynb)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "correlation_tests = [\n",
    "    \"validmind.data_validation.PearsonCorrelationMatrix:train_vs_test\",\n",
    "    \"validmind.data_validation.HighPearsonCorrelation:train_vs_test\",\n",
    "]\n",
    "\n",
    "for test in correlation_tests:\n",
    "    vm.tests.run_test(\n",
    "        test,\n",
    "        input_grid={\n",
    "            \"dataset\": [vm_train_ds, vm_monitor_ds],\n",
    "            \"model\": [vm_model],\n",
    "        },\n",
    "        show=False,\n",
    "    ).log()\n",
    "    print(\"Completed test {0}\".format(test))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You can view these results in the ValidMind Platform within **Ongoing Monitoring** under the following section:\n",
    "\n",
    "- 2. Data Quality & Drift Assessment > **2.2. Prediction Data Correlations and Interactions**"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id='toc5_6_'></a>\n",
    "\n",
    "### Conduct target and feature drift testing\n",
    "\n",
    "Next, the goal is to investigate the distributional characteristics of predictions and features to determine if the underlying data has changed. These tests are crucial for assessing the expected accuracy of the model.\n",
    "\n",
    "1. **Target drift:** We compare the dataset used for testing (reference data) with the monitoring data. This helps to identify any shifts in the target variable distribution.\n",
    "2. **Feature drift:** We compare the training dataset with the monitoring data. Since features were used to train the model, any drift in these features could indicate potential issues, as the underlying patterns that the model was trained on may have changed."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In the 2. Data Quality & Drift Assessment > **2.3 Target Drift** section we can confirm only there is only one pre-configured test:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "for l in vm.get_test_suite(section=\"comparison_data_target\").get_default_config():\n",
    "    print(l)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "As part of running the rest of the tests, we will directly log the results to a section when calling the `.log()` method."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "First, let's run the *Population Stability Index (PSI)* for predictions. In this case, we want to compare the test data with the monitoring data. (Note: For predictions, the training data is irrelevant.)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "vm.tests.run_test(\n",
    "    \"validmind.model_validation.sklearn.PopulationStabilityIndex\",\n",
    "    inputs={\n",
    "        \"datasets\": [vm_reference_ds, vm_monitor_ds],\n",
    "        \"model\": vm_model,\n",
    "    },\n",
    "    show=False,\n",
    ").log()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Next, we can examine the correlation between features and predictions. Significant changes in these correlations may trigger a deeper assessment."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "vm.tests.run_test(\n",
    "    \"validmind.ongoing_monitoring.TargetPredictionDistributionPlot\",\n",
    "    inputs={\n",
    "        \"datasets\": [vm_reference_ds, vm_monitor_ds],\n",
    "        \"model\": vm_model,\n",
    "    },\n",
    "    show=False,\n",
    ").log(section_id=\"comparison_data_target\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now we want see difference in correlation pairs between model prediction and features."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "vm.tests.run_test(\n",
    "    \"validmind.ongoing_monitoring.PredictionCorrelation\",\n",
    "    inputs={\n",
    "        \"datasets\": [vm_reference_ds, vm_monitor_ds],\n",
    "        \"model\": vm_model,\n",
    "    },\n",
    "    show=False,\n",
    ").log(section_id=\"comparison_data_target\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Finally for target drift, let's plot each prediction value and feature grid side by side.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "vm.tests.run_test(\n",
    "    \"validmind.ongoing_monitoring.PredictionAcrossEachFeature\",\n",
    "    inputs={\n",
    "        \"datasets\": [vm_reference_ds, vm_monitor_ds],\n",
    "        \"model\": vm_model,\n",
    "    },\n",
    "    show=False,\n",
    ").log(section_id=\"comparison_data_target\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id='toc5_6_1_'></a>\n",
    "\n",
    "#### Feature drift tests\n",
    "\n",
    "Next, let's add run a test to investigate how or if the features have drifted. In this instance we want to compare the training data with prediction data. These results will be logged in the 2. Data Quality & Drift Assessment > **2.4. Feature Drift** section."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "vm.tests.run_test(\n",
    "    \"validmind.ongoing_monitoring.FeatureDrift\",\n",
    "    inputs={\n",
    "        \"datasets\": [vm_reference_ds, vm_monitor_ds],\n",
    "        \"model\": vm_model,\n",
    "    },\n",
    "    show=False,\n",
    ").log(section_id=\"comparison_data_feature\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id='toc5_7_'></a>\n",
    "\n",
    "### Model performance monitoring tests\n",
    "\n",
    "Let's wrap up by monitoring the model's performance. Keep in mind that in some cases, it may not be possible to determine accuracy if the ground truth is unavailable. If this is the case, you can skip this test and instead focus on target and feature drift to inform the model owners.\n",
    "\n",
    "The pre-configured tests for model performance are:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "for l in vm.get_test_suite(section=\"model_performance_monitoring\").get_default_config():\n",
    "    print(l)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The code below will run the tests and log the results into the monitoring document for each of the tests. Note the use of `input_grid` again, which is required for comparison tests:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Use the reference dataset vs monitoring dataset - the true comparison of accuracy\n",
    "for test in vm.get_test_suite(\n",
    "    section=\"model_performance_monitoring\"\n",
    ").get_default_config():\n",
    "    if test == \"validmind.model_validation.statsmodels.GINITable\":\n",
    "        vm.tests.run_test(\n",
    "            \"validmind.model_validation.statsmodels.GINITable\",\n",
    "            input_grid={\n",
    "                \"dataset\": [vm_reference_ds, vm_monitor_ds],\n",
    "                \"model\": [vm_model],\n",
    "            },\n",
    "            show=False,\n",
    "        ).log()\n",
    "    else:\n",
    "        vm.tests.run_test(\n",
    "            test,\n",
    "            input_grid={\n",
    "                \"dataset\": [vm_reference_ds, vm_monitor_ds],\n",
    "                \"model\": [vm_model],\n",
    "            },\n",
    "            show=False,\n",
    "        ).log()\n",
    "    print(\"Completed test: {0}\".format(test))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id='toc6_'></a>\n",
    "\n",
    "## Next steps\n",
    "\n",
    "You can now review all the ongoing monitoring results in the ValidMind Platform.\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",
    "2. Click on the **Ongoing Monitoring** section.\n",
    "\n",
    "What you see is the full draft of your model monitoring documentation in a more easily consumable version. From here, you can make qualitative edits to model monitoring documentation, view guidelines, collaborate with validators, and submit your model monitoring documentation for approval when it's ready.\n",
    "\n",
    "<a id='toc6_1_'></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='toc7_'></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": "Python 3",
   "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": 4
}
