diff --git a/notebooks/how_to/log_metrics_over_time.ipynb b/notebooks/how_to/log_metrics_over_time.ipynb index 8474273df..47e6abbc0 100644 --- a/notebooks/how_to/log_metrics_over_time.ipynb +++ b/notebooks/how_to/log_metrics_over_time.ipynb @@ -4,17 +4,59 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "# Log Metrics Over Time\n", + "# Log metrics over time\n", "\n", - "In this notebook we showcase how to track and visualize the temporal evolution of key model performance metrics, such as AUC, F1 score, precision, recall, and accuracy. 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. By monitoring these metrics systematically, teams can detect early warning signs of model drift and take proactive measures to maintain model reliability.\n", + "Learn how to track and visualize the temporal evolution of key model performance metrics with ValidMind.\n", "\n", - "ValidMind allows you to log metrics over time using the `log_metric()` function from the `validmind-library` and visualize them in your documentation using the *Metrics Over Time* block. This integration enables seamless tracking of model performance, with support for custom thresholds and automated alerting capabilities." + "- 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", + "
Metrics over time are most commonly associated with the continued monitoring of a model's performance once it is deployed.\n", + "

\n", + "While you are able to add Metric Over Time blocks to model documentation, we recommend first enabling ongoing monitoring for your model to maximize the potential of your performance data." ] }, { "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", + "\n", + ":::\n", + "\n", + "" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "\n", "\n", "\n", "## About ValidMind\n", @@ -24,6 +66,8 @@ "\n", "\n", "\n", + "\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", @@ -31,6 +75,8 @@ "\n", "\n", "\n", + "\n", + "\n", "### New to ValidMind?\n", "If you haven't already seen our [Get started with the ValidMind Library](https://docs.validmind.ai/developer/get-started-validmind-library.html), we recommend you begin by exploring the available resources in this section. There, you can learn more about documenting models, find code samples, or read our developer reference.\n", "\n", @@ -43,6 +89,8 @@ "cell_type": "markdown", "metadata": {}, "source": [ + "\n", + "\n", "\n", "\n", "### Key concepts\n", @@ -75,6 +123,8 @@ "cell_type": "markdown", "metadata": {}, "source": [ + "\n", + "\n", "\n", "\n", "## Install the ValidMind Library\n", @@ -95,6 +145,8 @@ "cell_type": "markdown", "metadata": {}, "source": [ + "\n", + "\n", "\n", "\n", "## Initialize the ValidMind Library\n", @@ -103,6 +155,8 @@ "\n", "\n", "\n", + "\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", @@ -120,7 +174,7 @@ "\n", "4. Go to **Getting Started** and click **Copy snippet to clipboard**.\n", "\n", - "Next, replace the placeholder with your own code snippet:" + "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:" ] }, { @@ -129,14 +183,21 @@ "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 = \"http://localhost:3000/api/v1/tracking\",\n", - " api_key = \"...\",\n", - " api_secret = \"...\",\n", - " model = \"...\",\n", - " monitoring = True\n", + " # api_host=\"...\",\n", + " # api_key=\"...\",\n", + " # api_secret=\"...\",\n", + " # model=\"...\",\n", + " monitoring = True\n", ")" ] }, @@ -144,6 +205,8 @@ "cell_type": "markdown", "metadata": {}, "source": [ + "\n", + "\n", "\n", "\n", "## Initialize the Python environment\n", @@ -153,7 +216,7 @@ }, { "cell_type": "code", - "execution_count": 3, + "execution_count": null, "metadata": {}, "outputs": [], "source": [ @@ -172,9 +235,14 @@ "cell_type": "markdown", "metadata": {}, "source": [ + "\n", + "\n", "## Load demo model\n", "\n", - "We use a classification model trained on customer churn data to demonstrate ValidMind's metric logging capabilities. The notebook uses a built-in classification dataset, processes it through train-validation-test splits, and trains an XGBoost classifier. 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." + "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." ] }, { @@ -224,7 +292,10 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Once the datasets and model are prepared for validation, we initialize ValidMind `dataset` and `model`, specifying features and targets columns. The property `input_id` allows users to uniquely identify each dataset and model. 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." + "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." ] }, { @@ -260,7 +331,9 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "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:" + "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:" ] }, { @@ -282,20 +355,13 @@ "cell_type": "markdown", "metadata": {}, "source": [ + "\n", + "\n", "## Log metrics\n", "\n", - "In this section, we demonstrate how to track the temporal evolution of key model performance metrics, such as AUC, F1 score, precision, recall, and accuracy. 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. 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", + "Next, we'll use ValidMind to track the temporal evolution of key model performance metrics.\n", "\n", - "We'll showcase how to set appropriate thresholds for each metric, enabling 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": "markdown", - "metadata": {}, - "source": [ - "### List Available Metrics \n", - "\n", - "We can list all available unit metrics by using the `list_metrics()` function from the `unit_metrics` module. This function returns a list of all available metric functions." + "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." ] }, { @@ -314,15 +380,19 @@ "cell_type": "markdown", "metadata": {}, "source": [ + "\n", + "\n", "### Run unit metrics\n", "\n", - "To compute individual metrics, we will use ValidMind's unit metrics - single-value metrics that can be computed on a dataset and model. Using the `run_metric()` function from the `validmind.unit_metrics` module, we can calculate these metrics. While this function has a signature similar to `run_test()` from the `validmind.tests` module, it is specifically designed for unit metrics and takes the following arguments:\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", - "- `metric_id`: The unique identifier for the metric (e.g., `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", + "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", - "The function returns and displays a result object similar to a normal 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." + "- **`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." ] }, { @@ -409,15 +479,17 @@ "cell_type": "markdown", "metadata": {}, "source": [ + "\n", + "\n", "### Log unit metrics over time\n", "\n", - "Using the `log_metric()` function from the `validmind.api_client` module, we can log the unit metrics over time. This function takes the following arguments:\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\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)" + "- **`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)" ] }, { @@ -429,7 +501,8 @@ "log_metric(\n", " key=\"AUC Score\",\n", " value=auc,\n", - " recorded_at=datetime(2024, 1, 1),\n", + " # If `recorded_at` is not included, the time at function run is logged\n", + " recorded_at=datetime(2024, 1, 1), \n", ")" ] }, @@ -437,7 +510,11 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "To visualize the logged metric, we can use the *Metrics Over Time* block in ValidMind. After adding this visualization block to your documentation (as shown in the image below), you'll be able to see your logged metrics plotted over time. In this example, since we've only logged a single data point, the visualization shows just one measurement. As you continue logging metrics, the graph will populate with more points, enabling you to track trends and patterns.\n", + "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)" @@ -447,11 +524,20 @@ "cell_type": "markdown", "metadata": {}, "source": [ + "\n", + "\n", "### Pass thresholds\n", "\n", - "We can pass thresholds to the `log_metric()` function to visualize the metric over time. This is useful for visualizing the metric over time and identifying potential issues. The metric visualization component provides a dynamic way to monitor and contextualize metric values through customizable thresholds. These thresholds appear as horizontal reference lines on the chart. 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", + "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. 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. " + "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. " ] }, { @@ -506,9 +592,14 @@ "cell_type": "markdown", "metadata": {}, "source": [ + "\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. 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. 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." + "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." ] }, { @@ -607,9 +698,9 @@ ], "metadata": { "kernelspec": { - "display_name": "validmind-eEL8LtKG-py3.10", + "display_name": "ValidMind Library", "language": "python", - "name": "python3" + "name": "validmind" }, "language_info": { "codemirror_mode": { diff --git a/pyproject.toml b/pyproject.toml index 346914f33..551252934 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -10,7 +10,7 @@ description = "ValidMind Library" license = "Commercial License" name = "validmind" readme = "README.pypi.md" -version = "2.8.4" +version = "2.8.5" [tool.poetry.dependencies] python = ">=3.8.1,<3.12" diff --git a/validmind/__version__.py b/validmind/__version__.py index e897069b0..79a53d3a7 100644 --- a/validmind/__version__.py +++ b/validmind/__version__.py @@ -1 +1 @@ -__version__ = "2.8.4" +__version__ = "2.8.5"