{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Ongoing Monitoring for Application Scorecard \n",
    "\n",
    "In this notebook, 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."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 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": [
    "## 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": [
    "## 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 = \"https://api.prod.validmind.ai/api/v1/tracking\",\n",
    "  api_key = \"...\",\n",
    "  api_secret = \"...\",\n",
    "  model = \"...\",\n",
    "  monitoring = True\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 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",
    "import numpy as np\n",
    "\n",
    "from datetime import datetime, timedelta\n",
    "\n",
    "from validmind.tests import run_test\n",
    "from validmind.datasets.credit_risk import lending_club\n",
    "from validmind.unit_metrics import list_metrics\n",
    "from validmind.unit_metrics import describe_metric\n",
    "from validmind.unit_metrics import run_metric\n",
    "from validmind.api_client import log_metric\n",
    "\n",
    "%matplotlib inline"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 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:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "vm.preview_template()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 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 dataset splits as `reference` and `monitoring` datasets."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df = lending_club.load_data(source=\"offline\")\n",
    "df.head()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "preprocess_df = lending_club.preprocess(df)\n",
    "preprocess_df.head()"
   ]
  },
  {
   "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": [
    "## 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": 9,
   "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",
    ")\n",
    "\n",
    "# Compute probabilities\n",
    "train_xgb_prob = xgb_model.predict_proba(x_train)[:, 1]\n",
    "test_xgb_prob = xgb_model.predict_proba(x_test)[:, 1]\n",
    "\n",
    "# Compute binary predictions\n",
    "cut_off_threshold = 0.3\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)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 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",
    "\n",
    "With all datasets ready, you can now initialize training, reference(test) and monitor datasets (`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):"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "vm_reference_ds = vm.init_dataset(\n",
    "    dataset=train_df,\n",
    "    input_id=\"reference_dataset\",\n",
    "    target_column=lending_club.target_column,\n",
    ")\n",
    "\n",
    "vm_monitoring_ds = vm.init_dataset(\n",
    "    dataset=test_df,\n",
    "    input_id=\"monitoring_dataset\",\n",
    "    target_column=lending_club.target_column,\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 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": 11,
   "metadata": {},
   "outputs": [],
   "source": [
    "vm_xgb_model = vm.init_model(\n",
    "    xgb_model,\n",
    "    input_id=\"xgb_model\",\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 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": 12,
   "metadata": {},
   "outputs": [],
   "source": [
    "vm_reference_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_monitoring_ds.assign_predictions(\n",
    "    model=vm_xgb_model,\n",
    "    prediction_values=test_xgb_binary_predictions,\n",
    "    prediction_probabilities=test_xgb_prob,\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": 13,
   "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_reference_ds.add_extra_column(\"xgb_scores\", train_xgb_scores)\n",
    "vm_monitoring_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": 14,
   "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": [
    "### Monitoring data description\n",
    "\n",
    "The Monitoring Data Description tests aim to provide a comprehensive statistical analysis of the monitoring dataset's characteristics. These tests examine the basic statistical properties, identify any missing data patterns, assess data uniqueness, visualize numerical feature distributions, and evaluate feature relationships through correlation analysis.\n",
    "\n",
    "The primary objective is to establish a baseline understanding of the monitoring data's structure and quality, enabling the detection of any significant deviations from expected patterns that could impact model performance. Each test is designed to capture different aspects of the data, from univariate statistics to multivariate relationships, providing a foundation for ongoing data quality assessment in the production environment."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "run_test(\n",
    "    \"validmind.data_validation.DescriptiveStatistics:monitoring_data\",\n",
    "    inputs={\n",
    "        \"dataset\": vm_monitoring_ds,\n",
    "    }\n",
    ").log()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "run_test(\n",
    "    \"validmind.data_validation.MissingValues:monitoring_data\",\n",
    "    inputs={\n",
    "        \"dataset\": vm_monitoring_ds,\n",
    "    },\n",
    "    params={\n",
    "        \"min_threshold\": 1\n",
    "    }\n",
    ").log()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "run_test(\n",
    "    \"validmind.data_validation.UniqueRows:monitoring_data\",\n",
    "    inputs={\n",
    "        \"dataset\": vm_monitoring_ds,\n",
    "    },\n",
    "    params={\n",
    "        \"min_percent_threshold\": 1\n",
    "    }\n",
    ").log()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "run_test(\n",
    "    \"validmind.data_validation.TabularNumericalHistograms:monitoring_data\",\n",
    "    inputs={\n",
    "        \"dataset\": vm_monitoring_ds,\n",
    "    },\n",
    ").log()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "run_test(\n",
    "    \"validmind.data_validation.PearsonCorrelationMatrix:monitoring_data\",\n",
    "    inputs={\n",
    "        \"dataset\": vm_monitoring_ds,\n",
    "    }\n",
    ").log()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "run_test(\n",
    "    \"validmind.data_validation.HighPearsonCorrelation:monitoring_data\",\n",
    "    inputs={\n",
    "        \"dataset\": vm_monitoring_ds,\n",
    "    },\n",
    "    params={\n",
    "        \"feature_columns\": vm_monitoring_ds.feature_columns,\n",
    "        \"max_threshold\": 0.5,\n",
    "        \"top_n_correlations\": 10\n",
    "    }\n",
    ").log()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "run_test(\n",
    "    \"validmind.ongoing_monitoring.ClassImbalanceDrift\",\n",
    "    inputs={\n",
    "        \"datasets\": [vm_reference_ds, vm_monitoring_ds],\n",
    "    },\n",
    "    params={\n",
    "        \"drift_pct_threshold\": 1\n",
    "    },\n",
    ").log()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Target and feature drift\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": [
    "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": [
    "run_test(\n",
    "    \"validmind.model_validation.sklearn.PopulationStabilityIndex\",\n",
    "    inputs={\n",
    "        \"datasets\": [vm_reference_ds, vm_monitoring_ds],\n",
    "        \"model\": vm_xgb_model,\n",
    "    },\n",
    ").log()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "run_test(\n",
    "    \"validmind.ongoing_monitoring.TargetPredictionDistributionPlot\",\n",
    "    inputs={\n",
    "        \"datasets\": [vm_reference_ds, vm_monitoring_ds],\n",
    "        \"model\": vm_xgb_model,\n",
    "    },\n",
    "    params={\n",
    "        \"drift_pct_threshold\": 5\n",
    "    },\n",
    ").log()"
   ]
  },
  {
   "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": [
    "run_test(\n",
    "    \"validmind.ongoing_monitoring.PredictionCorrelation\",\n",
    "    inputs={\n",
    "        \"datasets\": [vm_reference_ds, vm_monitoring_ds],\n",
    "        \"model\": vm_xgb_model,\n",
    "    },\n",
    "    params={\n",
    "        \"drift_pct_threshold\": 5\n",
    "    },\n",
    ").log()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Finally for target drift, let's plot each prediction value and feature grid side by side."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "run_test(\n",
    "    \"validmind.ongoing_monitoring.PredictionQuantilesAcrossFeatures\",\n",
    "    inputs={\n",
    "        \"datasets\": [vm_reference_ds, vm_monitoring_ds],\n",
    "        \"model\": vm_xgb_model,\n",
    "    },\n",
    ").log()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "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."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "run_test(\n",
    "    \"validmind.ongoing_monitoring.FeatureDrift\",\n",
    "    inputs={\n",
    "        \"datasets\": [vm_reference_ds, vm_monitoring_ds],\n",
    "        \"model\": vm_xgb_model,\n",
    "    },\n",
    "    params={\n",
    "        \"psi_threshold\": 0.2,\n",
    "    },\n",
    ").log()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Classification accuracy\n",
    "\n",
    "We now evaluate the model's predictive performance by comparing its behavior between reference and monitoring datasets. These tests analyze shifts in overall accuracy metrics, examine changes in the confusion matrix to identify specific classification pattern changes, and assess the model's probability calibration across different prediction thresholds. \n",
    "\n",
    "The primary objective is to detect any degradation in the model's classification performance that might indicate reliability issues in production. The tests provide both aggregate performance metrics and detailed breakdowns of prediction patterns, enabling the identification of specific areas where the model's accuracy might be deteriorating."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "run_test(\n",
    "    \"validmind.ongoing_monitoring.ClassificationAccuracyDrift\",\n",
    "    inputs={\n",
    "        \"datasets\": [vm_reference_ds, vm_monitoring_ds],\n",
    "        \"model\": vm_xgb_model,\n",
    "    },\n",
    "    params={\n",
    "        \"drift_pct_threshold\": 5,\n",
    "    },\n",
    ").log()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "run_test(\n",
    "    \"validmind.ongoing_monitoring.ConfusionMatrixDrift\",\n",
    "    inputs={\n",
    "        \"datasets\": [vm_reference_ds, vm_monitoring_ds],\n",
    "        \"model\": vm_xgb_model,\n",
    "    },\n",
    "    params={\n",
    "        \"drift_pct_threshold\": 5,\n",
    "    },\n",
    ").log()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "run_test(\n",
    "    \"validmind.ongoing_monitoring.CalibrationCurveDrift\",\n",
    "    inputs={\n",
    "        \"datasets\": [vm_reference_ds, vm_monitoring_ds],\n",
    "        \"model\": vm_xgb_model,\n",
    "    },\n",
    "    params={\n",
    "        \"n_bins\": 10,\n",
    "        \"drift_pct_threshold\": 10,\n",
    "    },\n",
    ").log()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Class discrimination\n",
    "\n",
    "The following tests assess the model's ability to effectively separate different classes in both reference and monitoring datasets. These tests analyze the model's discriminative power by examining the separation between class distributions, evaluating changes in the ROC curve characteristics, comparing probability distribution patterns, and assessing cumulative prediction trends. \n",
    "\n",
    "The primary objective is to identify any deterioration in the model's ability to distinguish between classes, which could indicate a decline in model effectiveness. The tests examine both the overall discriminative capability and the granular patterns in prediction distributions, providing insights into whether the model maintains its ability to effectively differentiate between classes in the production environment."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "run_test(\n",
    "    \"validmind.ongoing_monitoring.ClassDiscriminationDrift\",\n",
    "    inputs={\n",
    "        \"datasets\": [vm_reference_ds, vm_monitoring_ds],\n",
    "        \"model\": vm_xgb_model,\n",
    "    },\n",
    "    params={\n",
    "        \"drift_pct_threshold\": 5,\n",
    "    },\n",
    ").log()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "run_test(\n",
    "    \"validmind.ongoing_monitoring.ROCCurveDrift\",\n",
    "    inputs={\n",
    "        \"datasets\": [vm_reference_ds, vm_monitoring_ds],\n",
    "        \"model\": vm_xgb_model,\n",
    "    }\n",
    ").log()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "run_test(\n",
    "    \"validmind.ongoing_monitoring.PredictionProbabilitiesHistogramDrift\",\n",
    "    inputs={\n",
    "        \"datasets\": [vm_reference_ds, vm_monitoring_ds],\n",
    "        \"model\": vm_xgb_model,\n",
    "    },\n",
    "    params={\n",
    "        \"drift_pct_threshold\": 10,\n",
    "    },\n",
    ").log()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "run_test(\n",
    "    \"validmind.ongoing_monitoring.CumulativePredictionProbabilitiesDrift\",\n",
    "    inputs={\n",
    "        \"datasets\": [vm_reference_ds, vm_monitoring_ds],\n",
    "        \"model\": vm_xgb_model,\n",
    "    }\n",
    ").log()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Scoring\n",
    "\n",
    "Next we analyze the distribution and stability of credit scores across reference and monitoring datasets. These tests evaluate shifts in score distributions, examine changes in score band populations, and assess the relationship between scores and default rates. \n",
    "\n",
    "The primary objective is to identify any significant changes in how the model assigns credit scores, which could indicate drift in risk assessment capabilities. The tests examine both the overall score distribution patterns and the specific performance within defined score bands, providing insights into whether the model maintains consistent and reliable risk segmentation."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "run_test(\n",
    "    \"validmind.ongoing_monitoring.ScorecardHistogramDrift\",\n",
    "    inputs={\n",
    "        \"datasets\": [vm_reference_ds, vm_monitoring_ds],\n",
    "    },\n",
    "    params={\n",
    "        \"score_column\": \"xgb_scores\",\n",
    "        \"drift_pct_threshold\": 20,\n",
    "    },\n",
    ").log()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "run_test(\n",
    "    \"validmind.ongoing_monitoring.ScoreBandsDrift\",\n",
    "    inputs={\n",
    "        \"datasets\": [vm_reference_ds, vm_monitoring_ds],\n",
    "        \"model\": vm_xgb_model,\n",
    "    },\n",
    "    params={\n",
    "        \"score_column\": \"xgb_scores\",\n",
    "        \"score_bands\": [500, 540, 570],\n",
    "        \"drift_pct_threshold\": 20,\n",
    "    },\n",
    ").log()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Model insights"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "run_test(\n",
    "    \"validmind.model_validation.sklearn.PermutationFeatureImportance\",\n",
    "    input_grid={\n",
    "        \"dataset\": [vm_reference_ds, vm_monitoring_ds],\n",
    "        \"model\": [vm_xgb_model]\n",
    "    }\n",
    ").log()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "run_test(\n",
    "    \"validmind.model_validation.FeaturesAUC\",\n",
    "    input_grid={\n",
    "        \"model\": [vm_xgb_model],\n",
    "        \"dataset\": [vm_reference_ds, vm_monitoring_ds],\n",
    "    },\n",
    ").log()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "run_test(\n",
    "    \"validmind.model_validation.sklearn.SHAPGlobalImportance\",\n",
    "    input_grid={\n",
    "        \"model\": [vm_xgb_model],\n",
    "        \"dataset\": [vm_reference_ds, vm_monitoring_ds],\n",
    "    },\n",
    "    params={\n",
    "        \"kernel_explainer_samples\": 10,\n",
    "        \"tree_or_linear_explainer_samples\": 200,\n",
    "    }\n",
    ").log()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Diagnostic monitoring"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "run_test(\n",
    "    \"validmind.model_validation.sklearn.WeakspotsDiagnosis\",\n",
    "    inputs={\n",
    "        \"datasets\": [vm_reference_ds, vm_monitoring_ds],\n",
    "        \"model\": vm_xgb_model,\n",
    "    },\n",
    ").log()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "run_test(\n",
    "    \"validmind.model_validation.sklearn.OverfitDiagnosis\",\n",
    "    inputs={\n",
    "        \"model\": vm_xgb_model,\n",
    "        \"datasets\": [vm_reference_ds, vm_monitoring_ds],\n",
    "    },\n",
    "    params={\n",
    "        \"cut_off_threshold\": 0.04\n",
    "    }\n",
    ").log()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Robustness monitoring"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "run_test(\n",
    "    \"validmind.model_validation.sklearn.RobustnessDiagnosis\",\n",
    "    inputs={\n",
    "        \"datasets\": [vm_reference_ds, vm_monitoring_ds],\n",
    "        \"model\": vm_xgb_model,\n",
    "    },\n",
    "    params={\n",
    "        \"scaling_factor_std_dev_list\": [\n",
    "            0.1,\n",
    "            0.2,\n",
    "            0.3,\n",
    "            0.4,\n",
    "            0.5\n",
    "        ],\n",
    "        \"performance_decay_threshold\": 0.05\n",
    "    }\n",
    ").log()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Performance history\n",
    "\n",
    "In this section we showcase how to track and visualize the temporal evolution of key model performance metrics, including AUC, F1 score, precision, recall, and accuracy. For demonstration purposes, the section simulates historical performance data by introducing a gradual downward trend and random noise to these metrics over a specified time period. These tests are useful for analyzing the stability and trends in model performance indicators, helping to identify potential degradation or unexpected fluctuations in model behavior over time. \n",
    "\n",
    "The main goal is to maintain a continuous record of model performance that can be used to detect gradual drift, sudden changes, or cyclical patterns in model effectiveness. This temporal monitoring approach provides early warning signals of potential issues and helps establish whether the model maintains consistent performance within acceptable boundaries throughout its deployment period."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "metrics = [metric for metric in list_metrics() if \"classification\" in metric]\n",
    "\n",
    "for metric_id in metrics:\n",
    "    describe_metric(metric_id)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "result = run_metric(\n",
    "    \"validmind.unit_metrics.classification.ROC_AUC\",\n",
    "    inputs={\n",
    "        \"model\": vm_xgb_model,\n",
    "        \"dataset\": vm_monitoring_ds,\n",
    "    },\n",
    ")\n",
    "auc = result.metric"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "result = run_metric(\n",
    "    \"validmind.unit_metrics.classification.Accuracy\",\n",
    "    inputs={\n",
    "        \"model\": vm_xgb_model,\n",
    "        \"dataset\": vm_monitoring_ds,\n",
    "    },\n",
    ")\n",
    "accuracy = result.metric"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "result = run_metric(\n",
    "    \"validmind.unit_metrics.classification.Recall\",\n",
    "    inputs={\n",
    "        \"model\": vm_xgb_model,\n",
    "        \"dataset\": vm_monitoring_ds,\n",
    "    },\n",
    ")\n",
    "recall = result.metric"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "f1 = run_metric(\n",
    "    \"validmind.unit_metrics.classification.F1\",\n",
    "    inputs={\n",
    "        \"model\": vm_xgb_model,\n",
    "        \"dataset\": vm_monitoring_ds,\n",
    "    },\n",
    ")\n",
    "f1 = result.metric"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "precision = run_metric(\n",
    "    \"validmind.unit_metrics.classification.Precision\",\n",
    "    inputs={\n",
    "        \"model\": vm_xgb_model,\n",
    "        \"dataset\": vm_monitoring_ds,\n",
    "    },\n",
    ")\n",
    "precision = result.metric"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "NUM_DAYS = 10\n",
    "REFERENCE_DATE = datetime(2024, 1, 1)  # Fixed date: January 1st, 2024\n",
    "base_date = REFERENCE_DATE - timedelta(days=NUM_DAYS)\n",
    "\n",
    "\n",
    "# Initial values\n",
    "performance_metrics = {\n",
    "    \"AUC Score\": auc,\n",
    "    \"F1 Score\": f1,\n",
    "    \"Precision Score\": precision,\n",
    "    \"Recall Score\": recall,\n",
    "    \"Accuracy Score\": accuracy\n",
    "}\n",
    "\n",
    "# Trend parameters\n",
    "trend_factor = 0.98  # Slight downward trend (multiply by 0.98 each step)\n",
    "noise_scale = 0.02   # Random fluctuation of ±2%\n",
    "\n",
    "\n",
    "for i in range(NUM_DAYS):\n",
    "    recorded_at = base_date + timedelta(days=i)\n",
    "    print(f\"\\nrecorded_at: {recorded_at}\")\n",
    "\n",
    "    # Log each metric with trend and noise\n",
    "    for metric_name, base_value in performance_metrics.items():\n",
    "        # Apply trend and add random noise\n",
    "        trend = base_value * (trend_factor ** i)\n",
    "        noise = np.random.normal(0, noise_scale * base_value)\n",
    "        value = max(0, min(1, trend + noise))  # Ensure value stays between 0 and 1\n",
    "        \n",
    "        log_metric(\n",
    "            key=metric_name,\n",
    "            value=value,\n",
    "            recorded_at=recorded_at.isoformat()\n",
    "        )\n",
    "        \n",
    "        print(f\"{metric_name:<15}: {value:.4f}\")\n"
   ]
  }
 ],
 "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
}
