Skip to content

Instantly share code, notes, and snippets.

@csiebler
Last active April 1, 2019 14:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save csiebler/6fb7d98f924fec94c8ee0c5511e20220 to your computer and use it in GitHub Desktop.
Save csiebler/6fb7d98f924fec94c8ee0c5511e20220 to your computer and use it in GitHub Desktop.
Anomaly Detection Python Example
import requests
import json
import pandas as pd
import matplotlib.pyplot as plt
subscription_key = "xxxxxxx"
endpoint = "https://westeurope.api.cognitive.microsoft.com"
batch_detection_url = "/anomalydetector/v1.0/timeseries/entire/detect"
latest_point_detection_url = "/anomalydetector/v1.0/timeseries/last/detect"
source_data = requests.get("https://raw.githubusercontent.com/Azure-Samples/anomalydetector/master/example-data/request-data.json").json()
headers = {'Content-Type': 'application/json',
'Ocp-Apim-Subscription-Key': subscription_key}
response = requests.post(endpoint + batch_detection_url, data=json.dumps(source_data), headers=headers)
response = json.loads(response.content.decode("utf-8"))
# Aggregate inputs and results
df_reponse = pd.DataFrame.from_dict(response)
df_source = pd.DataFrame(source_data['series'])
df = pd.concat([df_source, df_reponse], axis=1)
# Display results
plt.figure(1, figsize=(20, 8))
plt.plot(df.timestamp, df.value, color='black', label='Actual Values')
plt.plot(df.timestamp, df.expectedValues, linestyle='dashed', color='blue', label='Expected Values')
plt.fill_between(df.timestamp, df.expectedValues - df.lowerMargins, df.expectedValues + df.upperMargins,
color='blue', alpha=0.1)
anomalies = df[(df.isAnomaly == True)]
plt.scatter(anomalies.timestamp, anomalies.value, c='r', alpha=0.5, label='Anomalies')
plt.xlabel('Time')
plt.xticks(df.timestamp, rotation='vertical')
plt.ylabel('Values')
plt.legend()
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment