{"id":15648166,"url":"https://github.com/gokumohandas/monitoring-ml","last_synced_at":"2025-04-30T15:18:33.702Z","repository":{"id":51448468,"uuid":"520288280","full_name":"GokuMohandas/monitoring-ml","owner":"GokuMohandas","description":"Learn how to monitor ML systems to identify and mitigate sources of drift before model performance decay.","archived":false,"fork":false,"pushed_at":"2022-09-12T11:58:31.000Z","size":202,"stargazers_count":84,"open_issues_count":0,"forks_count":16,"subscribers_count":2,"default_branch":"main","last_synced_at":"2025-04-30T15:18:32.983Z","etag":null,"topics":["drift-detection","machine-learning","mlops","monitoring"],"latest_commit_sha":null,"homepage":"","language":"Jupyter Notebook","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/GokuMohandas.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2022-08-01T23:18:29.000Z","updated_at":"2025-04-17T19:49:21.000Z","dependencies_parsed_at":"2023-01-18T04:46:11.981Z","dependency_job_id":null,"html_url":"https://github.com/GokuMohandas/monitoring-ml","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/GokuMohandas%2Fmonitoring-ml","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/GokuMohandas%2Fmonitoring-ml/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/GokuMohandas%2Fmonitoring-ml/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/GokuMohandas%2Fmonitoring-ml/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/GokuMohandas","download_url":"https://codeload.github.com/GokuMohandas/monitoring-ml/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":251729735,"owners_count":21634281,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["drift-detection","machine-learning","mlops","monitoring"],"created_at":"2024-10-03T12:23:49.096Z","updated_at":"2025-04-30T15:18:33.683Z","avatar_url":"https://github.com/GokuMohandas.png","language":"Jupyter Notebook","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Monitoring ML\n\nLearn how to monitor ML systems to identify and address sources of drift before model performance decay.\n\n\u003cdiv align=\"left\"\u003e\n    \u003ca target=\"_blank\" href=\"https://madewithml.com\"\u003e\u003cimg src=\"https://img.shields.io/badge/Subscribe-40K-brightgreen\"\u003e\u003c/a\u003e\u0026nbsp;\n    \u003ca target=\"_blank\" href=\"https://github.com/GokuMohandas/Made-With-ML\"\u003e\u003cimg src=\"https://img.shields.io/github/stars/GokuMohandas/Made-With-ML.svg?style=social\u0026label=Star\"\u003e\u003c/a\u003e\u0026nbsp;\n    \u003ca target=\"_blank\" href=\"https://www.linkedin.com/in/goku\"\u003e\u003cimg src=\"https://img.shields.io/badge/style--5eba00.svg?label=LinkedIn\u0026logo=linkedin\u0026style=social\"\u003e\u003c/a\u003e\u0026nbsp;\n    \u003ca target=\"_blank\" href=\"https://twitter.com/GokuMohandas\"\u003e\u003cimg src=\"https://img.shields.io/twitter/follow/GokuMohandas.svg?label=Follow\u0026style=social\"\u003e\u003c/a\u003e\n    \u003cbr\u003e\n\u003c/div\u003e\n\n\u003cbr\u003e\n\n👉 \u0026nbsp;This repository contains the [interactive notebook](https://colab.research.google.com/github/GokuMohandas/monitoring-ml/blob/main/monitoring.ipynb) that complements the [monitoring lesson](https://madewithml.com/courses/mlops/monitoring/), which is a part of the [MLOps course](https://github.com/GokuMohandas/mlops-course). If you haven't already, be sure to check out the [lesson](https://madewithml.com/courses/mlops/monitoring/) because all the concepts are covered extensively and tied to software engineering best practices for building ML systems.\n\n\u003cdiv align=\"left\"\u003e\n\u003ca target=\"_blank\" href=\"https://madewithml.com/courses/mlops/monitoring/\"\u003e\u003cimg src=\"https://img.shields.io/badge/📖 Read-lesson-9cf\"\u003e\u003c/a\u003e\u0026nbsp;\n\u003ca href=\"https://github.com/GokuMohandas/monitoring-ml/blob/main/monitoring.ipynb\" role=\"button\"\u003e\u003cimg src=\"https://img.shields.io/static/v1?label=\u0026amp;message=View%20On%20GitHub\u0026amp;color=586069\u0026amp;logo=github\u0026amp;labelColor=2f363d\"\u003e\u003c/a\u003e\u0026nbsp;\n\u003ca href=\"https://colab.research.google.com/github/GokuMohandas/monitoring-ml/blob/main/monitoring.ipynb\"\u003e\u003cimg src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"\u003e\u003c/a\u003e\n\u003c/div\u003e\n\n\u003cbr\u003e\n\n- [Performance](#performance)\n- [Drift](#drift)\n    - [Data drift](#data-drift)\n    - [Target drift](#target-drift)\n    - [Concept drift](#concept-drift)\n- [Locating drift](#locating-drift)\n- [Measuring drift](#measuring-drift)\n    - [Expectations](#expectations)\n    - [Univariate](#univariate)\n    - [Multivariate](#multivariate)\n- [Online](#online)\n\n## Performance\n\nA key aspect of monitoring ML systems involves monitoring the actual performance of our deployed models. These could be quantitative evaluation metrics that we used during model evaluation (accuracy, precision, f1, etc.) but also key business metrics that the model influences (ROI, click rate, etc.). And it's usually never enough to just analyze the cumulative performance metrics across the entire span of time since the model has been deployed. Instead, we should also inspect performance across a period of time that's significant for our application (ex. daily). These sliding metrics might be more indicative of our system's health and we might be able to identify issues faster by not obscuring them with historical data.\n\n```python\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport seaborn as sns\nsns.set_theme()\n```\n```python\n# Generate data\nhourly_f1 = list(np.random.randint(low=94, high=98, size=24*20)) + \\\n            list(np.random.randint(low=92, high=96, size=24*5)) + \\\n            list(np.random.randint(low=88, high=96, size=24*5)) + \\\n            list(np.random.randint(low=86, high=92, size=24*5))\n```\n```python\n# Cumulative f1\ncumulative_f1 = [np.mean(hourly_f1[:n]) for n in range(1, len(hourly_f1)+1)]\nprint (f\"Average cumulative f1 on the last day: {np.mean(cumulative_f1[-24:]):.1f}\")\n```\n\u003cpre class=\"output\"\u003e\nAverage cumulative f1 on the last day: 93.7\n\u003c/pre\u003e\n```python\n# Sliding f1\nwindow_size = 24\nsliding_f1 = np.convolve(hourly_f1, np.ones(window_size)/window_size, mode=\"valid\")\nprint (f\"Average sliding f1 on the last day: {np.mean(sliding_f1[-24:]):.1f}\")\n```\n\u003cpre class=\"output\"\u003e\nAverage sliding f1 on the last day: 88.6\n\u003c/pre\u003e\n```python\nplt.ylim([80, 100])\nplt.hlines(y=90, xmin=0, xmax=len(hourly_f1), colors=\"blue\", linestyles=\"dashed\", label=\"threshold\")\nplt.plot(cumulative_f1, label=\"cumulative\")\nplt.plot(sliding_f1, label=\"sliding\")\nplt.legend()\n```\n\n\u003cdiv class=\"ai-center-all\"\u003e\n    \u003cimg width=\"500\" src=\"https://madewithml.com/static/images/mlops/monitoring/performance_drift.png\" alt=\"performance drift\"\u003e\n\u003c/div\u003e\n\n## Drift\n\nWe need to first understand the different types of issues that can cause our model's performance to decay (model drift). The best way to do this is to look at all the moving pieces of what we're trying to model and how each one can experience drift.\n\n\u003ccenter\u003e\n\n| Entity               | Description                              | Drift                                                               |\n| :------------------- | :--------------------------------------- | :------------------------------------------------------------------ |\n| $X$                  | inputs (features)                        | data drift     $\\rightarrow P(X) \\neq P_{ref}(X)$                 |\n| $y$                  | outputs (ground-truth)                   | target drift   $\\rightarrow P(y) \\neq P_{ref}(y)$                 |\n| $P(y \\vert X)$       | actual relationship between $X$ and $y$  | concept drift  $\\rightarrow P(y \\vert X) \\neq P_{ref}(y \\vert X)$ |\n\n\u003c/center\u003e\n\n### Data drift\n\nData drift, also known as feature drift or covariate shift, occurs when the distribution of the *production* data is different from the *training* data. The model is not equipped to deal with this drift in the feature space and so, it's predictions may not be reliable. The actual cause of drift can be attributed to natural changes in the real-world but also to systemic issues such as missing data, pipeline errors, schema changes, etc. It's important to inspect the drifted data and trace it back along it's pipeline to identify when and where the drift was introduced.\n\n\u003cdiv class=\"ai-center-all\"\u003e\n    \u003cimg width=\"700\" src=\"https://madewithml.com/static/images/mlops/monitoring/data_drift.png\" alt=\"data drift\"\u003e\n\u003c/div\u003e\n\u003cdiv class=\"ai-center-all\"\u003e\n    \u003csmall\u003eData drift can occur in either continuous or categorical features.\u003c/small\u003e\n\u003c/div\u003e\n\n\n### Target drift\n\nBesides just the input data changing, as with data drift, we can also experience drift in our outcomes. This can be a shift in the distributions but also the removal or addition of new classes with categorical tasks. Though retraining can mitigate the performance decay caused target drift, it can often be avoided with proper inter-pipeline communication about new classes, schema changes, etc.\n\n### Concept drift\n\nBesides the input and output data drifting, we can have the actual relationship between them drift as well. This concept drift renders our model ineffective because the patterns it learned to map between the original inputs and outputs are no longer relevant. Concept drift can be something that occurs in [various patterns](https://link.springer.com/article/10.1007/s11227-018-2674-1):\n\n\u003cdiv class=\"ai-center-all\"\u003e\n    \u003cimg width=\"500\" src=\"https://madewithml.com/static/images/mlops/monitoring/concept_drift.png\" alt=\"concept drift\"\u003e\n\u003c/div\u003e\n\n\u003cbr\u003e\n\n- gradually over a period of time\n- abruptly as a result of an external event\n- periodically as a result of recurring events\n\n\u003e All the different types of drift we discussed can can occur simultaneously which can complicated identifying the sources of drift.\n\n### Locating drift\n\nNow that we've identified the different types of drift, we need to learn how to locate and how often to measure it. Here are the constraints we need to consider:\n\n- **reference window**: the set of points to compare production data distributions with to identify drift.\n- **test window**: the set of points to compare with the reference window to determine if drift has occurred.\n\nSince we're dealing with online drift detection (ie. detecting drift in live production data as opposed to past batch data), we can employ either a [fixed or sliding window approach](https://onlinelibrary.wiley.com/doi/full/10.1002/widm.1381) to identify our set of points for comparison. Typically, the reference window is a fixed, recent subset of the training data while the test window slides over time.\n\n### Measuring drift\n\nOnce we have the window of points we wish to compare, we need to know how to compare them.\n\n```python\nimport great_expectations as ge\nimport json\nimport pandas as pd\nfrom urllib.request import urlopen\n```\n```python\n# Load labeled projects\nprojects = pd.read_csv(\"https://raw.githubusercontent.com/GokuMohandas/Made-With-ML/main/datasets/projects.csv\")\ntags = pd.read_csv(\"https://raw.githubusercontent.com/GokuMohandas/Made-With-ML/main/datasets/tags.csv\")\ndf = ge.dataset.PandasDataset(pd.merge(projects, tags, on=\"id\"))\ndf[\"text\"] = df.title + \" \" + df.description\ndf.drop([\"title\", \"description\"], axis=1, inplace=True)\ndf.head(5)\n```\n\n\u003cdiv class=\"output_subarea output_html rendered_html output_result\" dir=\"auto\"\u003e\u003cdiv\u003e\n\u003ctable border=\"1\" class=\"dataframe\"\u003e\n  \u003cthead\u003e\n    \u003ctr style=\"text-align: right;\"\u003e\n      \u003cth\u003e\u003c/th\u003e\n      \u003cth\u003eid\u003c/th\u003e\n      \u003cth\u003ecreated_on\u003c/th\u003e\n      \u003cth\u003etag\u003c/th\u003e\n      \u003cth\u003etext\u003c/th\u003e\n    \u003c/tr\u003e\n  \u003c/thead\u003e\n  \u003ctbody\u003e\n    \u003ctr\u003e\n      \u003cth\u003e0\u003c/th\u003e\n      \u003ctd\u003e6\u003c/td\u003e\n      \u003ctd\u003e2020-02-20 06:43:18\u003c/td\u003e\n      \u003ctd\u003ecomputer-vision\u003c/td\u003e\n      \u003ctd\u003eComparison between YOLO and RCNN on real world...\u003c/td\u003e\n    \u003c/tr\u003e\n    \u003ctr\u003e\n      \u003cth\u003e1\u003c/th\u003e\n      \u003ctd\u003e7\u003c/td\u003e\n      \u003ctd\u003e2020-02-20 06:47:21\u003c/td\u003e\n      \u003ctd\u003ecomputer-vision\u003c/td\u003e\n      \u003ctd\u003eShow, Infer \u0026amp; Tell: Contextual Inference for C...\u003c/td\u003e\n    \u003c/tr\u003e\n    \u003ctr\u003e\n      \u003cth\u003e2\u003c/th\u003e\n      \u003ctd\u003e9\u003c/td\u003e\n      \u003ctd\u003e2020-02-24 16:24:45\u003c/td\u003e\n      \u003ctd\u003egraph-learning\u003c/td\u003e\n      \u003ctd\u003eAwesome Graph Classification A collection of i...\u003c/td\u003e\n    \u003c/tr\u003e\n    \u003ctr\u003e\n      \u003cth\u003e3\u003c/th\u003e\n      \u003ctd\u003e15\u003c/td\u003e\n      \u003ctd\u003e2020-02-28 23:55:26\u003c/td\u003e\n      \u003ctd\u003ereinforcement-learning\u003c/td\u003e\n      \u003ctd\u003eAwesome Monte Carlo Tree Search A curated list...\u003c/td\u003e\n    \u003c/tr\u003e\n    \u003ctr\u003e\n      \u003cth\u003e4\u003c/th\u003e\n      \u003ctd\u003e19\u003c/td\u003e\n      \u003ctd\u003e2020-03-03 13:54:31\u003c/td\u003e\n      \u003ctd\u003egraph-learning\u003c/td\u003e\n      \u003ctd\u003eDiffusion to Vector Reference implementation o...\u003c/td\u003e\n    \u003c/tr\u003e\n  \u003c/tbody\u003e\n\u003c/table\u003e\n\u003c/div\u003e\u003c/div\u003e\n\n### Expectations\n\nThe first line of measurement can be rule-based such as validating [expectations](https://docs.greatexpectations.io/en/latest/reference/glossary_of_expectations.html) around missing values, data types, value ranges, etc. as we did in our [data testing lesson](https://madewithml.com/courses/mlops/testing#expectations). These can be done with or without a reference window and using the [mostly argument](https://docs.greatexpectations.io/en/latest/reference/core_concepts/expectations/standard_arguments.html#mostly) for some level of tolerance.\n\n```python\n# Simulated production data\nprod_df = ge.dataset.PandasDataset([{\"text\": \"hello\"}, {\"text\": 0}, {\"text\": \"world\"}])\n```\n```python\n# Expectation suite\ndf.expect_column_values_to_not_be_null(column=\"text\")\ndf.expect_column_values_to_be_of_type(column=\"text\", type_=\"str\")\nexpectation_suite = df.get_expectation_suite()\n```\n```python\n# Validate reference data\ndf.validate(expectation_suite=expectation_suite, only_return_failures=True)[\"statistics\"]\n```\n\n```json\n{\"evaluated_expectations\": 2,\n \"success_percent\": 100.0,\n \"successful_expectations\": 2,\n \"unsuccessful_expectations\": 0}\n```\n\n```python\n# Validate production data\nprod_df.validate(expectation_suite=expectation_suite, only_return_failures=True)[\"statistics\"]\n```\n\n```json\n{\"evaluated_expectations\": 2,\n \"success_percent\": 50.0,\n \"successful_expectations\": 1,\n \"unsuccessful_expectations\": 1}\n```\n\nOnce we've validated our rule-based expectations, we need to quantitatively measure drift across the different features in our data.\n\n### Univariate\n\nOur task may involve univariate (1D) features that we will want to monitor. While there are many types of hypothesis tests we can use, a popular option is the [Kolmogorov-Smirnov (KS) test](https://en.wikipedia.org/wiki/Kolmogorov%E2%80%93Smirnov_test).\n\n#### Kolmogorov-Smirnov (KS) test\n\nThe KS test determines the maximum distance between two distribution's cumulative density functions. Here, we'll measure if there is any drift on the size of our input text feature between two different data subsets.\n\n```python\nfrom alibi_detect.cd import KSDrift\n```\n\n```python\n# Reference\ndf[\"num_tokens\"] = df.text.apply(lambda x: len(x.split(\" \")))\nref = df[\"num_tokens\"][0:200].to_numpy()\nplt.hist(ref, alpha=0.75, label=\"reference\")\nplt.legend()\nplt.show()\n```\n\n```python\n# Initialize drift detector\nlength_drift_detector = KSDrift(ref, p_val=0.01)\n```\n\n```python\n# No drift\nno_drift = df[\"num_tokens\"][200:400].to_numpy()\nplt.hist(ref, alpha=0.75, label=\"reference\")\nplt.hist(no_drift, alpha=0.5, label=\"test\")\nplt.legend()\nplt.show()\n```\n\n\u003cdiv class=\"ai-center-all\"\u003e\n    \u003cimg width=\"500\" src=\"https://madewithml.com/static/images/mlops/monitoring/ks_no_drift.png\" alt=\"no drift with KS test\"\u003e\n\u003c/div\u003e\n\u003cbr\u003e\n\n```python\nlength_drift_detector.predict(no_drift, return_p_val=True, return_distance=True)\n```\n\n```json\n{\"data\": {\"distance\": array([0.09], dtype=float32),\n  \"is_drift\": 0,\n  \"p_val\": array([0.3927307], dtype=float32),\n  \"threshold\": 0.01},\n \"meta\": {\"data_type\": None,\n  \"detector_type\": \"offline\",\n  \"name\": \"KSDrift\",\n  \"version\": \"0.9.1\"}}\n```\n\n\u003e \u0026darr; p-value = \u0026uarr; confident that the distributions are different.\n\n```python\n# Drift\ndrift = np.random.normal(30, 5, len(ref))\nplt.hist(ref, alpha=0.75, label=\"reference\")\nplt.hist(drift, alpha=0.5, label=\"test\")\nplt.legend()\nplt.show()\n```\n\n\u003cdiv class=\"ai-center-all\"\u003e\n    \u003cimg width=\"500\" src=\"https://madewithml.com/static/images/mlops/monitoring/ks_drift.png\" alt=\"drift detection with KS\"\u003e\n\u003c/div\u003e\n\u003cbr\u003e\n\n```python\nlength_drift_detector.predict(drift, return_p_val=True, return_distance=True)\n```\n\n```json\n{\"data\": {\"distance\": array([0.63], dtype=float32),\n  \"is_drift\": 1,\n  \"p_val\": array([6.7101775e-35], dtype=float32),\n  \"threshold\": 0.01},\n \"meta\": {\"data_type\": None,\n  \"detector_type\": \"offline\",\n  \"name\": \"KSDrift\",\n  \"version\": \"0.9.1\"}}\n```\n\n#### Chi-squared test\n\nSimilarly, for categorical data (input features, targets, etc.), we can apply the [Pearson's chi-squared test](https://en.wikipedia.org/wiki/Pearson%27s_chi-squared_test) to determine if a frequency of events in production is consistent with a reference distribution.\n\n\u003e We're creating a categorical variable for the # of tokens in our text feature but we could very very apply it to the tag distribution itself, individual tags (binary), slices of tags, etc.\n\n```python\nfrom alibi_detect.cd import ChiSquareDrift\n```\n\n```python\n# Reference\ndf.token_count = df.num_tokens.apply(lambda x: \"small\" if x \u003c= 10 else (\"medium\" if x \u003c=25 else \"large\"))\nref = df.token_count[0:200].to_numpy()\nplt.hist(ref, alpha=0.75, label=\"reference\")\nplt.legend()\n```\n\n```python\n# Initialize drift detector\ntarget_drift_detector = ChiSquareDrift(ref, p_val=0.01)\n```\n\n```python\n# No drift\nno_drift = df.token_count[200:400].to_numpy()\nplt.hist(ref, alpha=0.75, label=\"reference\")\nplt.hist(no_drift, alpha=0.5, label=\"test\")\nplt.legend()\nplt.show()\n```\n\n\u003cdiv class=\"ai-center-all\"\u003e\n    \u003cimg width=\"500\" src=\"https://madewithml.com/static/images/mlops/monitoring/chi_no_drift.png\" alt=\"no drift with chi squared test\"\u003e\n\u003c/div\u003e\n\u003cbr\u003e\n\n```python\ntarget_drift_detector.predict(no_drift, return_p_val=True, return_distance=True)\n```\n\n```json\n{\"data\": {\"distance\": array([4.135522], dtype=float32),\n  \"is_drift\": 0,\n  \"p_val\": array([0.12646863], dtype=float32),\n  \"threshold\": 0.01},\n \"meta\": {\"data_type\": None,\n  \"detector_type\": \"offline\",\n  \"name\": \"ChiSquareDrift\",\n  \"version\": \"0.9.1\"}}\n```\n\n```python\n# Drift\ndrift = np.array([\"small\"]*80 + [\"medium\"]*40 + [\"large\"]*80)\nplt.hist(ref, alpha=0.75, label=\"reference\")\nplt.hist(drift, alpha=0.5, label=\"test\")\nplt.legend()\nplt.show()\n```\n\n\u003cdiv class=\"ai-center-all\"\u003e\n    \u003cimg width=\"500\" src=\"https://madewithml.com/static/images/mlops/monitoring/chi_drift.png\" alt=\"drift detection with chi squared tests\"\u003e\n\u003c/div\u003e\n\u003cbr\u003e\n\n```python\ntarget_drift_detector.predict(drift, return_p_val=True, return_distance=True)\n```\n\n```json\n{\"data\": {\"is_drift\": 1,\n  \"distance\": array([118.03355], dtype=float32),\n  \"p_val\": array([2.3406739e-26], dtype=float32),\n  \"threshold\": 0.01},\n \"meta\": {\"name\": \"ChiSquareDrift\",\n  \"detector_type\": \"offline\",\n  \"data_type\": None}}\n```\n\n### Multivariate\n\nAs we can see, measuring drift is fairly straightforward for univariate data but difficult for multivariate data. We'll summarize the reduce and measure approach outlined in the following paper: [Failing Loudly: An Empirical Study of Methods for Detecting Dataset Shift](https://arxiv.org/abs/1810.11953).\n\n\u003cdiv class=\"ai-center-all\"\u003e\n    \u003cimg width=\"700\" src=\"https://madewithml.com/static/images/mlops/monitoring/failing_loudly.png\" alt=\"multivariate drift detection\"\u003e\n\u003c/div\u003e\nWe vectorized our text using tf-idf (to keep modeling simple), which has high dimensionality and is not semantically rich in context. However, typically with text, word/char embeddings are used. So to illustrate what drift detection on multivariate data would look like, let's represent our text using pretrained embeddings.\n\n\u003e Be sure to refer to our [embeddings](https://madewithml.com/courses/foundations/embeddings/) and [transformers](https://madewithml.com/courses/foundations/transformers/) lessons to learn more about these topics. But note that detecting drift on multivariate text embeddings is still quite difficult so it's typically more common to use these methods applied to tabular features or images.\n\nWe'll start by loading the tokenizer from a pretrained model.\n\n```python\nfrom transformers import AutoTokenizer\n```\n\n```python\nmodel_name = \"allenai/scibert_scivocab_uncased\"\ntokenizer = AutoTokenizer.from_pretrained(model_name)\nvocab_size = len(tokenizer)\nprint (vocab_size)\n```\n\n\u003cpre class=\"output\"\u003e\n31090\n\u003c/pre\u003e\n\n```python\n# Tokenize inputs\nencoded_input = tokenizer(df.text.tolist(), return_tensors=\"pt\", padding=True)\nids = encoded_input[\"input_ids\"]\nmasks = encoded_input[\"attention_mask\"]\n```\n\n```python\n# Decode\nprint (f\"{ids[0]}\\n{tokenizer.decode(ids[0])}\")\n```\n\n\u003cpre class=\"output\"\u003e\ntensor([  102,  2029,   467,  1778,   609,   137,  6446,  4857,   191,  1332,\n         2399, 13572, 19125,  1983,   147,  1954,   165,  6240,   205,   185,\n          300,  3717,  7434,  1262,   121,   537,   201,   137,  1040,   111,\n          545,   121,  4714,   205,   103,     0,     0,     0,     0,     0,\n            0,     0,     0,     0,     0,     0,     0,     0,     0,     0,\n            0,     0,     0,     0,     0,     0,     0,     0,     0,     0,\n            0])\n[CLS] comparison between yolo and rcnn on real world videos bringing theory to experiment is cool. we can easily train models in colab and find the results in minutes. [SEP] [PAD] [PAD] ...\n\u003c/pre\u003e\n\n```python\n# Sub-word tokens\nprint (tokenizer.convert_ids_to_tokens(ids=ids[0]))\n```\n\n\u003cpre class=\"output\"\u003e\n['[CLS]', 'comparison', 'between', 'yo', '##lo', 'and', 'rc', '##nn', 'on', 'real', 'world', 'videos', 'bringing', 'theory', 'to', 'experiment', 'is', 'cool', '.', 'we', 'can', 'easily', 'train', 'models', 'in', 'col', '##ab', 'and', 'find', 'the', 'results', 'in', 'minutes', '.', '[SEP]', '[PAD]', '[PAD]', ...]\n\u003c/pre\u003e\n\nNext, we'll load the pretrained model's weights and use the `TransformerEmbedding` object to extract the embeddings from the hidden state (averaged across tokens).\n\n```python\nfrom alibi_detect.models.pytorch import TransformerEmbedding\n```\n\n```python\n# Embedding layer\nemb_type = \"hidden_state\"\nlayers = [-x for x in range(1, 9)]  # last 8 layers\nembedding_layer = TransformerEmbedding(model_name, emb_type, layers)\n```\n\n```python\n# Embedding dimension\nembedding_dim = embedding_layer.model.embeddings.word_embeddings.embedding_dim\nembedding_dim\n```\n\n\u003cpre class=\"output\"\u003e\n768\n\u003c/pre\u003e\n\n#### Dimensionality reduction\n\nNow we need to use a dimensionality reduction method to reduce our representations dimensions into something more manageable (ex. 32 dim) so we can run our two-sample tests on to detect drift. Popular options include:\n\n- [Principle component analysis (PCA)](https://en.wikipedia.org/wiki/Principal_component_analysis): orthogonal transformations that preserve the variability of the dataset.\n- [Autoencoders (AE)](https://en.wikipedia.org/wiki/Autoencoder): networks that consume the inputs and attempt to reconstruct it from an lower dimensional space while minimizing the error. These can either be trained or untrained (the Failing loudly paper recommends untrained).\n- [Black box shift detectors (BBSD)](https://arxiv.org/abs/1802.03916): the actual model trained on the training data can be used as a dimensionality reducer. We can either use the softmax outputs (multivariate) or the actual predictions (univariate).\n\n```python\nimport torch\nimport torch.nn as nn\n```\n\n```python\n# Device\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\nprint(device)\n```\n\n\u003cpre class=\"output\"\u003e\ncuda\n\u003c/pre\u003e\n\n```python\n# Untrained autoencoder (UAE) reducer\nencoder_dim = 32\nreducer = nn.Sequential(\n    embedding_layer,\n    nn.Linear(embedding_dim, 256),\n    nn.ReLU(),\n    nn.Linear(256, encoder_dim)\n).to(device).eval()\n```\n\nWe can wrap all of the operations above into one preprocessing function that will consume input text and produce the reduced representation.\n\n```python\nfrom alibi_detect.cd.pytorch import preprocess_drift\nfrom functools import partial\n```\n\n```python\n# Preprocessing with the reducer\nmax_len = 100\nbatch_size = 32\npreprocess_fn = partial(preprocess_drift, model=reducer, tokenizer=tokenizer,\n                        max_len=max_len, batch_size=batch_size, device=device)\n```\n\n#### Maximum Mean Discrepancy (MMD)\n\nAfter applying dimensionality reduction techniques on our multivariate data, we can use different statistical tests to calculate drift. A popular option is [Maximum Mean Discrepancy (MMD)](https://jmlr.csail.mit.edu/papers/v13/gretton12a.html), a kernel-based approach that determines the distance between two distributions by computing the distance between the mean embeddings of the features from both distributions.\n\n```python\nfrom alibi_detect.cd import MMDDrift\n```\n\n```python\n# Initialize drift detector\nmmd_drift_detector = MMDDrift(ref, backend=\"pytorch\", p_val=.01, preprocess_fn=preprocess_fn)\n```\n\n```python\n# No drift\nno_drift = df.text[200:400].to_list()\nmmd_drift_detector.predict(no_drift)\n```\n\n```json\n{\"data\": {\"distance\": 0.0021169185638427734,\n  \"distance_threshold\": 0.0032651424,\n  \"is_drift\": 0,\n  \"p_val\": 0.05999999865889549,\n  \"threshold\": 0.01},\n \"meta\": {\"backend\": \"pytorch\",\n  \"data_type\": None,\n  \"detector_type\": \"offline\",\n  \"name\": \"MMDDriftTorch\",\n  \"version\": \"0.9.1\"}}\n```\n\n```python\n# Drift\ndrift = [\"UNK \" + text for text in no_drift]\nmmd_drift_detector.predict(drift)\n```\n\n```json\n{\"data\": {\"distance\": 0.014705955982208252,\n  \"distance_threshold\": 0.003908038,\n  \"is_drift\": 1,\n  \"p_val\": 0.0,\n  \"threshold\": 0.01},\n \"meta\": {\"backend\": \"pytorch\",\n  \"data_type\": None,\n  \"detector_type\": \"offline\",\n  \"name\": \"MMDDriftTorch\",\n  \"version\": \"0.9.1\"}}\n```\n\n## Online\n\nSo far we've applied our drift detection methods on offline data to try and understand what reference window sizes should be, what p-values are appropriate, etc. However, we'll need to apply these methods in the online production setting so that we can catch drift as easy as possible.\n\n\u003e Many monitoring libraries and platforms come with [online equivalents](https://docs.seldon.io/projects/alibi-detect/en/latest/cd/methods.html#online) for their detection methods.\n\nTypically, reference windows are large so that we have a proper benchmark to compare our production data points to. As for the test window, the smaller it is, the more quickly we can catch sudden drift. Whereas, a larger test window will allow us to identify more subtle/gradual drift. So it's best to compose windows of different sizes to regularly monitor.\n\n```python\nfrom alibi_detect.cd import MMDDriftOnline\n```\n\n```python\n# Online MMD drift detector\nref = df.text[0:800].to_list()\nonline_mmd_drift_detector = MMDDriftOnline(\n    ref, ert=400, window_size=200, backend=\"pytorch\", preprocess_fn=preprocess_fn)\n```\n\n\u003cpre class=\"output\"\u003e\nGenerating permutations of kernel matrix..\n100%|██████████| 1000/1000 [00:00\u003c00:00, 13784.22it/s]\nComputing thresholds: 100%|██████████| 200/200 [00:32\u003c00:00,  6.11it/s]\n\u003c/pre\u003e\n\nAs data starts to flow in, we can use the detector to predict drift at every point. Our detector should detect drift sooner in our drifter dataset than in our normal data.\n\n```python\ndef simulate_production(test_window):\n    i = 0\n    online_mmd_drift_detector.reset()\n    for text in test_window:\n        result = online_mmd_drift_detector.predict(text)\n        is_drift = result[\"data\"][\"is_drift\"]\n        if is_drift:\n            break\n        else:\n            i += 1\n    print (f\"{i} steps\")\n```\n\n```python\n# Normal\ntest_window = df.text[800:]\nsimulate_production(test_window)\n```\n\n\u003cpre class=\"output\"\u003e\n27 steps\n\u003c/pre\u003e\n\n```python\n# Drift\ntest_window = \"UNK\" * len(df.text[800:])\nsimulate_production(test_window)\n```\n\n\u003cpre class=\"output\"\u003e\n11 steps\n\u003c/pre\u003e\n\nThere are also several considerations around how often to refresh both the reference and test windows. We could base in on the number of new observations or time without drift, etc. We can also adjust the various thresholds (ERT, window size, etc.) based on what we learn about our system through monitoring.\n\n## Learn more\n\nWhile these are the foundational concepts for monitoring ML systems, there are a lot of software best practices for monitoring that we cannot show in an isolated repository. Learn more in our [monitoring lesson](https://madewithml.com/courses/mlops/monitoring/).","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fgokumohandas%2Fmonitoring-ml","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fgokumohandas%2Fmonitoring-ml","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fgokumohandas%2Fmonitoring-ml/lists"}