Quickstart: Anomaly Detector client library for .NET

Get started with the Anomaly Detector client library for .NET. Follow these steps to install the package and try out the example code for basic tasks. The Anomaly Detector service enables you to find abnormalities in your time series data by automatically using the best-fitting models on it, regardless of industry, scenario, or data volume.

Use the Anomaly Detector client library for .NET to:

  • Detect anomalies throughout your time series dataset, as a batch request
  • Detect the anomaly status of the latest data point in your time series

Library reference documentation | Library source code | Package (NuGet) | Find the code on GitHub

Prerequisites

Setting up

Create an Anomaly Detector resource

Start using the Anomaly Detector service by creating one of the Azure resources below.

Create an environment variable

Note

The endpoints for non-trial resources created after July 1, 2019 use the custom subdomain format shown below. For more information and a complete list of regional endpoints, see Custom subdomain names for Cognitive Services.

Using your key and endpoint from the resource you created, create two environment variables for authentication:

  • ANOMALY_DETECTOR_KEY - The resource key for authenticating your requests.
  • ANOMALY_DETECTOR_ENDPOINT - The resource endpoint for sending API requests. It will look like this:
    • https://<your-custom-subdomain>.api.cognitive.microsoft.com

Use the instructions for your operating system.

setx ANOMALY_DETECTOR_KEY <replace-with-your-anomaly-detector-key>
setx ANOMALY_DETECTOR_ENDPOINT <replace-with-your-anomaly-detector-endpoint>

After you add the environment variable, restart the console window.

Create a new .NET Core application

In a console window (such as cmd, PowerShell, or Bash), use the dotnet new command to create a new console app with the name anomaly-detector-quickstart. This command creates a simple "Hello World" project with a single C# source file: Program.cs.

dotnet new console -n anomaly-detector-quickstart

Change your directory to the newly created app folder. You can build the application with:

dotnet build

The build output should contain no warnings or errors.

...
Build succeeded.
 0 Warning(s)
 0 Error(s)
...

Install the client library

Within the application directory, install the Anomaly Detector client library for .NET with the following command:

dotnet add package Microsoft.Azure.CognitiveServices.AnomalyDetector --version 0.8.0-preview

From the project directory, open the program.cs file and add the following using directives:

using System;
using System.IO;
using System.Text;
using System.Linq;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.Azure.CognitiveServices.AnomalyDetector;
using Microsoft.Azure.CognitiveServices.AnomalyDetector.Models;

In the application's main() method, create variables for your resource's Azure location, and your key as an environment variable. If you created the environment variable after application is launched, the editor, IDE, or shell running it will need to be closed and reloaded to access the variable.

static void Main(string[] args){
    //This sample assumes you have created an environment variable for your key and endpoint
    string endpoint = Environment.GetEnvironmentVariable("ANOMALY_DETECTOR_ENDPOINT");
    string key = Environment.GetEnvironmentVariable("ANOMALY_DETECTOR_KEY");
    string datapath = "request-data.csv";

    IAnomalyDetectorClient client = createClient(endpoint, key); //Anomaly Detector client

    Request request = GetSeriesFromFile(datapath); // The request payload with points from the data file

    EntireDetectSampleAsync(client, request).Wait(); // Async method for batch anomaly detection
    LastDetectSampleAsync(client, request).Wait(); // Async method for analyzing the latest data point in the set

    Console.WriteLine("\nPress ENTER to exit.");
    Console.ReadLine();
}

Object model

The Anomaly Detector client is a AnomalyDetectorClient object that authenticates to Azure using ApiKeyServiceClientCredentials, which contains your key. The client provides two methods of anomaly detection: On an entire dataset using EntireDetectAsync(), and on the latest data point using LastDetectAsync().

Time series data is sent as a series of Points in a Request object. The Request object contains properties to describe the data (Granularity for example), and parameters for the anomaly detection.

The Anomaly Detector response is either an EntireDetectResponse or LastDetectResponse object, depending on the method used.

Code examples

These code snippets show you how to do the following with the Anomaly Detector client library for .NET:

Authenticate the client

In a new method, instantiate a client with your endpoint and key. Create an ApiKeyServiceClientCredentials object with your key, and use it with your endpoint to create an AnomalyDetectorClient object.

static IAnomalyDetectorClient createClient(string endpoint, string key)
{
    IAnomalyDetectorClient client = new AnomalyDetectorClient(new ApiKeyServiceClientCredentials(key))
    {
        Endpoint = endpoint
    };
    return client;
}

Load time series data from a file

Download the example data for this quickstart from GitHub:

  1. In your browser, right-click Raw.
  2. Click Save link as.
  3. Save the file to your application directory, as a .csv file.

This time series data is formatted as a .csv file, and will be sent to the Anomaly Detector API.

Create a new method to read in the time series data and add it to a Request object. Call File.ReadAllLines() with the file path and create a list of Point objects, and strip any new line characters. Extract the values and separate the datestamp from its numerical value, and add them to a new Point object.

Make a Request object with the series of points, and Granularity.Daily for the Granularity (or periodicity) of the data points.

static Request GetSeriesFromFile(string path)
{
    List<Point> list = File.ReadAllLines(path, Encoding.UTF8)
        .Where(e => e.Trim().Length != 0)
        .Select(e => e.Split(','))
        .Where(e => e.Length == 2)
        .Select(e => new Point(DateTime.Parse(e[0]), Double.Parse(e[1]))).ToList();
    
    return new Request(list, Granularity.Daily); 
}

Detect anomalies in the entire data set

Create a method to call the client's EntireDetectAsync() method with the Request object and await the response as an EntireDetectResponse object. If the time series contains any anomalies, iterate through the response's IsAnomaly values and print any that are true. These values correspond to the index of anomalous data points, if any were found.

static async Task EntireDetectSampleAsync(IAnomalyDetectorClient client, Request request)
{
    Console.WriteLine("Detecting anomalies in the entire time series.");

    EntireDetectResponse result = await client.EntireDetectAsync(request).ConfigureAwait(false);

    if (result.IsAnomaly.Contains(true))
    {
        Console.WriteLine("An anomaly was detected at index:");
        for (int i = 0; i < request.Series.Count; ++i)
        {
            if (result.IsAnomaly[i])
            {
                Console.Write(i);
                Console.Write(" ");
            }
        }
        Console.WriteLine();
    }
    else
    {
        Console.WriteLine(" No anomalies detected in the series.");
    }
}

Detect the anomaly status of the latest data point

Create a method to call the client's LastDetectAsync() method with the Request object and await the response as a LastDetectResponse object. Check the response's IsAnomaly attribute to determine if the latest data point sent was an anomaly or not.

static async Task LastDetectSampleAsync(IAnomalyDetectorClient client, Request request)
{

    Console.WriteLine("Detecting the anomaly status of the latest point in the series.");
    LastDetectResponse result = await client.LastDetectAsync(request).ConfigureAwait(false);

    if (result.IsAnomaly)
    {
        Console.WriteLine("The latest point was detected as an anomaly.");
    }
    else
    {
        Console.WriteLine("The latest point was not detected as an anomaly.");
    }
}

Run the application

Run the application with the dotnet run command from your application directory.

dotnet run

Clean up resources

If you want to clean up and remove a Cognitive Services subscription, you can delete the resource or resource group. Deleting the resource group also deletes any other resources associated with the resource group.

Next steps

Concepts:

Tutorials: