匯出 BigQuery ML 模型以進行線上預測


本教學課程說明如何匯出 BigQuery ML 模型,然後在 Vertex AI 或本機電腦上部署模型。您將使用 BigQuery 公開資料集中的 iris 資料表,完成下列三個端對端情境:

  • 訓練及部署邏輯迴歸模型 - 也適用於 DNN 分類器、DNN 迴歸器、k-means、線性迴歸和矩陣分解模型。
  • 訓練及部署提升決策樹分類器模型,這也適用於提升決策樹迴歸模型。
  • 訓練及部署 AutoML 分類器模型 - 也適用於 AutoML 迴歸模型。

費用

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

  • BigQuery ML
  • Cloud Storage
  • Vertex AI (選用,用於線上預測)

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

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

如要進一步瞭解 Vertex AI 費用,請參閱「自訂訓練模型」。

事前準備

  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. Enable the AI Platform Training and Prediction API and Compute Engine APIs.

    Enable the APIs

  8. 安裝 Google Cloud CLI Google Cloud CLI

建立您的資料集

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

控制台

  1. 前往 Google 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)

訓練及部署邏輯迴歸模型

請參閱下列各節,瞭解如何訓練及部署邏輯迴歸模型。

訓練模型

使用 BigQuery ML CREATE MODEL 陳述式,訓練可預測鳶尾花類型的邏輯迴歸模型。這項訓練工作大約 1 分鐘就能完成。

bq query --use_legacy_sql=false \
  'CREATE MODEL `bqml_tutorial.iris_model`
  OPTIONS (model_type="logistic_reg",
      max_iterations=10, input_label_cols=["species"])
  AS SELECT
    *
  FROM
    `bigquery-public-data.ml_datasets.iris`;'

匯出模型

使用 bq 指令列工具將模型匯出至 Cloud Storage bucket。如需其他模型匯出方式,請參閱「匯出 BigQuery ML 模型」。這項擷取作業應可在 1 分鐘內完成。

bq extract -m bqml_tutorial.iris_model gs://some/gcs/path/iris_model

在本機部署及提供服務

您可以使用 TensorFlow Serving Docker 容器,部署匯出的 TensorFlow 模型。下列步驟需要安裝 Docker

將匯出的模型檔案下載至暫時目錄

mkdir tmp_dir
gcloud storage cp gs://some/gcs/path/iris_model tmp_dir --recursive

建立版本子目錄

這個步驟會為模型設定版本號碼 (本例為 1)。

mkdir -p serving_dir/iris_model/1
cp -r tmp_dir/iris_model/* serving_dir/iris_model/1
rm -r tmp_dir

提取 Docker 映像檔

docker pull tensorflow/serving

執行 Docker 容器

docker run -p 8500:8500 --network="host" --mount type=bind,source=`pwd`/serving_dir/iris_model,target=/models/iris_model -e MODEL_NAME=iris_model -t tensorflow/serving &

執行預測

curl -d '{"instances": [{"sepal_length":5.0, "sepal_width":2.0, "petal_length":3.5, "petal_width":1.0}]}' -X POST http://localhost:8501/v1/models/iris_model:predict

線上部署和供應

本節會使用 Google Cloud CLI 部署匯出的模型,並根據該模型執行預測。

如要進一步瞭解如何將模型部署至 Vertex AI,以進行線上或批次預測,請參閱「將模型部署至端點」。

建立模型資源

MODEL_NAME="IRIS_MODEL"
gcloud ai-platform models create $MODEL_NAME

建立模型版本

1) 設定環境變數:

MODEL_DIR="gs://some/gcs/path/iris_model"
// Select a suitable version for this model
VERSION_NAME="v1"
FRAMEWORK="TENSORFLOW"

2) 建立版本:

gcloud ai-platform versions create $VERSION_NAME --model=$MODEL_NAME --origin=$MODEL_DIR --runtime-version=1.15 --framework=$FRAMEWORK

這個步驟可能需要幾分鐘才能完成。您應該會看到「Creating version (this might take a few minutes)......」訊息。

3) (選用) 取得新版本的相關資訊:

gcloud ai-platform versions describe $VERSION_NAME --model $MODEL_NAME

畫面會顯示類似以下的輸出:

createTime: '2020-02-28T16:30:45Z'
deploymentUri: gs://your_bucket_name
framework: TENSORFLOW
machineType: mls1-c1-m2
name: projects/[YOUR-PROJECT-ID]/models/IRIS_MODEL/versions/v1
pythonVersion: '2.7'
runtimeVersion: '1.15'
state: READY

線上預測

如要進一步瞭解如何針對已部署的模型執行線上預測,請參閱「透過自訂訓練模型取得線上推論結果」。

1) 建立以換行符號分隔的 JSON 輸入檔案,例如 instances.json 檔案,其中含有下列內容:

{"sepal_length":5.0, "sepal_width":2.0, "petal_length":3.5, "petal_width":1.0}
{"sepal_length":5.3, "sepal_width":3.7, "petal_length":1.5, "petal_width":0.2}

2) 設定預測的環境變數:

INPUT_DATA_FILE="instances.json"

3) 執行預測:

gcloud ai-platform predict --model $MODEL_NAME --version $VERSION_NAME --json-instances $INPUT_DATA_FILE

訓練及部署提升決策樹分類器模型

請參閱下列各節,瞭解如何訓練及部署升級樹狀結構分類器模型。

訓練模型

使用 CREATE MODEL 陳述式訓練可預測鳶尾花類型的提升樹狀結構分類器模型。這項訓練工作大約需要 7 分鐘才能完成。

bq query --use_legacy_sql=false \
  'CREATE MODEL `bqml_tutorial.boosted_tree_iris_model`
  OPTIONS (model_type="boosted_tree_classifier",
      max_iterations=10, input_label_cols=["species"])
  AS SELECT
    *
  FROM
    `bigquery-public-data.ml_datasets.iris`;'

匯出模型

使用 bq 指令列工具將模型匯出至 Cloud Storage bucket。如要瞭解其他模型匯出方式,請參閱「匯出 BigQuery ML 模型」。

bq extract --destination_format ML_XGBOOST_BOOSTER -m bqml_tutorial.boosted_tree_iris_model gs://some/gcs/path/boosted_tree_iris_model

在本機部署及提供服務

匯出的檔案中會有 main.py 檔案,供本機執行。

將匯出的模型檔案下載至本機目錄

mkdir serving_dir
gcloud storage cp gs://some/gcs/path/boosted_tree_iris_model serving_dir --recursive

擷取預測因子

tar -xvf serving_dir/boosted_tree_iris_model/xgboost_predictor-0.1.tar.gz -C serving_dir/boosted_tree_iris_model/

安裝 XGBoost 程式庫

安裝 XGBoost 程式庫 (0.82 以上版本)。

執行預測

cd serving_dir/boosted_tree_iris_model/
python main.py '[{"sepal_length":5.0, "sepal_width":2.0, "petal_length":3.5, "petal_width":1.0}]'

線上部署和供應

本節會使用 Google Cloud CLI 部署匯出的模型,並根據該模型執行預測。詳情請參閱透過自訂訓練模型取得線上推論結果

如要進一步瞭解如何將模型部署至 Vertex AI,以便使用自訂常式執行線上或批次預測,請參閱「將模型部署至端點」。

建立模型資源

MODEL_NAME="BOOSTED_TREE_IRIS_MODEL"
gcloud ai-platform models create $MODEL_NAME

建立模型版本

1) 設定環境變數:

MODEL_DIR="gs://some/gcs/path/boosted_tree_iris_model"
VERSION_NAME="v1"

2) 建立版本:

gcloud beta ai-platform versions create $VERSION_NAME --model=$MODEL_NAME --origin=$MODEL_DIR --package-uris=${MODEL_DIR}/xgboost_predictor-0.1.tar.gz --prediction-class=predictor.Predictor --runtime-version=1.15

這個步驟可能需要幾分鐘才能完成。您應該會看到「Creating version (this might take a few minutes)......」訊息。

3) (選用) 取得新版本的相關資訊:

gcloud ai-platform versions describe $VERSION_NAME --model $MODEL_NAME

畫面會顯示類似以下的輸出:

createTime: '2020-02-07T00:35:42Z'
deploymentUri: gs://some/gcs/path/boosted_tree_iris_model
etag: rp090ebEnQk=
machineType: mls1-c1-m2
name: projects/[YOUR-PROJECT-ID]/models/BOOSTED_TREE_IRIS_MODEL/versions/v1
packageUris:
- gs://some/gcs/path/boosted_tree_iris_model/xgboost_predictor-0.1.tar.gz
predictionClass: predictor.Predictor
pythonVersion: '2.7'
runtimeVersion: '1.15'
state: READY

線上預測

如要進一步瞭解如何針對已部署的模型執行線上預測,請參閱「透過自訂訓練模型取得線上推論結果」。

1) 建立以換行符號分隔的輸入內容 JSON 檔案。舉例來說,instances.json 檔案的內容如下:

{"sepal_length":5.0, "sepal_width":2.0, "petal_length":3.5, "petal_width":1.0}
{"sepal_length":5.3, "sepal_width":3.7, "petal_length":1.5, "petal_width":0.2}

2) 設定預測的環境變數:

INPUT_DATA_FILE="instances.json"

3) 執行預測:

gcloud ai-platform predict --model $MODEL_NAME --version $VERSION_NAME --json-instances $INPUT_DATA_FILE

訓練及部署 AutoML 分類器模型

請參閱下列各節,瞭解如何訓練及部署 AutoML 分類器模型。

訓練模型

使用 CREATE MODEL 陳述式,訓練可預測鳶尾花類型的 AutoML 分類器模型。AutoML 模型至少需要 1000 列輸入資料。由於 ml_datasets.iris 只有 150 個資料列,因此我們將資料複製 10 次。這項訓練工作大約需要 2 小時才能完成。

bq query --use_legacy_sql=false \
  'CREATE MODEL `bqml_tutorial.automl_iris_model`
  OPTIONS (model_type="automl_classifier",
      budget_hours=1, input_label_cols=["species"])
  AS SELECT
    * EXCEPT(multiplier)
  FROM
    `bigquery-public-data.ml_datasets.iris`, unnest(GENERATE_ARRAY(1, 10)) as multiplier;'

匯出模型

使用 bq 指令列工具將模型匯出至 Cloud Storage bucket。如需其他模型匯出方式,請參閱「匯出 BigQuery ML 模型」。

bq extract -m bqml_tutorial.automl_iris_model gs://some/gcs/path/automl_iris_model

在本機部署及提供服務

如要瞭解如何建構 AutoML 容器,請參閱「匯出模型」。下列步驟需要安裝 Docker

將匯出的模型檔案複製到本機目錄

mkdir automl_serving_dir
gcloud storage cp gs://some/gcs/path/automl_iris_model/* automl_serving_dir/ --recursive

提取 AutoML Docker 映像檔

docker pull gcr.io/cloud-automl-tables-public/model_server

啟動 Docker 容器

docker run -v `pwd`/automl_serving_dir:/models/default/0000001 -p 8080:8080 -it gcr.io/cloud-automl-tables-public/model_server

執行預測

1) 建立以換行符號分隔的輸入內容 JSON 檔案。舉例來說,input.json 檔案的內容如下:

{"instances": [{"sepal_length":5.0, "sepal_width":2.0, "petal_length":3.5, "petal_width":1.0},
{"sepal_length":5.3, "sepal_width":3.7, "petal_length":1.5, "petal_width":0.2}]}

2) 呼叫預測:

curl -X POST --data @input.json http://localhost:8080/predict

線上部署和供應

Vertex AI 不支援 AutoML 迴歸模型和 AutoML 分類器模型的線上預測。

清除所用資源

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

  • 您可以刪除建立的專案。
  • 或者,您也可以保留專案,但刪除資料集和 Cloud Storage 值區。

停止 Docker 容器

1) 列出所有執行中的 Docker 容器。

docker ps

2) 從容器清單中,找出適用的容器 ID 並停止容器。

docker stop container_id

刪除 Vertex AI 資源

1) 刪除模型版本。

gcloud ai-platform versions delete $VERSION_NAME --model=$MODEL_NAME

2) 刪除模型。

gcloud ai-platform models delete $MODEL_NAME

刪除資料集

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

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

    前往 BigQuery 頁面

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

  3. 按一下視窗右側的「刪除資料集」。 這個動作將會刪除資料集、資料表,以及所有資料。

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

刪除 Cloud Storage 值區

刪除專案會移除專案中的所有 Cloud Storage 值區。若您希望重新使用專案,可以刪除本教學課程中所建立的 bucket。

  1. 在 Google Cloud 控制台,前往「Cloud Storage bucket」頁面。

    前往「Buckets」(值區) 頁面

  2. 找到您要刪除的值區,並選取旁邊的核取方塊。

  3. 按一下 [Delete] (刪除)。

  4. 在出現的重疊視窗中,確認您要刪除的值區及內容,然後按一下 [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.

後續步驟