快速入門:使用 Anomaly Detector REST API 與 Java 偵測時間序列資料中的異常狀況Quickstart: Detect anomalies in your time series data using the Anomaly Detector REST API and Java

使用本快速入門以開始使用 Anomaly Detector API 的兩個偵測模式,來偵測時間序列資料中的異常狀況。Use this quickstart to start using the Anomaly Detector API's two detection modes to detect anomalies in your time series data. 此 Java 應用程式會傳送包含 JSON 格式時間序列資料的兩個 API 要求,並取得回應。This Java application sends two API requests containing JSON-formatted time series data, and gets the responses.

API 要求API request 應用程式輸出Application output
以批次方式偵測異常狀況Detect anomalies as a batch JSON 回應包含時間序列資料中每個資料點的異常狀態 (和其他資料),以及偵測到的任何異常狀況的位置。The JSON response containing the anomaly status (and other data) for each data point in the time series data, and the positions of any detected anomalies.
偵測最新資料點的異常狀態Detect the anomaly status of the latest data point JSON 回應包含時間序列資料中最新資料點的異常狀態 (和其他資料)。The JSON response containing the anomaly status (and other data) for the latest data point in the time series data.

雖然此應用程式是以 Java 撰寫的,但 API 是一種與大多數程式設計語言都相容的 RESTful Web 服務。While this application is written in Java, the API is a RESTful web service compatible with most programming languages.

必要條件Prerequisites

注意

使用異常偵測器 API 時若要取得最佳結果,您的 JSON 格式時間序列資料應該包含:For best results when using the Anomaly Detector API, your JSON-formatted time series data should include:

  • 依據相同間隔分隔的資料點,遺漏的點數目不超過預期的 10%。data points separated by the same interval, with no more than 10% of the expected number of points missing.
  • 如果您的資料沒有清楚的季節模式,則至少有 12 個資料點。at least 12 data points if your data doesn't have a clear seasonal pattern.
  • 如果您的資料有清楚的季節模式,則至少會發生 4 個模式。at least 4 pattern occurrences if your data does have a clear seasonal pattern.

您必須有具備 Anomaly Detector API 存取權的認知服務 API 帳戶You must have a Cognitive Services API account with access to the Anomaly Detector API. 您可以在建立帳戶後從 Azure 入口網站取得訂用帳戶金鑰。You can get your subscription key from the Azure portal after creating your account.

建立新的應用程式Create a new application

  1. 在您最愛的 IDE 或編輯器中建立新的 Java 專案,並匯入下列程式庫。Create a new Java project in your favorite IDE or editor, and import the following libraries.

    import org.apache.http.HttpEntity;
    import org.apache.http.client.methods.CloseableHttpResponse;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.entity.StringEntity;
    import org.apache.http.impl.client.CloseableHttpClient;
    import org.apache.http.impl.client.HttpClients;
    import org.apache.http.util.EntityUtils;
    import org.json.JSONArray;
    import org.json.JSONObject;
    import java.io.IOException;
    import java.nio.file.Files;
    import java.nio.file.Paths;
    
  2. 針對您的訂用帳戶金鑰和端點建立變數。Create variables for your subscription key and your endpoint. 以下是您可以用於異常偵測的 URI。Below are the URIs you can use for anomaly detection. 這些稍後將會附加至您的服務端點,以建立 API 要求 URL。These will be appended to your service endpoint later to create the API request URLs.

    偵測方法Detection method URIURI
    批次偵測Batch detection /anomalydetector/v1.0/timeseries/entire/detect
    最新資料點上的偵測Detection on the latest data point /anomalydetector/v1.0/timeseries/last/detect
    // Replace the subscriptionKey string value with your valid subscription key.
    static final String subscriptionKey = "[YOUR_SUBSCRIPTION_KEY]";
    //replace the endpoint URL with the correct one for your subscription. Your endpoint can be found in the Azure portal. 
    //For example: https://westus2.api.cognitive.microsoft.com
    static final String endpoint = "[YOUR_ENDPOINT_URL]";
    // Replace the dataPath string with a path to the JSON formatted time series data.
    static final String dataPath = "[PATH_TO_TIME_SERIES_DATA]";
    static final String latestPointDetectionUrl = "/anomalydetector/v1.0/timeseries/last/detect";
    static final String batchDetectionUrl = "/anomalydetector/v1.0/timeseries/entire/detect";
    
  3. 讀入 JSON 資料檔案Read in the JSON data file

    String requestData = new String(Files.readAllBytes(Paths.get(dataPath)), "utf-8");
    

建立傳送要求的函式Create a function to send requests

  1. 建立名為 sendRequest() 的新函式,取用上面建立的變數。Create a new function called sendRequest() that takes the variables created above. 然後執行下列步驟。Then perform the following steps.

  2. 建立可將要求傳送至 API 的 CloseableHttpClient 物件。Create a CloseableHttpClient object that can send requests to the API. 藉由結合您的端點和 Anomaly Detector URL,將要求傳送至 HttpPost 要求物件。Send the request to an HttpPost request object by combining your endpoint, and an Anomaly Detector URL.

  3. 使用要求的 setHeader() 函式,將 Content-Type 標頭設定為 application/json,並將您的訂用帳戶金鑰新增至 Ocp-Apim-Subscription-Key 標頭。Use the request's setHeader() function to set the Content-Type header to application/json, and add your subscription key to the Ocp-Apim-Subscription-Key header.

  4. 將要求的 setEntity() 函式用於要傳送的資料。Use the request's setEntity() function to the data to be sent.

  5. 使用用戶端的 execute() 函式傳送要求,並將它儲存到 CloseableHttpResponse 物件。Use the client's execute() function to send the request, and save it to a CloseableHttpResponse object.

  6. 建立 HttpEntity 物件以儲存回應內容。Create an HttpEntity object to store the response content. 使用 getEntity() 取得內容。Get the content with getEntity(). 如果回應不是空的,請將它傳回。If the response isn't empty, return it.

static String sendRequest(String apiAddress, String endpoint, String subscriptionKey, String requestData) {
    try (CloseableHttpClient client = HttpClients.createDefault()) {
        HttpPost request = new HttpPost(endpoint + apiAddress);
        // Request headers.
        request.setHeader("Content-Type", "application/json");
        request.setHeader("Ocp-Apim-Subscription-Key", subscriptionKey);
        request.setEntity(new StringEntity(requestData));
        try (CloseableHttpResponse response = client.execute(request)) {
            HttpEntity respEntity = response.getEntity();
            if (respEntity != null) {
                return EntityUtils.toString(respEntity, "utf-8");
            }
        } catch (Exception respEx) {
            respEx.printStackTrace();
        }
    } catch (IOException ex) {
        System.err.println("Exception on Anomaly Detector: " + ex.getMessage());
        ex.printStackTrace();
    }
    return null;
}

以批次方式偵測異常狀況Detect anomalies as a batch

  1. 建立名為 detectAnomaliesBatch() 的方法,以批次方式偵測整個資料的異常狀況。Create a method called detectAnomaliesBatch() to detect anomalies throughout the data as a batch. 使用端點、URL、訂用帳戶金鑰和 json 資料呼叫上方建立的 sendRequest() 方法。Call the sendRequest() method created above with your endpoint, url, subscription key, and json data. 取得結果,並將它列印到主控台。Get the result, and print it to the console.

  2. 如果回應包含 code 欄位,則列印錯誤碼和錯誤訊息。If the response contains code field, print the error code and error message.

  3. 否則,在資料集中尋找異常狀況的位置。Otherwise, find the positions of anomalies in the data set. 回應的 isAnomaly 欄位包含與指定的資料點是否為異常相關的布林值。The response's isAnomaly field contains a boolean value relating to whether a given data point is an anomaly. 取得 JSON 陣列並逐一查看,然後列印任何 true 值的索引。Get the JSON array, and iterate through it, printing the index of any true values. 如果有找到,這些值會對應到異常資料點的索引。These values correspond to the index of anomalous data points, if any were found.

static void detectAnomaliesBatch(String requestData) {
    System.out.println("Detecting anomalies as a batch");
    String result = sendRequest(batchDetectionUrl, endpoint, subscriptionKey, requestData);
    if (result != null) {
        System.out.println(result);
        JSONObject jsonObj = new JSONObject(result);
        if (jsonObj.has("code")) {
            System.out.println(String.format("Detection failed. ErrorCode:%s, ErrorMessage:%s", jsonObj.getString("code"), jsonObj.getString("message")));
        } else {
            JSONArray jsonArray = jsonObj.getJSONArray("isAnomaly");
            System.out.println("Anomalies found in the following data positions:");
            for (int i = 0; i < jsonArray.length(); ++i) {
                if (jsonArray.getBoolean(i))
                    System.out.print(i + ", ");
            }
            System.out.println();
        }
    }
}

偵測最新資料點的異常狀態Detect the anomaly status of the latest data point

  • 建立名為 detectAnomaliesLatest() 的方法,以偵測資料集中最後一個資料點的異常狀態。Create a method called detectAnomaliesLatest() to detect the anomaly status of the last data point in the data set. 使用端點、URL、訂用帳戶金鑰和 json 資料呼叫上方建立的 sendRequest() 方法。Call the sendRequest() method created above with your endpoint, url, subscription key, and json data. 取得結果,並將它列印到主控台。Get the result, and print it to the console.
static void detectAnomaliesLatest(String requestData) {
    System.out.println("Determining if latest data point is an anomaly");
    String result = sendRequest(latestPointDetectionUrl, endpoint, subscriptionKey, requestData);
    System.out.println(result);
}

載入時間序列資料,並傳送要求Load your time series data and send the request

  1. 在您應用程式的主要方法中,讀入 JSON 檔案,其中包含將新增至要求的資料。In the main method of your application, read in the JSON file containing the data that will be added to the requests.

  2. 呼叫上面建立的兩個異常偵測函式。Call the two anomaly detection functions created above.

public static void main(String[] args) throws Exception {
    String requestData = new String(Files.readAllBytes(Paths.get(dataPath)), "utf-8");
    detectAnomaliesBatch(requestData);
    detectAnomaliesLatest(requestData);
}

範例回應Example response

成功的回應會以 JSON 格式傳回。A successful response is returned in JSON format. 按一下以下連結,在 GitHub 上檢視 JSON 回應:Click the links below to view the JSON response on GitHub:

後續步驟Next steps