{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Log metrics over time\n",
    "\n",
    "Learn how to track and visualize the temporal evolution of key model performance metrics with ValidMind.\n",
    "\n",
    "- Key model performance metrics such as AUC, F1 score, precision, recall, and accuracy, 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",
    "- By monitoring these metrics systematically, teams can detect early warning signs of model drift and take proactive measures to maintain model reliability.\n",
    "- Unit metrics in ValidMind provide a standardized way to compute and track individual performance measures, making it easy to monitor specific aspects of model behavior.\n",
    "\n",
    "Log metrics over time with the ValidMind Library's [`log_metric()`](https://docs.validmind.ai/validmind/validmind.html#log_metric) function and visualize them in your documentation using the *Metric Over Time* block within the ValidMind Platform. This integration enables seamless tracking of model performance, supporting custom thresholds and facilitating the automation of alerts based on logged metrics.\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>Metrics over time are most commonly associated with the continued monitoring of a model's performance once it is deployed.</b></span>\n",
    "<br></br>\n",
    "While you are able to add Metric Over Time blocks to model documentation, we recommend first <a href=\"https://docs.validmind.ai/guide/monitoring/enable-monitoring.html\" style=\"color: #DE257E;\"><b>enabling ongoing monitoring</b></a> for your model to maximize the potential of your performance data.</div>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "::: {.content-hidden when-format=\"html\"}\n",
    "## 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",
    "- [Load demo model](#toc5_)    \n",
    "- [Log metrics](#toc6_)    \n",
    "  - [Run unit metrics](#toc6_1_)    \n",
    "  - [Log unit metrics over time](#toc6_2_)    \n",
    "  - [Pass thresholds](#toc6_3_)    \n",
    "  - [Log multiple metrics with custom thresholds](#toc6_4_)    \n",
    "  - [Add acceptable performance flag](#toc6_5_)\n",
    "- [Next steps](#toc7_)\n",
    "- [Upgrade ValidMind](#toc8_)\n",
    ":::\n",
    "<!-- jn-toc-notebook-config\n",
    "\tnumbering=false\n",
    "\tanchor=true\n",
    "\tflat=false\n",
    "\tminLevel=2\n",
    "\tmaxLevel=4\n",
    "\t/jn-toc-notebook-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",
    "<a id='toc1_'></a>\n",
    "\n",
    "## About ValidMind\n",
    "ValidMind is a suite of tools for managing model risk, including risk associated with AI and statistical models.\n",
    "\n",
    "You use the ValidMind Library to automate documentation and validation tests, and then use the ValidMind Platform to collaborate on model documentation. Together, these products simplify model risk management, facilitate compliance with regulations and institutional standards, and enhance collaboration between yourself and model validators.\n",
    "\n",
    "<a id='toc1_1_'></a>\n",
    "\n",
    "<a id='toc1_1_'></a>\n",
    "\n",
    "### Before you begin\n",
    "This notebook assumes you have basic familiarity with Python, including an understanding of how functions work. If you are new to Python, you can still run the notebook but we recommend further familiarizing yourself with the language.\n",
    "\n",
    "If you encounter errors due to missing modules in your Python environment, install the modules with `pip install`, and then re-run the notebook. For more help, refer to [Installing Python Modules](https://docs.python.org/3/installing/index.html).\n",
    "\n",
    "<a id='toc1_2_'></a>\n",
    "\n",
    "<a id='toc1_2_'></a>\n",
    "\n",
    "### New to ValidMind?\n",
    "If you haven't already seen our documentation on the [ValidMind Library](https://docs.validmind.ai/developer/validmind-library.html), we recommend you begin by exploring the available resources in this section. There, you can learn more about documenting models and running tests, as well as find code samples and our Python Library API reference.\n",
    "\n",
    "<div class=\"alert alert-block alert-info\" style=\"background-color: #B5B5B510; color: black; border: 1px solid #083E44; border-left-width: 5px; box-shadow: 2px 2px 4px rgba(0, 0, 0, 0.2);border-radius: 5px;\"><span style=\"color: #083E44;\"><b>For access to all features available in this notebook, create a free ValidMind account.</b></span>\n",
    "<br></br>\n",
    "Signing up is FREE — <a href=\"https://docs.validmind.ai/guide/configuration/register-with-validmind.html\" style=\"color: #DE257E;\"><b>Register with ValidMind</b></a></div>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id='toc1_3_'></a>\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."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id='toc2_'></a>\n",
    "\n",
    "<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",
    "<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",
    "<a id='toc3_1_'></a>\n",
    "\n",
    "### Get your code snippet\n",
    "\n",
    "1. In a browser, [log in to ValidMind](https://docs.validmind.ai/guide/configuration/log-in-to-validmind.html).\n",
    "\n",
    "2. In the left sidebar, navigate to **Model Inventory** and click **+ Register Model**.\n",
    "\n",
    "3. Enter the model details and click **Continue**. ([Need more help?](https://docs.validmind.ai/guide/model-inventory/register-models-in-inventory.html))\n",
    "\n",
    "   For example, to register a model for use with this notebook, select:\n",
    "\n",
    "   - Documentation template: `Credit Risk Scorecard`\n",
    "   - Use case: `Credit Risk - CECL`\n",
    "\n",
    "   You can fill in other options according to your preference.\n",
    "\n",
    "4. Go to **Getting Started** and click **Copy snippet to clipboard**.\n",
    "\n",
    "Next, [load your model identifier credentials from an `.env` file](https://docs.validmind.ai/developer/model-documentation/store-credentials-in-env-file.html) or replace the placeholder with your own code snippet:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Load your model identifier credentials from an `.env` file\n",
    "\n",
    "%load_ext dotenv\n",
    "%dotenv .env\n",
    "\n",
    "# Or replace with your code snippet\n",
    "\n",
    "import validmind as vm\n",
    "\n",
    "vm.init(\n",
    "    # api_host=\"...\",\n",
    "    # api_key=\"...\",\n",
    "    # api_secret=\"...\",\n",
    "    # model=\"...\",\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id='toc4_'></a>\n",
    "\n",
    "<a id='toc4_'></a>\n",
    "\n",
    "## Initialize the Python environment\n",
    "\n",
    "Next, let's import the necessary libraries and set up your Python environment for data analysis:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "import xgboost as xgb\n",
    "import numpy as np\n",
    "\n",
    "from datetime import datetime, timedelta\n",
    "\n",
    "from validmind.unit_metrics import list_metrics, describe_metric, run_metric\n",
    "from validmind.api_client import log_metric\n",
    "\n",
    "%matplotlib inline"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id='toc5_'></a>\n",
    "\n",
    "## Load demo model\n",
    "\n",
    "We'll use a classification model trained on customer churn data to demonstrate ValidMind's metric logging capabilities.\n",
    "\n",
    "- We'll employ a built-in classification dataset, process it through train-validation-test splits, and train an XGBoost classifier.\n",
    "- The trained model and datasets are then initialized in ValidMind's framework, enabling us to track and monitor various performance metrics in the following sections."
   ]
  },
  {
   "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\n",
    "\n",
    "print(\n",
    "    f\"Loaded demo dataset with: \\n\\n\\t• Target column: '{customer_churn.target_column}' \\n\\t• Class labels: {customer_churn.class_labels}\"\n",
    ")\n",
    "\n",
    "raw_df = customer_churn.load_data()\n",
    "raw_df.head()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "train_df, validation_df, test_df = customer_churn.preprocess(raw_df)\n",
    "\n",
    "x_train = train_df.drop(customer_churn.target_column, axis=1)\n",
    "y_train = train_df[customer_churn.target_column]\n",
    "x_val = validation_df.drop(customer_churn.target_column, axis=1)\n",
    "y_val = validation_df[customer_churn.target_column]\n",
    "\n",
    "model = xgb.XGBClassifier(early_stopping_rounds=10)\n",
    "model.set_params(\n",
    "    eval_metric=[\"error\", \"logloss\", \"auc\"],\n",
    ")\n",
    "model.fit(\n",
    "    x_train,\n",
    "    y_train,\n",
    "    eval_set=[(x_val, y_val)],\n",
    "    verbose=False,\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Once the datasets and model are prepared for validation, let's initialize the ValidMind `dataset` and `model`, specifying features and targets columns.\n",
    "\n",
    "- The property `input_id` allows users to uniquely identify each dataset and model.\n",
    "- This allows for the creation of multiple versions of datasets and models, enabling us to compute metrics by specifying which versions we want to use as inputs."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "vm_raw_dataset = vm.init_dataset(\n",
    "    dataset=raw_df,\n",
    "    input_id=\"raw_dataset\",\n",
    "    target_column=customer_churn.target_column,\n",
    "    class_labels=customer_churn.class_labels,\n",
    ")\n",
    "\n",
    "vm_train_ds = vm.init_dataset(\n",
    "    dataset=train_df,\n",
    "    input_id=\"train_dataset\",\n",
    "    target_column=customer_churn.target_column,\n",
    ")\n",
    "\n",
    "vm_test_ds = vm.init_dataset(\n",
    "    dataset=test_df, input_id=\"test_dataset\", target_column=customer_churn.target_column\n",
    ")\n",
    "\n",
    "vm_model = vm.init_model(\n",
    "    model,\n",
    "    input_id=\"model\",\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We can now use the `assign_predictions()` method from the Dataset object to link existing predictions to any model. \n",
    "\n",
    "If no prediction values are passed, the method will compute predictions automatically:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "vm_train_ds.assign_predictions(\n",
    "    model=vm_model,\n",
    ")\n",
    "\n",
    "vm_test_ds.assign_predictions(\n",
    "    model=vm_model,\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id='toc6_'></a>\n",
    "\n",
    "## Log metrics\n",
    "\n",
    "Next, we'll use ValidMind to track the temporal evolution of key model performance metrics.\n",
    "\n",
    "We'll set appropriate thresholds for each metric, enable automated alerting when performance drifts beyond acceptable boundaries, and demonstrate how these thresholds can be customized based on business requirements and risk tolerance levels."
   ]
  },
  {
   "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": "markdown",
   "metadata": {},
   "source": [
    "<a id='toc6_1_'></a>\n",
    "\n",
    "### Run unit metrics\n",
    "\n",
    "Compute individual metrics using ValidMind's *unit metrics* — single-value metrics that can be computed on a dataset and model. Use the `run_metric()` function from the `validmind.unit_metrics` module to calculate these metrics.\n",
    "\n",
    "The `run_metric()` function has a signature similar to `run_test()` from the `validmind.tests` module, but is specifically designed for unit metrics and takes the following arguments:\n",
    "\n",
    "- **`metric_id`:** The unique identifier for the metric (for example, `validmind.unit_metrics.classification.ROC_AUC`)\n",
    "- **`inputs`:** A dictionary containing the input dataset and model or their respective input IDs\n",
    "- **`params`:** A dictionary containing keyword arguments for the unit metric (optional, accepts any `kwargs` from the underlying sklearn implementation)\n",
    "\n",
    "`run_metric()` returns and displays a result object similar to a regular ValidMind test, but only shows the unit metric value. While this result object has a `.log()` method for logging to the ValidMind Platform, in this use case we'll use unit metrics to compute performance metrics and then log them over time using the `log_metric()` function from the `validmind.api_client` module."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "result = run_metric(\n",
    "    \"validmind.unit_metrics.classification.ROC_AUC\",\n",
    "    inputs={\n",
    "        \"model\": vm_model,\n",
    "        \"dataset\": vm_test_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_model,\n",
    "        \"dataset\": vm_test_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_model,\n",
    "        \"dataset\": vm_test_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_model,\n",
    "        \"dataset\": vm_test_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_model,\n",
    "        \"dataset\": vm_test_ds,\n",
    "    },\n",
    ")\n",
    "precision = result.metric"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id='toc6_2_'></a>\n",
    "\n",
    "### Log unit metrics over time\n",
    "\n",
    "Using the `log_metric()` function from the `validmind.api_client` module, let's log the unit metrics over time. This function takes the following arguments:\n",
    "\n",
    "- **`key`:** The name of the metric to log\n",
    "- **`value`:** The value of the metric to log\n",
    "- **`recorded_at`:** The timestamp of the metric to log — useful for logging historic predictions\n",
    "- **`thresholds`:** A dictionary containing the thresholds for the metric to log\n",
    "- **`params`:** A dictionary containing the keyword arguments for the unit metric (in this case, none are required, but we can pass any `kwargs` that the underlying sklearn implementation accepts)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "log_metric(\n",
    "    key=\"AUC Score\",\n",
    "    value=auc,\n",
    "    # If `recorded_at` is not included, the time at function run is logged\n",
    "    recorded_at=datetime(2024, 1, 1), \n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "To visualize the logged metric, we'll use the **[Metrics Over Time block](https://docs.validmind.ai/guide/monitoring/work-with-metrics-over-time.html)** in the ValidMind Platform:\n",
    "\n",
    "- After adding this visualization block to your documentation or ongoing monitoring report (as shown in the image below), you'll be able to review your logged metrics plotted over time.\n",
    "- In this example, since we've only logged a single data point, the visualization shows just one measurement.\n",
    "- As you continue logging metrics, the graph will populate with more points, enabling you to track trends and patterns.\n",
    "\n",
    "![Metric Over Time block](../images/add_metric_over_time_block.png)\n",
    "![AUC Score](../images/log_metric_auc_1.png)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id='toc6_3_'></a>\n",
    "\n",
    "### Pass thresholds\n",
    "\n",
    "We can pass *thresholds* to the `log_metric()` function to enhance the metric over time: \n",
    "\n",
    "- This is useful for visualizing the metric over time and identifying potential issues. \n",
    "- The metric visualization component provides a dynamic way to monitor and contextualize metric values through customizable thresholds. \n",
    "- These thresholds appear as horizontal reference lines on the chart. \n",
    "- The system always displays the most recent threshold configuration, meaning that if you update threshold values in your client application, the visualization will reflect these changes immediately. \n",
    "\n",
    "When a metric is logged without thresholds or with an empty threshold dictionary, the reference lines gracefully disappear from the chart, though the metric line itself remains visible. \n",
    "\n",
    "Thresholds are highly flexible in their implementation. You can define them with any meaningful key names (such as `low_risk`, `maximum`, `target`, or `acceptable_range`) in your metric data, and the visualization will adapt accordingly. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "log_metric(\n",
    "    key=\"AUC Score\",\n",
    "    value=auc,\n",
    "    recorded_at=datetime(2024, 1, 1),\n",
    "    thresholds={\n",
    "        \"min_auc\": 0.7,\n",
    "    }\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![AUC Score](../images/log_metric_auc_2.png)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "log_metric(\n",
    "    key=\"AUC Score\",\n",
    "    value=auc,\n",
    "    recorded_at=datetime(2024, 1, 1),\n",
    "    thresholds={\n",
    "        \"high_risk\": 0.6,\n",
    "        \"medium_risk\": 0.7,\n",
    "        \"low_risk\": 0.8,\n",
    "    }\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![AUC Score](../images/log_metric_auc_3.png)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id='toc6_4_'></a>\n",
    "\n",
    "### Log multiple metrics with custom thresholds\n",
    "\n",
    "The following code snippet shows an example of how to set up and log multiple performance metrics with custom thresholds for each metric:\n",
    "\n",
    "- Using AUC, F1, Precision, Recall, and Accuracy scores as examples, it demonstrates how to define different risk levels (high, medium, low) appropriate for each metric's expected range.\n",
    "- The code simulates 10 days of metric history by applying a gradual decay and random noise to help visualize how metrics might drift over time in a production environment."
   ]
  },
  {
   "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",
    "# Initial values with their specific thresholds\n",
    "performance_metrics = {\n",
    "    \"AUC Score\": {\n",
    "        \"value\": auc,\n",
    "        \"thresholds\": {\n",
    "            \"high_risk\": 0.7,\n",
    "            \"medium_risk\": 0.8,\n",
    "            \"low_risk\": 0.9,\n",
    "        }\n",
    "    },\n",
    "    \"F1 Score\": {\n",
    "        \"value\": f1,\n",
    "        \"thresholds\": {\n",
    "            \"high_risk\": 0.5,\n",
    "            \"medium_risk\": 0.6,\n",
    "            \"low_risk\": 0.7,\n",
    "        }\n",
    "    },\n",
    "    \"Precision Score\": {\n",
    "        \"value\": precision,\n",
    "        \"thresholds\": {\n",
    "            \"high_risk\": 0.6,\n",
    "            \"medium_risk\": 0.7,\n",
    "            \"low_risk\": 0.8,\n",
    "        }\n",
    "    },\n",
    "    \"Recall Score\": {\n",
    "        \"value\": recall,\n",
    "        \"thresholds\": {\n",
    "            \"high_risk\": 0.4,\n",
    "            \"medium_risk\": 0.5,\n",
    "            \"low_risk\": 0.6,\n",
    "        }\n",
    "    },\n",
    "    \"Accuracy Score\": {\n",
    "        \"value\": accuracy,\n",
    "        \"thresholds\": {\n",
    "            \"high_risk\": 0.75,\n",
    "            \"medium_risk\": 0.8,\n",
    "            \"low_risk\": 0.85,\n",
    "        }\n",
    "    }\n",
    "}\n",
    "\n",
    "# Trend parameters\n",
    "trend_factor = 0.98  # Slight downward trend\n",
    "noise_scale = 0.02   # Random fluctuation of ±2%\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, metric_info in performance_metrics.items():\n",
    "        base_value = metric_info[\"value\"]\n",
    "        thresholds = metric_info[\"thresholds\"]\n",
    "        \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",
    "            thresholds=thresholds\n",
    "        )\n",
    "        \n",
    "        print(f\"{metric_name:<15}: {value:.4f} (Thresholds: {thresholds})\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![AUC Score](../images/log_metric_auc_4.png)\n",
    "![Accuracy Score](../images/log_metric_accuracy.png)\n",
    "![Precision Score](../images/log_metric_precision.png)\n",
    "![Recall Score](../images/log_metric_recall.png)\n",
    "![F1 Score](../images/log_metric_f1.png)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id='toc6_5_'></a>\n",
    "\n",
    "### Add acceptable performance flag\n",
    "\n",
    "The `passed` parameter in the `log_metric()` function allows you to explicitly mark whether a specific metric value should be considered \"Satisfactory\" or \"Requires Attention\":\n",
    "   - When `passed=True`: A green \"Satisfactory\" badge appears on the chart, indicating the metric value meets your acceptance criteria.\n",
    "   - When `passed=False`: A yellow \"Requires Attention\" badge appears, highlighting potential concerns that may require investigation."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In the example below, the `passed=True` parameter adds a green \"Satisfactory\" badge to the GINI Score metric visualization, instantly indicating that the 0.75 value meets acceptable performance standards by being above the `medium_risk` threshold of 0.6:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "log_metric(\n",
    "    key=\"GINI Score\",\n",
    "    value=0.75,\n",
    "    recorded_at=datetime(2025, 6, 7),\n",
    "    thresholds = {\n",
    "        \"high_risk\": 0.5,\n",
    "        \"medium_risk\": 0.6,\n",
    "        \"low_risk\": 0.8,\n",
    "    },\n",
    "    passed=True\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![GINI Score](../images/log_metric_satisfactory.png)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In this example, the `passed=False` parameter adds a yellow \"Requires Attention\" badge to the GINI Score metric visualization, immediately highlighting that the value of 0.5 fails to meet acceptable performance standards by not exceeding the `medium_risk` threshold of 0.6:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "log_metric(\n",
    "    key=\"GINI Score\",\n",
    "    value=0.5,\n",
    "    recorded_at=datetime(2025, 6, 9),\n",
    "    thresholds = {\n",
    "        \"high_risk\": 0.5,\n",
    "        \"medium_risk\": 0.6,\n",
    "        \"low_risk\": 0.8,\n",
    "    },\n",
    "    passed=False\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![GINI Score](../images/log_metric_attention.png)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Here, a custom function `passed_fn` determines the badge status automatically, displaying a green \"Satisfactory\" badge for the 0.65 GINI Score because it exceeds the `medium_risk` threshold of 0.6, enabling programmatic evaluation of metric performance based on predefined business rules:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "gini = 0.65\n",
    "\n",
    "thresholds = {\n",
    "    \"high_risk\": 0.5,\n",
    "    \"medium_risk\": 0.6,\n",
    "    \"low_risk\": 0.8,\n",
    "}\n",
    "\n",
    "def passed_fn(value):\n",
    "    return value > thresholds[\"medium_risk\"]\n",
    "\n",
    "log_metric(\n",
    "    key=\"GINI Score\",\n",
    "    value=gini, \n",
    "    recorded_at=datetime(2025, 6, 10),\n",
    "    thresholds=thresholds,\n",
    "    passed=passed_fn(gini)\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![GINI Score](../images/log_metric_satisfactory_2.png)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id='toc7_'></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='toc9_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",
    "What you see is the full draft of your model documentation in a more easily consumable version. From here, you can make qualitative edits to model documentation, 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='toc9_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='toc8_'></a>\n",
    "\n",
    "## Upgrade ValidMind\n",
    "\n",
    "<div class=\"alert alert-block alert-info\" style=\"background-color: #B5B5B510; color: black; border: 1px solid #083E44; border-left-width: 5px; box-shadow: 2px 2px 4px rgba(0, 0, 0, 0.2);border-radius: 5px;\">After installing ValidMind, you’ll want to periodically make sure you are on the latest version to access any new features and other enhancements.</div>\n",
    "\n",
    "Retrieve the information for the currently installed version of ValidMind:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%pip show validmind"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "If the version returned is lower than the version indicated in our [production open-source code](https://github.com/validmind/validmind-library/blob/prod/validmind/__version__.py), restart your notebook and run:\n",
    "\n",
    "```bash\n",
    "%pip install --upgrade validmind\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You may need to restart your kernel after running the upgrade package for changes to be applied."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "validmind-eEL8LtKG-py3.10",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.15"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
