透過超參數調整提升模型效能


本教學課程將說明如何在 BigQuery ML 中使用超參數調整功能,調整機器學習模型並改善其效能。

您可以指定 CREATE MODEL 陳述式的 NUM_TRIALS 選項,並搭配其他特定模型選項,執行超參數調整。設定這些選項後,BigQuery ML 會訓練多個模型版本或試驗,每個版本的參數略有不同,並傳回成效最佳的試驗。

本教學課程會使用公開的 tlc_yellow_trips_2018 範例表格,其中包含紐約市 2018 年計程車行程的相關資訊。

目標

本教學課程會逐步引導您完成下列工作:

費用

本教學課程使用 Google Cloud的計費元件,包括:

  • BigQuery
  • BigQuery ML

如要進一步瞭解 BigQuery 費用,請參閱 BigQuery 定價頁面。

事前準備

  1. Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
  2. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  3. Make sure that billing is enabled for your Google Cloud project.

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

    Go to project selector

  5. Make sure that billing is enabled for your Google Cloud project.

  6. 新專案會自動啟用 BigQuery。如要在現有的專案中啟用 BigQuery,請前往

    Enable the BigQuery API.

    Enable the API

  7. 所需權限

    • 如要建立資料集,您必須具備 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 簡介」。

建立資料集

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

控制台

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

    前往「BigQuery」頁面

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

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

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

  4. 在「Create dataset」頁面上執行下列操作:

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

    • 在「位置類型」中選取「多區域」,然後選取「美國 (多個美國區域)」

    • 保留其餘預設設定,然後點選「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 快速入門:使用 BigQuery DataFrames,按照 BigQuery DataFrames 設定說明進行操作。詳情請參閱 BigQuery DataFrames 參考資料說明文件

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

import google.cloud.bigquery

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

建立訓練資料表

根據 tlc_yellow_trips_2018 資料表資料的子集,建立訓練資料表。

請按照下列步驟建立資料表:

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

    前往 BigQuery

  2. 在查詢編輯器中貼上以下查詢,然後點選「執行」

    CREATE OR REPLACE TABLE `bqml_tutorial.taxi_tip_input`
    AS
    SELECT * EXCEPT (tip_amount), tip_amount AS label
    FROM
      `bigquery-public-data.new_york_taxi_trips.tlc_yellow_trips_2018`
    WHERE
      tip_amount IS NOT NULL
    LIMIT 100000;

建立基準線性迴歸模型

建立不經過超參數調整的線性迴歸模型,並在 taxi_tip_input 資料表資料上訓練模型。

請按照下列步驟建立模型:

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

    前往 BigQuery

  2. 在查詢編輯器中貼上以下查詢,然後點選「執行」

    CREATE OR REPLACE MODEL `bqml_tutorial.baseline_taxi_tip_model`
      OPTIONS (
        MODEL_TYPE = 'LINEAR_REG'
      )
    AS
    SELECT
      *
    FROM
      `bqml_tutorial.taxi_tip_input`;

    查詢���約需要 2 分鐘才能完成。

評估基準模型

使用 ML.EVALUATE 函式評估模型效能。ML.EVALUATE 函式會根據模型訓練期間計算的評估指標,評估模型傳回的預測內容評分。

如要評估模型,請按照下列步驟操作:

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

    前往 BigQuery

  2. 在查詢編輯器中貼上以下查詢,然後點選「執行」

    SELECT *
    FROM
      ML.EVALUATE(MODEL `bqml_tutorial.baseline_taxi_tip_model`);

    結果如下所示:

    +---------------------+--------------------+------------------------+-----------------------+---------------------+---------------------+
    | mean_absolute_error | mean_squared_error | mean_squared_log_error | median_absolute_error |      r2_score       | explained_variance  |
    +---------------------+--------------------+------------------------+-----------------------+---------------------+---------------------+
    |  2.5853895559690323 | 23760.416358496139 |   0.017392406523370374 | 0.0044248227819481123 | -1934.5450533482465 | -1934.3513857946277 |
    +---------------------+--------------------+------------------------+-----------------------+---------------------+---------------------+
    

基準模型的 r2_score 值為負值,表示模型與資料不相符;R2 分數越接近 1,模型就越適合。

使用超參數調整建立線性迴歸模型

使用超參數調整建立線性迴歸模型,並在 taxi_tip_input 資料表資料上訓練模型。

您可以在 CREATE MODEL 陳述式中使用下列超參數調整選項:

  • NUM_TRIALS 選項:將測試次數設為 20 次。
  • MAX_PARALLEL_TRIALS 選項:在每個訓練工作中執行兩次試驗,共十個工作和二十次試驗。這麼做可縮短訓練所需的時間。不過,兩個同時進行的試驗並不會互相利用訓練結果。
  • L1_REG 選項:在不同試驗中嘗試不同的 L1 正則化值。L1 正則化會從模型中移除不相關的特徵,有助於避免過度擬合

模型支援的其他超參數調整選項會使用預設值,如下所示:

  • L1_REG0
  • HPARAM_TUNING_ALGORITHM'VIZIER_DEFAULT'
  • HPARAM_TUNING_OBJECTIVES['R2_SCORE']

請按照下列步驟建立模型:

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

    前往 BigQuery

  2. 在查詢編輯器中貼上以下查詢,然後點選「執行」

    CREATE OR REPLACE MODEL `bqml_tutorial.hp_taxi_tip_model`
      OPTIONS (
        MODEL_TYPE = 'LINEAR_REG',
        NUM_TRIALS = 20,
        MAX_PARALLEL_TRIALS = 2,
        L1_REG = HPARAM_RANGE(0, 5))
    AS
    SELECT
      *
    FROM
      `bqml_tutorial.taxi_tip_input`;

    這項查詢大約需要 20 分鐘才能完成。

取得訓練試驗資訊

使用 ML.TRIAL_INFO 函式,即可取得所有試驗的相關資訊,包括超參數值、目標和狀態。這個函式也會根據這項資訊,傳回哪項測試的效能最佳的相關資訊。

如要取得試用資訊,請按照下列步驟操作:

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

    前往 BigQuery

  2. 在查詢編輯器中貼上以下查詢,然後點選「執行」

    SELECT *
    FROM
      ML.TRIAL_INFO(MODEL `bqml_tutorial.hp_taxi_tip_model`)
    ORDER BY is_optimal DESC;

    結果如下所示:

    +----------+-------------------------------------+-----------------------------------+--------------------+--------------------+-----------+---------------+------------+
    | trial_id |           hyperparameters           | hparam_tuning_evaluation_metrics  |   training_loss    |     eval_loss      |  status   | error_message | is_optimal |
    +----------+-------------------------------------+-----------------------------------+--------------------+--------------------+-----------+---------------+------------+
    |        7 |      {"l1_reg":"4.999999999999985"} |  {"r2_score":"0.653653627638174"} | 4.4677841296238165 |  4.478469742512195 | SUCCEEDED | NULL          |       true |
    |        2 |  {"l1_reg":"2.402163664510254E-11"} | {"r2_score":"0.6532493667964732"} |  4.457692508421795 |  4.483697081650438 | SUCCEEDED | NULL          |      false |
    |        3 |  {"l1_reg":"1.2929452948742316E-7"} |  {"r2_score":"0.653249366811995"} |   4.45769250849513 |  4.483697081449748 | SUCCEEDED | NULL          |      false |
    |        4 |  {"l1_reg":"2.5787102060628228E-5"} | {"r2_score":"0.6532493698925899"} |  4.457692523040582 |  4.483697041615808 | SUCCEEDED | NULL          |      false |
    |      ... |                             ...     |                           ...     |              ...   |             ...    |       ... |          ...  |        ... |
    +----------+-------------------------------------+-----------------------------------+--------------------+--------------------+-----------+---------------+------------+
    

    is_optimal 欄值表示試驗 7 是微調所傳回的最佳模型。

評估經過調整的模型測試

使用 ML.EVALUATE 函式評估試驗的成效。ML.EVALUATE 函式會根據所有試驗期間訓練時計算的評估指標,評估模型傳回的預測內容評等。

請按照下列步驟評估模型試驗:

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

    前往 BigQuery

  2. 在查詢編輯器中貼上以下查詢,然後點選「執行」

    SELECT *
    FROM
      ML.EVALUATE(MODEL `bqml_tutorial.hp_taxi_tip_model`)
    ORDER BY r2_score DESC;

    結果如下所示:

    +----------+---------------------+--------------------+------------------------+-----------------------+--------------------+--------------------+
    | trial_id | mean_absolute_error | mean_squared_error | mean_squared_log_error | median_absolute_error |      r2_score      | explained_variance |
    +----------+---------------------+--------------------+------------------------+-----------------------+--------------------+--------------------+
    |        7 |   1.151814398002232 |  4.109811493266523 |     0.4918733252641176 |    0.5736103414025084 | 0.6652110305659145 | 0.6652144696114834 |
    |       19 |  1.1518143358927102 |  4.109811921460791 |     0.4918672150119582 |    0.5736106106914161 | 0.6652109956848206 | 0.6652144346901685 |
    |        8 |   1.152747850702547 |  4.123625876152422 |     0.4897808307399327 |    0.5731702310239184 | 0.6640856984144734 |  0.664088410199906 |
    |        5 |   1.152895108945439 |  4.125775524878872 |    0.48939088205957937 |    0.5723300569616766 | 0.6639105860807425 | 0.6639132416838652 |
    |      ... |                ...  |                ... |                    ... |                   ... |                ... |                ... |
    +----------+---------------------+--------------------+------------------------+-----------------------+--------------------+--------------------+
    

    最佳模型 (即試驗 7) 的 r2_score 值為 0.66521103056591446,顯示相較於基準模型,有顯著改善。

您可以在 ML.EVALUATE 函式中指定 TRIAL_ID 引數,評估特定試驗。

如要進一步瞭解 ML.TRIAL_INFO 目標和 ML.EVALUATE 評估指標的差異,請參閱「模型服務函式」。

使用微調後的模型預測計程車小費

使用微調作業傳回的最佳模型,預測不同計程車行程的小費。除非您指定 TRIAL_ID 引數,否則 ML.PREDICT 函式會自動使用最佳模型。預測結果會傳回至 predicted_label 欄。

如要取得預測結果,請按照下列步驟操作:

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

    前往 BigQuery

  2. 在查詢編輯器中貼上以下查詢,然後點選「執行」

    SELECT *
    FROM
      ML.PREDICT(
        MODEL `bqml_tutorial.hp_taxi_tip_model`,
        (
          SELECT
            *
          FROM
            `bqml_tutorial.taxi_tip_input`
          LIMIT 5
        ));

    結果如下所示:

    +----------+--------------------+-----------+---------------------+---------------------+-----------------+---------------+-----------+--------------------+--------------+-------------+-------+---------+--------------+---------------+--------------+--------------------+---------------------+----------------+-----------------+-------+
    | trial_id |  predicted_label   | vendor_id |   pickup_datetime   |  dropoff_datetime   | passenger_count | trip_distance | rate_code | store_and_fwd_flag | payment_type | fare_amount | extra | mta_tax | tolls_amount | imp_surcharge | total_amount | pickup_location_id | dropoff_location_id | data_file_year | data_file_month | label |
    +----------+--------------------+-----------+---------------------+---------------------+-----------------+---------------+-----------+--------------------+--------------+-------------+-------+---------+--------------+---------------+--------------+--------------------+---------------------+----------------+-----------------+-------+
    |        7 |  1.343367839584448 | 2         | 2018-01-15 18:55:15 | 2018-01-15 18:56:18 |               1 |             0 | 1         | N                  | 1            |           0 |     0 |       0 |            0 |             0 |            0 | 193                | 193                 |           2018 |               1 |     0 |
    |        7 | -1.176072791783461 | 1         | 2018-01-08 10:26:24 | 2018-01-08 10:26:37 |               1 |             0 | 5         | N                  | 3            |        0.01 |     0 |       0 |            0 |           0.3 |         0.31 | 158                | 158                 |           2018 |               1 |     0 |
    |        7 |  3.839580104168765 | 1         | 2018-01-22 10:58:02 | 2018-01-22 12:01:11 |               1 |          16.1 | 1         | N                  | 1            |        54.5 |     0 |     0.5 |            0 |           0.3 |         55.3 | 140                | 91                  |           2018 |               1 |     0 |
    |        7 |  4.677393985230036 | 1         | 2018-01-16 10:14:35 | 2018-01-16 11:07:28 |               1 |            18 | 1         | N                  | 2            |        54.5 |     0 |     0.5 |            0 |           0.3 |         55.3 | 138                | 67                  |           2018 |               1 |     0 |
    |        7 |  7.938988937253062 | 2         | 2018-01-16 07:05:15 | 2018-01-16 08:06:31 |               1 |          17.8 | 1         | N                  | 1            |        54.5 |     0 |     0.5 |            0 |           0.3 |        66.36 | 132                | 255                 |           2018 |               1 | 11.06 |
    +----------+--------------------+-----------+---------------------+---------------------+-----------------+---------------+-----------+--------------------+--------------+-------------+-------+---------+--------------+---------------+--------------+--------------------+---------------------+----------------+-----------------+-------+
    

清除所用資源

如要避免系統向您的 Google Cloud 帳戶收取本教學課程中所用資源的相關費用,請刪除含有該項資源的專案,或者保留專案但刪除個別資源。

  • 您可以刪除建立的專案。
  • 或者您可以保留專案並刪除資料集。

刪除資料集

刪除專案將移除專案中所有的資料集與資料表。若您希望重新使用專案,您可以刪除本教學課程中所建立的資料集。

  1. 如有必要,請���Google Cloud ������台中開啟 BigQuery 頁面。

    前往「BigQuery」頁面

  2. 在導覽面板中,按一下您建立的 bqml_tutorial 資料集。

  3. 按一下視窗右側的「Delete dataset」。這項操作會刪除資料集、資料表和所有資料。

  4. 在「Delete dataset」對話方塊中,輸入資料集的名稱 (bqml_tutorial),然後按一下「Delete」來確認刪除指令。

刪除專案

如要刪除專案,請進行以下操作:

  1. In the Google 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.

後續步驟