使用增強型樹狀模型進行分類


本教學課程將說明如何使用提升樹分類器模型,根據個人人口統計資料預測其收入範圍。模型會預測某值是否屬於兩個類別之一,在本例中,就是個人年收入是否超過或低於 $50,000 美元。

本教學課程使用 bigquery-public-data.ml_datasets.census_adult_income 資料集。這個資料集包含從 2000 年到 2010 年美國居民的人口和收入資訊。

目標

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

費用

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

  • BigQuery
  • BigQuery ML

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

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

事前準備

  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)

準備範例資料

您在本教學課程中建立的模型會根據下列特徵,預測人口普查受訪者的收入等級:

  • 年齡
  • 從事的工作類型
  • 婚姻狀態
  • 教育程度
  • 職業
  • 每週工作時數

education 欄並未納入訓練資料,因為 educationeducation_num 欄都以不同格式表示受訪者的教育程度。

您可以建立新的 dataframe 資料欄,並從 functional_weight 資料欄衍生,藉此將資料分割為訓練、評估和預測集。八成資料用於訓練模型,其餘兩成資料則用於評估和預測。

SQL

如要準備範例資料,請建立檢視畫面來容納訓練資料。這個檢視畫面會在本教學課程後續的 CREATE MODEL 陳述式中使用。

執行準備範例資料的查詢:

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

    前往 BigQuery

  2. 在查詢編輯器中執行以下查詢:

    CREATE OR REPLACE VIEW
      `bqml_tutorial.input_data` AS
    SELECT
      age,
      workclass,
      marital_status,
      education_num,
      occupation,
      hours_per_week,
      income_bracket,
      CASE
        WHEN MOD(functional_weight, 10) < 8 THEN 'training'
        WHEN MOD(functional_weight, 10) = 8 THEN 'evaluation'
        WHEN MOD(functional_weight, 10) = 9 THEN 'prediction'
      END AS dataframe
    FROM
      `bigquery-public-data.ml_datasets.census_adult_income`;
  3. 在「Explorer」窗格中展開 bqml_tutorial 資料集,然後找出 input_data 檢視畫面。

  4. 按一下檢視名稱,開啟資訊窗格。檢視表結構定義會顯示在「Schema」分頁中。

BigQuery DataFrames

建立名為 input_data 的 DataFrame。您稍後會在本教學課程中使用 input_data 訓練模型、評估模型,並進行預測。

在嘗試這個範例之前,請先參閱 BigQuery 快速入門:使用 BigQuery DataFrames,按照 BigQuery DataFrames 設定說明進行操作。詳情請參閱 BigQuery DataFrames 參考資料說明文件

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

import bigframes.pandas as bpd

input_data = bpd.read_gbq(
    "bigquery-public-data.ml_datasets.census_adult_income",
    columns=(
        "age",
        "workclass",
        "marital_status",
        "education_num",
        "occupation",
        "hours_per_week",
        "income_bracket",
        "functional_weight",
    ),
)
input_data["dataframe"] = bpd.Series("training", index=input_data.index,).case_when(
    [
        (((input_data["functional_weight"] % 10) == 8), "evaluation"),
        (((input_data["functional_weight"] % 10) == 9), "prediction"),
    ]
)
del input_data["functional_weight"]

建立增強型樹狀模型

建立提升樹模型,以預測人口普查受訪者的收入區間,並使用人口普查資料訓練模型。查詢大約需要 30 分鐘才能完成。

SQL

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

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

    前往 BigQuery

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

    CREATE MODEL `bqml_tutorial.tree_model`
    OPTIONS(MODEL_TYPE='BOOSTED_TREE_CLASSIFIER',
            BOOSTER_TYPE = 'GBTREE',
            NUM_PARALLEL_TREE = 1,
            MAX_ITERATIONS = 50,
            TREE_METHOD = 'HIST',
            EARLY_STOP = FALSE,
            SUBSAMPLE = 0.85,
            INPUT_LABEL_COLS = ['income_bracket'])
    AS SELECT * EXCEPT(dataframe)
    FROM `bqml_tutorial.input_data`
    WHERE dataframe = 'training';

    查詢完成後,tree_model 模型會顯示在「探索器」窗格中。由於查詢是使用 CREATE MODEL 陳述式建立模型,因此您不會看到查詢結果。

BigQuery DataFrames

在嘗試這個範例之前,請先參閱 BigQuery 快速入門:使用 BigQuery DataFrames,按照 BigQuery DataFrames 設定說明進行操作。詳情請參閱 BigQuery DataFrames 參考資料說明文件

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

from bigframes.ml import ensemble

# input_data is defined in an earlier step.
training_data = input_data[input_data["dataframe"] == "training"]
X = training_data.drop(columns=["income_bracket", "dataframe"])
y = training_data["income_bracket"]

# create and train the model
tree_model = ensemble.XGBClassifier(
    n_estimators=1,
    booster="gbtree",
    tree_method="hist",
    max_iterations=1,  # For a more accurate model, try 50 iterations.
    subsample=0.85,
)
tree_model.fit(X, y)

tree_model.to_gbq(
    your_model_id,  # For example: "your-project.bqml_tutorial.tree_model"
    replace=True,
)

評估模型

SQL

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

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

    前往 BigQuery

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

      SELECT
        *
      FROM
        ML.EVALUATE (MODEL `bqml_tutorial.tree_model`,
          (
          SELECT
            *
          FROM
            `bqml_tutorial.input_data`
          WHERE
            dataframe = 'evaluation'
          )
        );

    結果應如下所示:

    +---------------------+---------------------+---------------------+-------------------+---------------------+---------------------+
    | precision           | recall              | accuracy            | f1_score          | log_loss            | roc_auc             |
    +---------------------+---------------------+---------------------+-------------------+-------------------------------------------+
    | 0.67192429022082023 | 0.57880434782608692 | 0.83942963422194672 | 0.621897810218978 | 0.34405456040833338 | 0.88733566433566435 |
    +---------------------+---------------------+ --------------------+-------------------+---------------------+---------------------+
    

BigQuery DataFrames

在嘗試這個範例之前,請先參閱 BigQuery 快速入門:使用 BigQuery DataFrames,按照 BigQuery DataFrames 設定說明進行操作。詳情請參閱 BigQuery DataFrames 參考資料說明文件

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

# Select model you'll use for predictions. `read_gbq_model` loads model
# data from BigQuery, but you could also use the `tree_model` object
# from the previous step.
tree_model = bpd.read_gbq_model(
    your_model_id,  # For example: "your-project.bqml_tutorial.tree_model"
)

# input_data is defined in an earlier step.
evaluation_data = input_data[input_data["dataframe"] == "evaluation"]
X = evaluation_data.drop(columns=["income_bracket", "dataframe"])
y = evaluation_data["income_bracket"]

# The score() method evaluates how the model performs compared to the
# actual data. Output DataFrame matches that of ML.EVALUATE().
score = tree_model.score(X, y)
score.peek()
# Output:
#    precision    recall  accuracy  f1_score  log_loss   roc_auc
# 0   0.671924  0.578804  0.839429  0.621897  0.344054  0.887335

評估指標顯示模型成效良好,特別是 roc_auc 分數大於 0.8

如要進一步瞭解評估指標,請參閱分類模型

使用模型預測分類

SQL

如要使用模型預測資料,請按照下列步驟操作:

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

    前往 BigQuery

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

      SELECT
        *
      FROM
        ML.PREDICT (MODEL `bqml_tutorial.tree_model`,
          (
          SELECT
            *
          FROM
            `bqml_tutorial.input_data`
          WHERE
            dataframe = 'prediction'
          )
        );

結果的前幾欄應如下所示:

  +---------------------------+--------------------------------------+-------------------------------------+
  | predicted_income_bracket  | predicted_income_bracket_probs.label | predicted_income_bracket_probs.prob |
  +---------------------------+--------------------------------------+-------------------------------------+
  |  <=50K                    |  >50K                                | 0.05183430016040802                 |
  +---------------------------+--------------------------------------+-------------------------------------+
  |                           |  <50K                                | 0.94816571474075317                 |
  +---------------------------+--------------------------------------+-------------------------------------+
  |  <=50K                    |  >50K                                | 0.00365859130397439                 |
  +---------------------------+--------------------------------------+-------------------------------------+
  |                           |  <50K                                | 0.99634140729904175                 |
  +---------------------------+--------------------------------------+-------------------------------------+
  |  <=50K                    |  >50K                                | 0.037775970995426178                |
  +---------------------------+--------------------------------------+-------------------------------------+
  |                           |  <50K                                | 0.96222406625747681                 |
  +---------------------------+--------------------------------------+-------------------------------------+
  

BigQuery DataFrames

在嘗試這個範例之前,請先參閱 BigQuery 快速入門:使用 BigQuery DataFrames,按照 BigQuery DataFrames 設定說明進行操作。詳情請參閱 BigQuery DataFrames 參考資料說明文件

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

# Select model you'll use for predictions. `read_gbq_model` loads model
# data from BigQuery, but you could also use the `tree_model` object
# from previous steps.
tree_model = bpd.read_gbq_model(
    your_model_id,  # For example: "your-project.bqml_tutorial.tree_model"
)

# input_data is defined in an earlier step.
prediction_data = input_data[input_data["dataframe"] == "prediction"]

predictions = tree_model.predict(prediction_data)
predictions.peek()
# Output:
# predicted_income_bracket   predicted_income_bracket_probs.label  predicted_income_bracket_probs.prob
#                   <=50K                                   >50K                   0.05183430016040802
#                                                           <50K                   0.94816571474075317
#                   <=50K                                   >50K                   0.00365859130397439
#                                                           <50K                   0.99634140729904175
#                   <=50K                                   >50K                   0.037775970995426178
#                                                           <50K                   0.96222406625747681

predicted_income_bracket 包含模型的預測值。predicted_income_bracket_probs.label 會顯示模型必須選擇的兩個標籤,而 predicted_income_bracket_probs.prob 欄則會顯示指定標籤為正確標籤的機率。

如要進一步瞭解輸出欄,請參閱分類模型

清除所用資源

如要避免系統向您的 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.

後續步驟