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

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

本教學課程會使用公開 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 簡介」。

費用

在本文件中,您會使用 Trusted Cloud by S3NS的下列計費元件:

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

如要根據預測用量估算費用,請使用 Pricing Calculator

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

詳情請參閱 BigQuery 價格一文。

事前準備

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

    Go to project selector

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

  3. Enable the BigQuery API.

    Enable the API

  4. 建立資料集

    建立 BigQuery 資料集來儲存機器學習模型。

    控制台

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

      前往 BigQuery 頁面

    2. 在「Explorer」窗格中,按一下專案名稱。

    3. 依序點按 「View actions」(查看動作) >「Create dataset」(建立資料集)

      「建立資料集」選單選項。

    4. 在「建立資料集」頁面中,執行下列操作:

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

      • 針對「Location type」(位置類型) 選取「Multi-region」(多區域),然後選取「US (multiple regions in United States)」(us (多個美國區域))

      • 其餘設定請保留預設狀態,然後按一下「Create dataset」(建立資料集)

    bq

    如要建立新的資料集,請使用 bq mk 指令搭配 --location 旗標。如需可能的完整參數清單,請參閱 bq mk --dataset 指令參考資料。

    1. 建立名為「bqml_tutorial」的資料集,並將資料位置設為「US」,以及說明設為「BigQuery ML tutorial dataset」:

      bq --location=US mk -d \
       --description "BigQuery ML tutorial dataset." \
       bqml_tutorial

      這個指令採用 -d 捷徑,而不是使用 --dataset 旗標。如果您省略 -d--dataset,該指令預設會建立資料集。

    2. 確認資料集已建立完成:

      bq ls

    API

    請呼叫 datasets.insert 方法,搭配已定義的資料集資源

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

    BigQuery DataFrames

    在嘗試這個範例之前,請按照使用 BigQuery DataFrames 的 BigQuery 快速入門導覽課程中的 BigQuery DataFrames 設定說明操作。 詳情請參閱 BigQuery DataFrames 參考說明文件

    如要向 BigQuery 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定 ADC」。

    import google.cloud.bigquery
    
    bqclient = google.cloud.bigquery.Client()
    bqclient.create_dataset("bqml_tutorial", exists_ok=True)

    準備訓練資料

    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 會顯示在「Explorer」(探索工具) 窗格的 bqml_tutorial 資料集中。

      由於查詢是使用 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. In the Trusted Cloud console, go to the Manage resources page.

      Go to Manage resources

    2. In the project list, select the project that you want to delete, and then click Delete.
    3. In the dialog, type the project ID, and then click Shut down to delete the project.