{"id":700,"date":"2020-10-13T14:25:18","date_gmt":"2020-10-13T21:25:18","guid":{"rendered":"https:\/\/devblogs.microsoft.com\/azure-sdk\/?p=700"},"modified":"2020-10-13T14:25:18","modified_gmt":"2020-10-13T21:25:18","slug":"metrics-advisor-anomaly-detection","status":"publish","type":"post","link":"https:\/\/devblogs.microsoft.com\/azure-sdk\/metrics-advisor-anomaly-detection\/","title":{"rendered":"Detect anomalies in your data with Metrics Advisor"},"content":{"rendered":"<h2>Metrics Advisor Service Introduction<\/h2>\n<p><a href=\"https:\/\/docs.microsoft.com\/azure\/cognitive-services\/metrics-advisor\/overview\">Metrics Advisor<\/a> is an Azure Cognitive Service that uses AI to perform data monitoring and anomaly detection on timeseries data. The service automates the process of applying models to your data, and provides a set of APIs and web-based workspace for data ingestion, anomaly detection, and diagnostics &#8211; without needing to know machine learning.<\/p>\n<p>We can use Metrics Advisor to:<\/p>\n<ul>\n<li>Analyze multi-dimensional data from multiple data sources<\/li>\n<li>Identify and correlate anomalies<\/li>\n<li>Configure and fine-tune the anomaly detection model used on your data<\/li>\n<li>Diagnose anomalies and help with root cause analysis<\/li>\n<\/ul>\n<h2>Basic Concepts<\/h2>\n<p>To get started, you must onboard your data from one of the supported data source types and configure the data feed settings. See the <a href=\"https:\/\/docs.microsoft.com\/azure\/cognitive-services\/metrics-advisor\/how-tos\/onboard-your-data\">&#8220;How-to: Onboard your metric data to Metrics Advisor&#8221;<\/a> article for detailed instructions on how to configure your data. As data is ingested, you can fine-tune the anomaly detection to fit your scenario and subscribe to alerts with notification hooks that will let you know of any anomalies detected. Moving forward, the service will provide diagnostic insights including root cause analysis and recommended actions while additionally using your feedback to perform automatic model customization and earlier notice of future anomalies.<\/p>\n<h3>Metric, Dimensions, and Timeseries<\/h3>\n<p>The service can connect to various data sources. Consumers specify the <em>metrics<\/em> in the data-source that they want service to monitor and the <em>dimensions<\/em> of the metric. Service produces <em>timeseries<\/em> data for each metric across <em>dimensions<\/em>.<\/p>\n<p><img decoding=\"async\" src=\"https:\/\/devblogs.microsoft.com\/azure-sdk\/wp-content\/uploads\/sites\/58\/2020\/10\/20201013-metics-dimensions-time-series.png\" alt=\"\" \/><\/p>\n<h3>Anomaly<\/h3>\n<p>An <em>anomaly<\/em> is an abnormal data point in the <em>timeseries<\/em>.<\/p>\n<p><img decoding=\"async\" src=\"https:\/\/devblogs.microsoft.com\/azure-sdk\/wp-content\/uploads\/sites\/58\/2020\/10\/20201013-anomaly.png\" alt=\"\" \/><\/p>\n<h3>Anomaly Detection<\/h3>\n<p>Consumers can specify the <em>anomaly detection configurations<\/em> for the <em>metric<\/em> and <em>timeseries<\/em>, which will be used to detect the abnormal data point (i.e. anomalies).<\/p>\n<p><img decoding=\"async\" src=\"https:\/\/devblogs.microsoft.com\/azure-sdk\/wp-content\/uploads\/sites\/58\/2020\/10\/20201013-anomaly-detection.png\" alt=\"\" \/><\/p>\n<h3>Alert<\/h3>\n<p>The <em>alert configuration<\/em> can be used to combine multiple <em>anomaly detection configurations<\/em> and produce alerts.<\/p>\n<p><img decoding=\"async\" src=\"https:\/\/devblogs.microsoft.com\/azure-sdk\/wp-content\/uploads\/sites\/58\/2020\/10\/20201013-alert.png\" alt=\"\" \/><\/p>\n<h3>Incident<\/h3>\n<p>When anomalies appear for a long period of time or show some pattern, then service treats it as an incident. An <em>alerting configuration<\/em> can have notification hooks attached to it and an alert will be sent to the hook. Currently the supported hooks are &#8211; email and webhook.<\/p>\n<p><img decoding=\"async\" src=\"https:\/\/devblogs.microsoft.com\/azure-sdk\/wp-content\/uploads\/sites\/58\/2020\/10\/20201013-incident.png\" alt=\"\" \/><\/p>\n<h2>Get the package<\/h2>\n<p>Today we want to demonstrate how to use the <a href=\"https:\/\/pypi.org\/project\/azure-ai-metricsadvisor\/\">Python Metrics Advisor client library<\/a> to configure the Metrics Advisor service, monitor anomalies, and handle incidents.<\/p>\n<p>Run the following command to install the library:<\/p>\n<pre><code class=\"python\">pip install azure-ai-metricsadvisor --pre\n<\/code><\/pre>\n<p>We also support other languages including <a href=\"https:\/\/www.nuget.org\/packages\/Azure.AI.MetricsAdvisor\/\">.NET<\/a>, <a href=\"https:\/\/www.npmjs.com\/package\/@azure\/ai-metrics-advisor\">JavaScript\/TypeScript<\/a>, and <a href=\"https:\/\/oss.sonatype.org\/#nexus-search;quick~azure-ai-metricsadvisor\">Java<\/a>.<\/p>\n<h2>Configure Metrics Advisor Service<\/h2>\n<p>To configure Metrics Advisor service, we need an authorized <code>MetricsAdvisorAdministrationClient<\/code> which needs two keys: &#8211; The subscription key to your Metrics Advisor resource. You can find this in the Keys and Endpoint section of your resource in the Azure portal. &#8211; The API key for your Metrics Advisor instance. You can find this in the workspace for Metrics Advisor, in API keys on the left navigation menu.<\/p>\n<p>Then you can use the keys to create a client:<\/p>\n<pre><code class=\"python\">from azure.ai.metricsadvisor import (\n    MetricsAdvisorKeyCredential,\n    MetricsAdvisorAdministrationClient,\n)\nclient = MetricsAdvisorAdministrationClient (&lt;service_endpoint&gt;,\n        MetricsAdvisorKeyCredential(&lt;subscription_key&gt;, &lt;api_key&gt;))\n<\/code><\/pre>\n<p>Now let&#8217;s get our data onboarded. Metrics Advisor supports connecting different types of data sources. In this demo, we will use the data from SQL Server.<\/p>\n<pre><code class=\"python\">import datetime\nfrom azure.ai.metricsadvisor.models import (\n        SQLServerDataFeed,\n        DataFeedSchema,\n        Metric,\n        Dimension,\n        DataFeedOptions,\n        DataFeedRollupSettings,\n        DataFeedMissingDataPointFillSettings\n    )\n\ndata_feed = client.create_data_feed(\n    name=\"My data feed\",\n    source=SQLServerDataFeed(\n        connection_string=&lt;sql_server_connection_string&gt;,\n        query=&lt;query&gt;,\n    ),\n    granularity=\"Daily\",\n    schema=DataFeedSchema(\n        metrics=[\n            Metric(name=\"cost\", display_name=\"Cost\"),\n            Metric(name=\"revenue\", display_name=\"Revenue\")\n        ],\n        dimensions=[\n            Dimension(name=\"category\", display_name=\"Category\"),\n            Dimension(name=\"city\", display_name=\"City\")\n        ],\n        timestamp_column=\"Timestamp\"\n    ),\n    ingestion_settings=datetime.datetime(2019, 10, 1),\n    options=DataFeedOptions(\n        data_feed_description=\"cost\/revenue data feed\",\n        rollup_settings=DataFeedRollupSettings(\n            rollup_type=\"AutoRollup\",\n            rollup_method=\"Sum\",\n            rollup_identification_value=\"__SUM__\"\n        ),\n        missing_data_point_fill_settings=DataFeedMissingDataPointFillSettings(\n            fill_type=\"SmartFilling\"\n        ),\n        access_mode=\"Private\"\n    )\n)\n<\/code><\/pre>\n<p>Here we set rollup_type to &#8220;AutoRollup&#8221; and rollup_method to &#8220;Sum&#8221; so the service will automatically use &#8220;Sum&#8221; method to calculate the aggregations for the ingested data.<\/p>\n<p>After the data is ingested, a default detection configuration is automatically applied to each metric. Now, we want to configure an <code>AnomalyAlertConfiguration<\/code> to tell the service in which conditions an alert needs to be triggered.<\/p>\n<pre><code class=\"python\">from azure.ai.metricsadvisor.models import (\n    MetricAlertConfiguration,\n    MetricAnomalyAlertScope,\n    TopNGroupScope,\n    MetricAnomalyAlertConditions,\n    SeverityCondition,\n    MetricBoundaryCondition,\n    MetricAnomalyAlertSnoozeCondition\n)\n\nalert_config = client.create_anomaly_alert_configuration(\n    name=\"my alert config\",\n    description=\"alert config description\",\n    cross_metrics_operator=\"AND\",\n    metric_alert_configurations=[\n        MetricAlertConfiguration(\n            detection_configuration_id=&lt;anomaly_detection_configuration_id&gt;,\n            alert_scope=MetricAnomalyAlertScope(\n                scope_type=\"WholeSeries\"\n            ),\n            alert_conditions=MetricAnomalyAlertConditions(\n                severity_condition=SeverityCondition(\n                    min_alert_severity=\"Low\",\n                    max_alert_severity=\"High\"\n                )\n            )\n        ),\n        MetricAlertConfiguration(\n            detection_configuration_id=&lt;anomaly_detection_configuration_id&gt;,\n            alert_scope=MetricAnomalyAlertScope(\n                scope_type=\"TopN\",\n                top_n_group_in_scope=TopNGroupScope(\n                    top=10,\n                    period=5,\n                    min_top_count=5\n                )\n            ),\n            alert_conditions=MetricAnomalyAlertConditions(\n                metric_boundary_condition=MetricBoundaryCondition(\n                    direction=\"Up\",\n                    upper=50\n                )\n            ),\n            alert_snooze_condition=MetricAnomalyAlertSnoozeCondition(\n                auto_snooze=2,\n                snooze_scope=\"Metric\",\n                only_for_successive=True\n            )\n        ),\n    ],\n    hook_ids=[&lt;hook_id&gt;]\n)\n<\/code><\/pre>\n<h2>Query anomalies and alerts<\/h2>\n<p>After the configurations are set, Metrics Advisor service will keep running and monitoring anomalies for us. If we assign hooks when creating <code>AnomalyAlertConfiguration<\/code>, callbacks will be invoked when alerts pop up. Of course, we can use <code>MetricsAdvisorClient<\/code> to query anomalies and alerts as well.<\/p>\n<pre><code class=\"python\">import datetime\nfrom azure.ai.metricsadvisor import (\n    MetricsAdvisorKeyCredential,\n    MetricsAdvisorClient,\n)\nclient = MetricsAdvisorClient(&lt;service_endpoint&gt;,\n        MetricsAdvisorKeyCredential(&lt;subscription_key&gt;, &lt;api_key&gt;))\n\nresults = client.list_alerts_for_alert_configuration(\n    alert_configuration_id=&lt;alert_config_id&gt;,\n    start_time=datetime.datetime(2020, 1, 1),\n    end_time=datetime.datetime(2020, 9, 9),\n    time_mode=\"AnomalyTime\",\n)\nprint(\"Alerts\")\nfor result in results:\n    print(\"    Alert id: {}\".format(result.id))\n    print(\"    Created on: {}\".format(result.created_on))\n\nresults = client.list_anomalies_for_alert(\n    alert_configuration_id=&lt;alert_config_id&gt;,\n    alert_id=&lt;alert_id&gt;,\n)\nprint(\"Anomalies\")\nfor result in results:\n    print(\"    Detection configuration id: {}\".format(result.detection_configuration_id))\n    print(\"    Severity: {}\".format(result.severity))\n    print(\"    Status: {}\".format(result.status))\n<\/code><\/pre>\n<p>Output:<\/p>\n<pre><code class=\"console\">Alerts\n    Created on: 2020-09-12 01:15:16.406000+00:00\n    Alert id: 17465dcc000\n    Created on: 2020-09-12 01:14:17.184000+00:00\n    Alert id: 17460b66400\n\nAnomalies\n    Detection configuration id: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx\n    Severity: Low\n    Status: Active\n<\/code><\/pre>\n<p>You are all set! Azure Metrics Advisor service will monitor your timeseries and trigger alerts when something is wrong. Enjoy!<\/p>\n<h2>Further Documentation<\/h2>\n<ul>\n<li><a href=\"https:\/\/docs.microsoft.com\/azure\/cognitive-services\/metrics-advisor\/\">Metrics Advisor documentation<\/a><\/li>\n<li><a href=\"https:\/\/aka.ms\/azsdk\/python\/metricsadvisor\/docs\">Python Reference Documentation<\/a>, <a href=\"https:\/\/aka.ms\/azsdk\/python\/metricsadvisor\/readme\">Readme<\/a><\/li>\n<li><a href=\"https:\/\/aka.ms\/azsdk\/net\/metricsadvisor\/docs\">.NET Reference Documentation<\/a>, <a href=\"https:\/\/aka.ms\/azsdk\/net\/metricsadvisor\/readme\">Readme<\/a><\/li>\n<li><a href=\"https:\/\/aka.ms\/azsdk\/js\/metricsadvisor\/docs\">JavaScript\/TypeScript Reference Documentation<\/a>, <a href=\"https:\/\/aka.ms\/azsdk\/js\/metricsadvisor\/readme\">Readme<\/a><\/li>\n<li><a href=\"https:\/\/aka.ms\/azsdk\/java\/metricsadvisor\/docs\">Java Reference Documentation<\/a>, <a href=\"https:\/\/aka.ms\/azsdk\/java\/metricsadvisor\/readme\">Readme<\/a><\/li>\n<\/ul>\n<p><!-- FOOTER: DO NOT EDIT OR REMOVE --><\/p>\n<p><div  class=\"d-flex justify-content-center\"><a class=\"cta_button_link btn-primary mb-24\" href=\"https:\/\/aka.ms\/azsdk\/releases\" target=\"_blank\">Azure SDK Releases<\/a><\/div><\/p>\n<h2>Azure SDK Blog Contributions<\/h2>\n<p>Thank you for reading this Azure SDK blog post! We hope that you learned something new and welcome you to share this post. We are open to Azure SDK blog contributions. Please contact us at <a href=\"&#109;&#x61;&#105;&#x6c;&#116;&#x6f;&#58;&#x61;z&#115;&#x64;&#107;&#x62;&#108;&#x6f;&#103;&#x40;&#109;&#105;&#x63;&#114;&#x6f;&#115;&#x6f;&#102;&#x74;&#46;&#x63;o&#109;\">&#x61;z&#115;&#x64;&#107;&#x62;&#108;&#x6f;&#103;&#x40;&#109;&#105;&#x63;&#114;&#x6f;&#115;&#x6f;&#102;&#x74;&#46;&#x63;o&#109;<\/a> with your topic and we&#8217;ll get you setup as a guest blogger.<\/p>\n<h2>Azure SDK Links<\/h2>\n<ul>\n<li>Azure SDK Website: <a href=\"https:\/\/aka.ms\/azsdk\">aka.ms\/azsdk<\/a><\/li>\n<li>Azure SDK Intro (3 minute video): <a href=\"https:\/\/aka.ms\/azsdk\/intro\">aka.ms\/azsdk\/intro<\/a><\/li>\n<li>Azure SDK Intro Deck (PowerPoint deck): <a href=\"https:\/\/aka.ms\/azsdk\/intro\/deck\">aka.ms\/azsdk\/intro\/deck<\/a><\/li>\n<li>Azure SDK Releases: <a href=\"https:\/\/aka.ms\/azsdk\/releases\">aka.ms\/azsdk\/releases<\/a><\/li>\n<li>Azure SDK Blog: <a href=\"https:\/\/aka.ms\/azsdk\/blog\">aka.ms\/azsdk\/blog<\/a><\/li>\n<li>Azure SDK Twitter: <a href=\"https:\/\/twitter.com\/AzureSDK\">twitter.com\/AzureSDK<\/a><\/li>\n<li>Azure SDK Design Guidelines: <a href=\"https:\/\/aka.ms\/azsdk\/guide\">aka.ms\/azsdk\/guide<\/a><\/li>\n<li>Azure SDKs &amp; Tools: <a href=\"https:\/\/azure.microsoft.com\/downloads\">azure.microsoft.com\/downloads<\/a><\/li>\n<li>Azure SDK Central Repository: <a href=\"https:\/\/github.com\/azure\/azure-sdk#azure-sdk\">github.com\/azure\/azure-sdk<\/a><\/li>\n<li>Azure SDK for .NET: <a href=\"https:\/\/github.com\/azure\/azure-sdk-for-net\">github.com\/azure\/azure-sdk-for-net<\/a><\/li>\n<li>Azure SDK for Java: <a href=\"https:\/\/github.com\/azure\/azure-sdk-for-java\">github.com\/azure\/azure-sdk-for-java<\/a><\/li>\n<li>Azure SDK for Python: <a href=\"https:\/\/github.com\/azure\/azure-sdk-for-python\">github.com\/azure\/azure-sdk-for-python<\/a><\/li>\n<li>Azure SDK for JavaScript\/TypeScript: <a href=\"https:\/\/github.com\/azure\/azure-sdk-for-js\">github.com\/azure\/azure-sdk-for-js<\/a><\/li>\n<li>Azure SDK for Android: <a href=\"https:\/\/github.com\/Azure\/azure-sdk-for-android\">github.com\/Azure\/azure-sdk-for-android<\/a><\/li>\n<li>Azure SDK for iOS: <a href=\"https:\/\/github.com\/Azure\/azure-sdk-for-ios\">github.com\/Azure\/azure-sdk-for-ios<\/a><\/li>\n<li>Azure SDK for Go: <a href=\"https:\/\/github.com\/Azure\/azure-sdk-for-go\">github.com\/Azure\/azure-sdk-for-go<\/a><\/li>\n<li>Azure SDK for C: <a href=\"https:\/\/github.com\/Azure\/azure-sdk-for-c\">github.com\/Azure\/azure-sdk-for-c<\/a><\/li>\n<li>Azure SDK for C++: <a href=\"https:\/\/github.com\/Azure\/azure-sdk-for-cpp\">github.com\/Azure\/azure-sdk-for-cpp<\/a><\/li>\n<\/ul>\n<p><!-- FOOTER: DO NOT EDIT OR REMOVE --><\/p>\n<p><!-- LINKS --><\/p>\n","protected":false},"excerpt":{"rendered":"<p>The new Metrics Advisor service allows you to easily detect anomalies in your data. This blog will show you how to set the service up and use it in your application.<\/p>\n","protected":false},"author":41895,"featured_media":714,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[1],"tags":[734,750,767,766,162],"class_list":["post-700","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-azure-sdk","tag-azure","tag-azure-sdk","tag-cognitive","tag-metricsadvisor","tag-python"],"acf":[],"blog_post_summary":"<p>The new Metrics Advisor service allows you to easily detect anomalies in your data. This blog will show you how to set the service up and use it in your application.<\/p>\n","_links":{"self":[{"href":"https:\/\/devblogs.microsoft.com\/azure-sdk\/wp-json\/wp\/v2\/posts\/700","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/devblogs.microsoft.com\/azure-sdk\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/devblogs.microsoft.com\/azure-sdk\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/azure-sdk\/wp-json\/wp\/v2\/users\/41895"}],"replies":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/azure-sdk\/wp-json\/wp\/v2\/comments?post=700"}],"version-history":[{"count":0,"href":"https:\/\/devblogs.microsoft.com\/azure-sdk\/wp-json\/wp\/v2\/posts\/700\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/azure-sdk\/wp-json\/wp\/v2\/media\/714"}],"wp:attachment":[{"href":"https:\/\/devblogs.microsoft.com\/azure-sdk\/wp-json\/wp\/v2\/media?parent=700"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/azure-sdk\/wp-json\/wp\/v2\/categories?post=700"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/azure-sdk\/wp-json\/wp\/v2\/tags?post=700"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}