Melakukan deteksi anomali dengan model perkiraan deret waktu multivariat

Tutorial ini menunjukkan cara melakukan tugas-tugas berikut:

Tutorial ini menggunakan tabel berikut dari set data epa_historical_air_quality publik, yang berisi informasi harian PM 2.5, suhu, dan kecepatan angin yang dikumpulkan dari beberapa kota di AS:

Izin yang diperlukan

  • Untuk membuat set data, Anda memerlukan izin IAM bigquery.datasets.create.

  • Untuk membuat model, Anda memerlukan izin berikut:

    • bigquery.jobs.create
    • bigquery.models.create
    • bigquery.models.getData
    • bigquery.models.updateData
  • Untuk menjalankan inferensi, Anda memerlukan izin berikut:

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

Untuk mengetahui informasi lebih lanjut tentang peran dan izin IAM di BigQuery, baca Pengantar IAM.

Biaya

Dalam dokumen ini, Anda akan menggunakan komponen yang dapat ditagih sebagai berikut Google Cloud:

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

Untuk membuat perkiraan biaya berdasarkan proyeksi penggunaan Anda, gunakan kalkulator harga.

Pengguna baru mungkin memenuhi syarat untuk mendapatkan uji coba gratis. Google Cloud

Untuk informasi lebih lanjut, lihat Harga BigQuery.

Sebelum memulai

  1. Sign in to your Google Cloud account. Jika Anda baru menggunakan Google Cloud, buat akun untuk mengevaluasi performa produk kami dalam skenario dunia nyata. Pelanggan baru juga mendapatkan kredit gratis senilai $300 untuk menjalankan, menguji, dan men-deploy workload.
  2. 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

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

  4. Enable the BigQuery API.

    Roles required to enable APIs

    To enable APIs, you need the Service Usage Admin IAM role (roles/serviceusage.serviceUsageAdmin), which contains the serviceusage.services.enable permission. Learn how to grant roles.

    Enable the API

  5. 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

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

  7. Enable the BigQuery API.

    Roles required to enable APIs

    To enable APIs, you need the Service Usage Admin IAM role (roles/serviceusage.serviceUsageAdmin), which contains the serviceusage.services.enable permission. Learn how to grant roles.

    Enable the API

Membuat set data

Buat set data BigQuery untuk menyimpan model ML Anda.

Konsol

  1. Di konsol Google Cloud , buka halaman BigQuery.

    Buka halaman BigQuery

  2. Di panel Explorer, klik nama project Anda.

  3. Klik View actions > Create dataset

  4. Di halaman Create dataset, lakukan hal berikut:

    • Untuk Dataset ID, masukkan bqml_tutorial.

    • Untuk Location type, pilih Multi-region, lalu pilih US.

    • Jangan ubah setelan default yang tersisa, lalu klik Create dataset.

bq

Untuk membuat set data baru, gunakan perintah bq mk --dataset.

  1. Buat set data bernama bqml_tutorial dengan lokasi data ditetapkan ke US.

    bq mk --dataset \
      --location=US \
      --description "BigQuery ML tutorial dataset." \
      bqml_tutorial
  2. Konfirmasi bahwa set data telah dibuat:

    bq ls

API

Panggil datasets.insert metode dengan resource set data yang ditentukan.

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

Menyiapkan data pelatihan

Data PM2,5, suhu, dan kecepatan angin berada di tabel terpisah. Buat tabel data pelatihan bqml_tutorial.seattle_air_quality_daily dengan menggabungkan data dalam tabel publik ini. bqml_tutorial.seattle_air_quality_daily berisi kolom berikut:

  • date: tanggal pengamatan
  • PM2.5: nilai rata-rata PM2,5 untuk setiap hari
  • wind_speed: kecepatan angin rata-rata untuk setiap hari
  • temperature: suhu tertinggi untuk setiap hari

Tabel baru ini memiliki data harian dari 11 Agustus 2009 hingga 31 Januari 2022.

  1. Buka halaman BigQuery.

    Buka BigQuery

  2. Di panel editor SQL, jalankan pernyataan SQL berikut:

    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)

Membuat model

Buat model deret waktu multivariat, menggunakan data dari bqml_tutorial.seattle_air_quality_daily sebagai data pelatihan.

  1. Buka halaman BigQuery.

    Buka BigQuery

  2. Di panel editor SQL, jalankan pernyataan SQL berikut:

    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";

    Kueri memerlukan waktu beberapa detik untuk diselesaikan, setelah itu model arimax_model akan muncul di set data bqml_tutorial dan dapat diakses di panel Explorer.

    Karena kueri menggunakan pernyataan CREATE MODEL untuk membuat model, tidak akan ada hasil kueri.

Melakukan deteksi anomali pada data historis

Jalankan deteksi anomali terhadap data historis yang Anda gunakan untuk melatih model.

  1. Buka halaman BigQuery.

    Buka BigQuery

  2. Di panel editor SQL, jalankan pernyataan SQL berikut:

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

    Hasilnya akan terlihat seperti berikut:

    +-------------------------+-------------+------------+--------------------+--------------------+---------------------+
    | 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   |
    +-------------------------+-------------+------------+--------------------+--------------------+---------------------+
    

Melakukan deteksi anomali pada data baru

Jalankan deteksi anomali pada data baru yang Anda buat.

  1. Buka halaman BigQuery.

    Buka BigQuery

  2. Di panel editor SQL, jalankan pernyataan SQL berikut:

    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)
             ]
           )
         )
       );

    Hasilnya akan terlihat seperti berikut:

    +-------------------------+-------------+------------+--------------------+--------------------+---------------------+------------+------------+
    | 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  |
    +-------------------------+-------------+------------+--------------------+--------------------+---------------------+-------------------------+
    

Pembersihan

  1. Di Google Cloud konsol, buka halaman Manage resources.

    Buka Kelola resource

  2. Pada daftar project, pilih project yang Anda ingin Anda hapus, lalu klik Delete.
  3. Pada dialog, ketik project ID, lalu klik Shut down untuk menghapus project.