使用多變數時間序列預測模型執行異常偵測

本教學課程說明如何執行下列工作:

本教學課程使用公開 epa_historical_air_quality 資料集中的下列資料表,其中包含從多個美國城市收集的每日 PM 2.5、溫度和風速資訊:

所需權限

  • 如要建立資料集,您必須具備 bigquery.datasets.create IAM 權限。

  • 如要建立模型,您必須具備下列權限:

    • bigquery.jobs.create
    • bigquery.models.create
    • bigquery.models.getData
    • bigquery.models.updateData
  • 如要執行推論,您必須具備下列權限:

    • bigquery.models.getData
    • bigquery.jobs.create

如要進一步瞭解 BigQuery 的 IAM 角色和權限,請參閱「IAM 簡介」。

費用

在本文件中,您將使用下列 Google Cloud計費元件:

  • BigQuery: You incur costs for the data you process in BigQuery.

您可以使用 Pricing Calculator,根據預測用量估算費用。

初次使用 Google Cloud 的使用者可能符合免費試用期資格。

詳情請參閱「BigQuery 定價」一文。

事前準備

  1. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  2. Verify that billing is enabled for your Google Cloud project.

  3. Enable the BigQuery API, if it is not already enabled.

    Roles required to enable APIs

    To enable APIs, you need the serviceusage.services.enable permission. If you created the project, then you likely already have this permission through the Owner role (roles/owner). Otherwise, you can get this permission through the Service Usage Admin role (roles/serviceusage.serviceUsageAdmin). Learn how to grant roles.

    Enable the API

建立資料集

如要建立 BigQuery 資料集,請選取下列其中一個選項:

控制台

  1. 前往 Google Cloud 控制台的「BigQuery」頁面。

    前往「BigQuery」

  2. 點選左側窗格中的 「Explorer」。

    醒目顯示的「Explorer」窗格按鈕。

    如果沒有看到左側窗格,請按一下 「Expand left pane」(展開左側窗格),開啟窗格。

  3. 在「Explorer」中展開專案,然後按一下「資料集」。

  4. 在「Datasets」(資料集) 頁面,按一下「Create dataset」(建立資料集)。

  5. 在「建立資料集」窗格中,執行下列操作:

    • 在「Dataset ID」(資料集 ID) 中輸入 bqml_tutorial。

    • 在「資料位置」部分,選取「US」。

    其餘預設設定則保持不變。

  6. 點選「建立資料集」。

bq

如要建立新的資料集,請使用 bq mk --dataset 指令。

  1. 建立名為 bqml_tutorial 的資料集,並將資料位置設為 US:

    bq mk --dataset \
      --location=US \
      --description "BigQuery ML tutorial dataset." \
      bqml_tutorial
  2. 確認資料集已建立:

    bq ls

API

使用定義的資料集資源呼叫 datasets.insert 方法:

{
  "datasetReference": {
     "datasetId": "bqml_tutorial"
  }
}

準備訓練資料

PM2.5、溫度和風速資料分別位於不同的資料表。合併這些公開資料表中的資料,建立訓練資料的 bqml_tutorial.seattle_air_quality_daily 資料表。bqml_tutorial.seattle_air_quality_daily 包含下列資料欄:

  • date:觀測日期
  • PM2.5:每天的平均 PM2.5 值
  • wind_speed:每日平均風速
  • temperature:每天的最高溫

新資料表包含 2009 年 8 月 11 日至 2022 年 1 月 31 日的每日資料。

  1. 前往「BigQuery」頁面

    前往「BigQuery」

  2. 在 SQL 編輯器窗格中,執行下列 SQL 陳述式:

    CREATE TABLE `bqml_tutorial.seattle_air_quality_daily`
    AS
    WITH
      pm25_daily AS (
        SELECT
          avg(arithmetic_mean) AS pm25, date_local AS date
        FROM
          `bigquery-public-data.epa_historical_air_quality.pm25_nonfrm_daily_summary`
        WHERE
          city_name = 'Seattle'
          AND parameter_name = 'Acceptable PM2.5 AQI & Speciation Mass'
        GROUP BY date_local
      ),
      wind_speed_daily AS (
        SELECT
          avg(arithmetic_mean) AS wind_speed, date_local AS date
        FROM
          `bigquery-public-data.epa_historical_air_quality.wind_daily_summary`
        WHERE
          city_name = 'Seattle' AND parameter_name = 'Wind Speed - Resultant'
        GROUP BY date_local
      ),
      temperature_daily AS (
        SELECT
          avg(first_max_value) AS temperature, date_local AS date
        FROM
          `bigquery-public-data.epa_historical_air_quality.temperature_daily_summary`
        WHERE
          city_name = 'Seattle' AND parameter_name = 'Outdoor Temperature'
        GROUP BY date_local
      )
    SELECT
      pm25_daily.date AS date, pm25, wind_speed, temperature
    FROM pm25_daily
    JOIN wind_speed_daily USING (date)
    JOIN temperature_daily USING (date)

建立模型

使用 bqml_tutorial.seattle_air_quality_daily 的資料做為訓練資料,建立多變量時間序列模型。

  1. 前往「BigQuery」頁面

    前往「BigQuery」

  2. 在 SQL 編輯器窗格中,執行下列 SQL 陳述式:

    CREATE OR REPLACE MODEL `bqml_tutorial.arimax_model`
      OPTIONS (
        model_type = 'ARIMA_PLUS_XREG',
        auto_arima=TRUE,
        time_series_data_col = 'temperature',
        time_series_timestamp_col = 'date'
        )
    AS
    SELECT
      *
    FROM
      `bqml_tutorial.seattle_air_quality_daily`
    WHERE
      date < "2023-02-01";

    查詢會在幾秒內完成,之後模型 arimax_model 會顯示在 bqml_tutorial 資料集中,並可在「Explorer」窗格中存取。

    由於查詢使用 CREATE MODEL 陳述式建立模型,因此不會有查詢結果。

對歷來資料執行異常偵測

針對用於訓練模型的歷來資料執行異常偵測。

  1. 前往「BigQuery」頁面

    前往「BigQuery」

  2. 在 SQL 編輯器窗格中,執行下列 SQL 陳述式:

    SELECT
      *
    FROM
      ML.DETECT_ANOMALIES (
       MODEL `bqml_tutorial.arimax_model`,
       STRUCT(0.6 AS anomaly_prob_threshold)
      )
    ORDER BY
      date ASC;

    結果大致如下:

    +-------------------------+-------------+------------+--------------------+--------------------+---------------------+
    | date                    | temperature | is_anomaly | lower_bound        | upper_bound        | anomaly_probability |
    +--------------------------------------------------------------------------------------------------------------------+
    | 2009-08-11 00:00:00 UTC | 70.1        | false      | 67.647370742988727 | 72.552629257011262 | 0                   |
    +--------------------------------------------------------------------------------------------------------------------+
    | 2009-08-12 00:00:00 UTC | 73.4        | false      | 71.7035428351283   | 76.608801349150838 | 0.20478819992561115 |
    +--------------------------------------------------------------------------------------------------------------------+
    | 2009-08-13 00:00:00 UTC | 64.6        | true       | 67.740408724826068 | 72.6456672388486   | 0.945588334903206   |
    +-------------------------+-------------+------------+--------------------+--------------------+---------------------+
    

對新資料執行異常偵測

對生成的新資料執行異常偵測。

  1. 前往「BigQuery」頁面

    前往「BigQuery」

  2. 在 SQL 編輯器窗格中,執行下列 SQL 陳述式:

    SELECT
      *
    FROM
      ML.DETECT_ANOMALIES (
       MODEL `bqml_tutorial.arimax_model`,
       STRUCT(0.6 AS anomaly_prob_threshold),
       (
         SELECT
           *
         FROM
           UNNEST(
             [
               STRUCT<date TIMESTAMP, pm25 FLOAT64, wind_speed FLOAT64, temperature FLOAT64>
               ('2023-02-01 00:00:00 UTC', 8.8166665, 1.6525, 44.0),
               ('2023-02-02 00:00:00 UTC', 11.8354165, 1.558333, 40.5),
               ('2023-02-03 00:00:00 UTC', 10.1395835, 1.6895835, 46.5),
               ('2023-02-04 00:00:00 UTC', 11.439583500000001, 2.0854165, 45.0),
               ('2023-02-05 00:00:00 UTC', 9.7208335, 1.7083335, 46.0),
               ('2023-02-06 00:00:00 UTC', 13.3020835, 2.23125, 43.5),
               ('2023-02-07 00:00:00 UTC', 5.7229165, 2.377083, 47.5),
               ('2023-02-08 00:00:00 UTC', 7.6291665, 2.24375, 44.5),
               ('2023-02-09 00:00:00 UTC', 8.5208335, 2.2541665, 40.5),
               ('2023-02-10 00:00:00 UTC', 9.9086955, 7.333335, 39.5)
             ]
           )
         )
       );

    結果大致如下:

    +-------------------------+-------------+------------+--------------------+--------------------+---------------------+------------+------------+
    | date                    | temperature | is_anomaly | lower_bound        | upper_bound        | anomaly_probability | pm25       | wind_speed |
    +----------------------------------------------------------------------------------------------------------------------------------------------+
    | 2023-02-01 00:00:00 UTC | 44.0        | true       | 36.89918003713138  | 41.8044385511539   | 0.88975675709801583 | 8.8166665  | 1.6525     |
    +----------------------------------------------------------------------------------------------------------------------------------------------+
    | 2023-02-02 00:00:00 UTC | 40.5        | false      | 34.439946284051572 | 40.672021330796483 | 0.57358239699845348 | 11.8354165 | 1.558333   |
    +--------------------------------------------------------------------------------------------------------------------+-------------------------+
    | 2023-02-03 00:00:00 UTC | 46.5        | true       | 33.615139992931191 | 40.501364463964549 | 0.97902867696346974 | 10.1395835 | 1.6895835  |
    +-------------------------+-------------+------------+--------------------+--------------------+---------------------+-------------------------+
    

清除所用資源

  1. 前往 Google Cloud 控制台的「Manage resources」(管理資源) 頁面。

    前往「Manage resources」(管理資源)

  2. 在專案清單中選取要刪除的專案,然後點選「Delete」(刪除)。
  3. 在對話方塊中輸入專案 ID,然後按一下 [Shut down] (關閉) 以刪除專案。