def last_detect_sample(endpoint, key, request):
    print('Sample of detecting whether the latest point in series is anomaly.')

    client = AnomalyDetectorClient(endpoint, CognitiveServicesCredentials(key))
    response = client.last_detect(request)
    if response.is_anomaly:
        print('The latest point is detected as anomaly.')
    else:
        print('The latest point is not detected as anomaly.')
def entire_detect_sample(endpoint, key, request):
    print('Sample of detecting anomalies in the entire series.')

    client = AnomalyDetectorClient(endpoint, CognitiveServicesCredentials(key))
    response = client.entire_detect(request)
    if True in response.is_anomaly:
        print('Anomaly was detected from the series at index:')
        for i in range(len(series)):
            if response.is_anomaly[i]:
                print(i)
    else:
        print('There is no anomaly detected from the series.')
def entire_dectect_sample(endpoint, key):
    print('Sample of detecting anomalies in the entire series.')

    client = AnomalyDetectorClient(endpoint, CognitiveServicesCredentials(key))

    series = [
        Point(timestamp=datetime(1962, 1, 1, tzinfo=timezone.utc), value=1),
        Point(timestamp=datetime(1962, 2, 1, tzinfo=timezone.utc), value=1),
        Point(timestamp=datetime(1962, 3, 1, tzinfo=timezone.utc), value=0),
        Point(timestamp=datetime(1962, 4, 1, tzinfo=timezone.utc), value=1),
        Point(timestamp=datetime(1962, 5, 1, tzinfo=timezone.utc), value=1),
        Point(timestamp=datetime(1962, 6, 1, tzinfo=timezone.utc), value=1),
        Point(timestamp=datetime(1962, 7, 1, tzinfo=timezone.utc), value=1),
        Point(timestamp=datetime(1962, 8, 1, tzinfo=timezone.utc), value=1),
        Point(timestamp=datetime(1962, 9, 1, tzinfo=timezone.utc), value=1),
        Point(timestamp=datetime(1962, 10, 1, tzinfo=timezone.utc), value=1),
        Point(timestamp=datetime(1962, 11, 1, tzinfo=timezone.utc), value=1),
        Point(timestamp=datetime(1962, 12, 1, tzinfo=timezone.utc), value=1),
        Point(timestamp=datetime(1963, 1, 1, tzinfo=timezone.utc), value=1),
        Point(timestamp=datetime(1963, 2, 1, tzinfo=timezone.utc), value=1),
        Point(timestamp=datetime(1963, 3, 1, tzinfo=timezone.utc), value=1),
        Point(timestamp=datetime(1963, 4, 1, tzinfo=timezone.utc), value=0),
        Point(timestamp=datetime(1963, 5, 1, tzinfo=timezone.utc), value=1),
        Point(timestamp=datetime(1963, 6, 1, tzinfo=timezone.utc), value=1),
        Point(timestamp=datetime(1963, 7, 1, tzinfo=timezone.utc), value=1),
        Point(timestamp=datetime(1963, 8, 1, tzinfo=timezone.utc), value=1),
        Point(timestamp=datetime(1963, 9, 1, tzinfo=timezone.utc), value=1),
        Point(timestamp=datetime(1963, 10, 1, tzinfo=timezone.utc), value=1),
        Point(timestamp=datetime(1963, 11, 1, tzinfo=timezone.utc), value=1),
        Point(timestamp=datetime(1963, 12, 1, tzinfo=timezone.utc), value=1),
    ]

    data = Request(series=series,
                   granularity=Granularity.monthly,
                   sensitivity=95,
                   max_anomaly_ratio=0.25)
    response = client.entire_detect(data)
    if True in response.is_anomaly:
        print('Anomaly was detected from the series at index:')
        for i in range(len(series)):
            if response.is_anomaly[i]:
                print(i)
    else:
        print('There is no anomaly detected from the series.')
Esempio n. 4
0
def last_detect(subscription_key):
    print("Sample of detecting whether the latest point in series is anomaly.")
    # Add your Azure Anomaly Detector subscription key to your environment variables.
    endpoint = os.environ.get["ANOMALY_DETECTOR_ENDPOINT"]
    
    try:
        client = AnomalyDetectorClient(
            endpoint, CognitiveServicesCredentials(subscription_key))
        request = get_request()
        response = client.last_detect(request)
        if response.is_anomaly:
            print("The latest point is detected as anomaly.")
        else:
            print("The latest point is not detected as anomaly.")
    except Exception as e:
        if isinstance(e, APIErrorException):
            print("Error code: {}".format(e.error.code))
            print("Error message: {}".format(e.error.message))
        else:
            print(e)
def last_detect(subscription_key):
    print("Sample of detecting whether the latest point in series is anomaly.")

    endpoint = "https://{}.api.cognitive.microsoft.com".format(
        ANOMALYDETECTOR_LOCATION)
    try:
        client = AnomalyDetectorClient(
            endpoint, CognitiveServicesCredentials(subscription_key))
        request = get_request()
        response = client.last_detect(request)
        if response.is_anomaly:
            print("The latest point is detected as anomaly.")
        else:
            print("The latest point is not detected as anomaly.")
    except Exception as e:
        if isinstance(e, APIErrorException):
            print("Error code: {}".format(e.error.code))
            print("Error message: {}".format(e.error.message))
        else:
            print(e)
def last_detect_sample(endpoint, key):
    print('Sample of detecting whether the latest point in series is anomaly.')

    client = AnomalyDetectorClient(endpoint, CognitiveServicesCredentials(key))

    series = [
        Point(timestamp=datetime(1962, 1, 1, tzinfo=timezone.utc), value=1),
        Point(timestamp=datetime(1962, 2, 1, tzinfo=timezone.utc), value=1),
        Point(timestamp=datetime(1962, 3, 1, tzinfo=timezone.utc), value=1),
        Point(timestamp=datetime(1962, 4, 1, tzinfo=timezone.utc), value=1),
        Point(timestamp=datetime(1962, 5, 1, tzinfo=timezone.utc), value=1),
        Point(timestamp=datetime(1962, 6, 1, tzinfo=timezone.utc), value=1),
        Point(timestamp=datetime(1962, 7, 1, tzinfo=timezone.utc), value=1),
        Point(timestamp=datetime(1962, 8, 1, tzinfo=timezone.utc), value=1),
        Point(timestamp=datetime(1962, 9, 1, tzinfo=timezone.utc), value=1),
        Point(timestamp=datetime(1962, 10, 1, tzinfo=timezone.utc), value=1),
        Point(timestamp=datetime(1962, 11, 1, tzinfo=timezone.utc), value=1),
        Point(timestamp=datetime(1962, 12, 1, tzinfo=timezone.utc), value=1),
        Point(timestamp=datetime(1963, 1, 1, tzinfo=timezone.utc), value=1),
        Point(timestamp=datetime(1963, 2, 1, tzinfo=timezone.utc), value=1),
        Point(timestamp=datetime(1963, 3, 1, tzinfo=timezone.utc), value=1),
        Point(timestamp=datetime(1963, 4, 1, tzinfo=timezone.utc), value=1),
        Point(timestamp=datetime(1963, 5, 1, tzinfo=timezone.utc), value=1),
        Point(timestamp=datetime(1963, 6, 1, tzinfo=timezone.utc), value=1),
        Point(timestamp=datetime(1963, 7, 1, tzinfo=timezone.utc), value=1),
        Point(timestamp=datetime(1963, 8, 1, tzinfo=timezone.utc), value=1),
        Point(timestamp=datetime(1963, 9, 1, tzinfo=timezone.utc), value=1),
        Point(timestamp=datetime(1963, 10, 1, tzinfo=timezone.utc), value=1),
        Point(timestamp=datetime(1963, 11, 1, tzinfo=timezone.utc), value=1),
        Point(timestamp=datetime(1963, 12, 1, tzinfo=timezone.utc), value=0),
    ]

    data = Request(series=series,
                   granularity=Granularity.monthly,
                   sensitivity=95,
                   max_anomaly_ratio=0.25)
    response = client.last_detect(data)
    if response.is_anomaly:
        print('The latest point is detected as anomaly.')
    else:
        print('The latest point is not detected as anomaly.')
Esempio n. 7
0
def entire_detect(subscription_key):
    print("Sample of detecting anomalies in the entire series.")
    # Add your Azure Anomaly Detector subscription key to your environment variables.
    endpoint = os.environ.get["ANOMALY_DETECTOR_ENDPOINT"]
    
    try:
        client = AnomalyDetectorClient(
            endpoint, CognitiveServicesCredentials(subscription_key))
        request = get_request()
        response = client.entire_detect(request)
        if True in response.is_anomaly:
            print("Anomaly was detected from the series at index:")
            for i in range(len(request.series)):
                if response.is_anomaly[i]:
                    print(i)
        else:
            print("There is no anomaly detected from the series.")
    except Exception as e:
        if isinstance(e, APIErrorException):
            print("Error code: {}".format(e.error.code))
            print("Error message: {}".format(e.error.message))
        else:
            print(e)
def entire_detect(subscription_key):
    print("Sample of detecting anomalies in the entire series.")

    endpoint = "https://{}.api.cognitive.microsoft.com".format(
        ANOMALYDETECTOR_LOCATION)
    try:
        client = AnomalyDetectorClient(
            endpoint, CognitiveServicesCredentials(subscription_key))
        request = get_request()
        response = client.entire_detect(request)
        if True in response.is_anomaly:
            print("Anomaly was detected from the series at index:")
            for i in range(len(request.series)):
                if response.is_anomaly[i]:
                    print(i)
        else:
            print("There is no anomaly detected from the series.")
    except Exception as e:
        if isinstance(e, APIErrorException):
            print("Error code: {}".format(e.error.code))
            print("Error message: {}".format(e.error.message))
        else:
            print(e)
import os
# </imports>

# <initVars>
# Set the COGSRV_ACCOUNT_KEY environment variable on your local machine using the
# appropriate method for your preferred shell (Bash, PowerShell, Command Prompt, etc.)
SUBSCRIPTION_KEY = os.environ["COGSRV_ACCOUNT_KEY"]
ANOMALY_DETECTION_LOCATION = "westus2"
TIME_SERIES_DATA_PATH = ""
# </initVars>

# Create an Anomaly Detector client and add the 

# <client>
base_url = "https://{}.api.cognitive.microsoft.com".format(ANOMALY_DETECTION_LOCATION)
client = AnomalyDetectorClient(base_url, CognitiveServicesCredentials(SUBSCRIPTION_KEY))
# </client>

# Load in the time series data file

# <loadDataFile>
series = []
data_file = pd.read_csv(TIME_SERIES_DATA_PATH, header=None, encoding='utf-8', parse_dates=[0])
for index, row in data_file.iterrows():
    series.append(Point(timestamp=row[0], value=row[1]))
# </loadDataFile>

# Create a request from the data file 

# <request>
request = Request(series=series, granularity=Granularity.daily)
Esempio n. 10
0
import pandas as pd
import os
# </imports>

# <initVars>
# This sample assumes you have created an environment variable for your key and endpoint
SUBSCRIPTION_KEY = os.environ["ANOMALY_DETECTOR_KEY"]
ANOMALY_DETECTOR_ENDPOINT = os.environ["ANOMALY_DETECTOR_ENDPOINT"]

TIME_SERIES_DATA_PATH = "request-data.csv"
# </initVars>

# Create an Anomaly Detector client and add the 

# <client>
client = AnomalyDetectorClient(ANOMALY_DETECTOR_ENDPOINT, CognitiveServicesCredentials(SUBSCRIPTION_KEY))
# </client>

# Load in the time series data file

# <loadDataFile>
series = []
data_file = pd.read_csv(TIME_SERIES_DATA_PATH, header=None, encoding='utf-8', parse_dates=[0])
for index, row in data_file.iterrows():
    series.append(Point(timestamp=row[0], value=row[1]))
# </loadDataFile>

# Create a request from the data file 

# <request>
request = Request(series=series, granularity=Granularity.daily)
Esempio n. 11
0
    def get_client_lazy(self):
        from azure.cognitiveservices.anomalydetector import AnomalyDetectorClient
        from msrest.authentication import CognitiveServicesCredentials

        return AnomalyDetectorClient(
            self.url, CognitiveServicesCredentials(self.get_secret()))
def detect_anomalies(X,
                     index,
                     interval,
                     overlap_size,
                     subscription_key,
                     endpoint,
                     granularity,
                     custom_interval=None,
                     period=None,
                     max_anomaly_ratio=None,
                     sensitivity=None,
                     timezone="UTC"):
    """Microsoft's Azure Anomaly Detection tool.

    Args:
        X (list):
            Array containing the input value sequences.
        index (list):
            Array containing the input index sequences.
        interval (int):
            Integer denoting time span frequency of the data.
        overlap_size (int):
            Length of the values from previous sequence that overlaps with current sequnce.
        subscription_key (str):
            Resource key for authenticating your requests.
        endpoint (str):
            Resource endpoint for sending API requests.
        granularity (str or Granularity):
            Can only be one of yearly, monthly, weekly, daily, hourly or minutely.
            Granularity is used for verify whether input series is valid. Possible values
            include: 'yearly', 'monthly', 'weekly', 'daily', 'hourly', 'minutely'.
        custom_interval (int):
            Integer used to set non-standard time interval, for example, if the series
            is 5 minutes, request can be set as `{"granularity":"minutely", "custom_interval":5}`.
            If not given, `None` is used.
        period (int):
            Periodic value of a time series. If not given, `None` is used, and the API
            will determine the period automatically.
        max_anomaly_ratio (float):
            Advanced model parameter, max anomaly ratio in a time series. If not given,
            `None` is used.
        sensitivity (int):
            Advanced model parameter, between 0-99, the lower the value is, the larger
            the margin value will be which means less anomalies will be accepted. If not given,
            `None` is used.
        timezone (str):
            String indicating the timezone of the timestamps. If not given, will use UTC as
            default. The format of the string should be complaint with ``pytz``
            which can be found in http://pytz.sourceforge.net/.

        Returns:
            list:
                Array containing start-index, end-index, score for each anomalous sequence.
                Note that the API does not have an anomaly score, and so score is set to `None`.
    """
    client = AnomalyDetectorClient(
        endpoint, CognitiveServicesCredentials(subscription_key))

    tz = pytz.timezone(timezone)
    overlap = 0
    result = list()

    for x, idx in zip(X, index):
        series = []
        for i in range(len(x)):
            idx_ = _convert_date(idx[i], tz)
            series.append(Point(timestamp=idx_, value=x[i]))

        request = Request(series=series,
                          granularity=granularity,
                          custom_interval=custom_interval,
                          period=period,
                          max_anomaly_ratio=max_anomaly_ratio,
                          sensitivity=sensitivity)

        response = client.entire_detect(request)
        if response.is_anomaly:
            anomalous = response.is_anomaly[overlap:]
            index_ = idx[overlap:]
            result.extend(index_[anomalous])

        overlap = overlap_size

    return _convert_anomalies_to_contextual(result, interval)