使用匯入的 TensorFlow 模型進行預測


在本教學課程中,您將 TensorFlow 模型匯入 BigQuery ML 資料集。接著,您可以使用 SQL 查詢,根據匯入的模型進行預測。

目標

  • 使用 CREATE MODEL 陳述式將 TensorFlow 模型匯入 BigQuery ML。
  • 使用 ML.PREDICT 函式,透過匯入的 TensorFlow 模型進行預測。

費用

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

您可以使用 Pricing Calculator 根據預測用量產生預估費用。 新 Google Cloud 使用者可能符合申請免費試用的資格。

完成本文件所述工作後,您可以刪除已建立的資源,避免繼續計費。詳情請參閱「清除所用資源」。

事前準備

  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. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

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

  5. 確認已啟用 BigQuery API。

    啟用 API

  6. 請確認您具備必要權限,才能執行本文所述的任務。
  7. 必要的角色

    如果您建立新專案,就會成為專案擁有者,並獲得完成本教學課程所需的所有必要身分和存取權管理 (IAM) 權限。

    如果您使用的是現有專案,則「BigQuery Studio 管理員」 (roles/bigquery.studioAdmin) 角色會授予完成本教學課程所需的所有權限。

    Make sure that you have the following role or roles on the project: BigQuery Studio Admin (roles/bigquery.studioAdmin).

    Check for the roles

    1. In the Google Cloud console, go to the IAM page.

      Go to IAM
    2. Select the project.
    3. In the Principal column, find all rows that identify you or a group that you're included in. To learn which groups you're included in, contact your administrator.

    4. For all rows that specify or include you, check the Role column to see whether the list of roles includes the required roles.

    Grant the roles

    1. In the Google Cloud console, go to the IAM page.

      前往「身分與存取權管理」頁面
    2. 選取專案。
    3. 按一下 「授予存取權」
    4. 在「New principals」(新增主體) 欄位中輸入使用者 ID。 通常是 Google 帳戶的電子郵件地址。

    5. 在「請選擇角色」清單中,選取角色。
    6. 如要授予其他角色,請按一下 「Add another role」(新增其他角色),然後新增其他角色。
    7. 按一下 [Save]
    8. 如要進一步瞭解 BigQuery 中的 IAM 權限,請參閱「BigQuery 權限」。

建立資料集

建立 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)

匯入 TensorFlow 模型

下列步驟說明如何從 Cloud Storage 匯入模型。模型的路徑為 gs://cloud-training-demos/txtclass/export/exporter/1549825580/*。匯入的模型名稱為 imported_tf_model

請注意,Cloud Storage URI 的結尾是萬用字元 (*)。這個字元表示 BigQuery ML 應匯入與模型相關聯的所有資產。

匯入的模型為 TensorFlow 文字分類程式模型,可預測發布特定文章標題的網站。

如要將 TensorFlow 模型匯入資料集,請按照下列步驟操作。

控制台

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

    前往「BigQuery」頁面

  2. 針對「建立新」,請點選「SQL 查詢」

  3. 在查詢編輯器中輸入以下 CREATE MODEL 陳述式,然後點選「Run」(執行)

      CREATE OR REPLACE MODEL `bqml_tutorial.imported_tf_model`
      OPTIONS (MODEL_TYPE='TENSORFLOW',
        MODEL_PATH='gs://cloud-training-demos/txtclass/export/exporter/1549825580/*')

    作業完成後,您應該會看到類似 Successfully created model named imported_tf_model 的訊息。

  4. 新模型會顯示在「資源」面板中。模型會以模型圖示 模型圖示 來表示。

  5. 如果您在「Resources」面板中選取新模型,「Query editor」下方就會顯示該模型的相關資訊。

    TensorFlow 模型資訊

bq

  1. 輸入以下 CREATE MODEL 陳述式,即可從 Cloud Storage 匯入 TensorFlow 模型。

    bq query --use_legacy_sql=false \
    "CREATE OR REPLACE MODEL
      `bqml_tutorial.imported_tf_model`
    OPTIONS
      (MODEL_TYPE='TENSORFLOW',
        MODEL_PATH='gs://cloud-training-demos/txtclass/export/exporter/1549825580/*')"
  2. 匯入模型後,請確認模型是否顯示在資料集中。

    bq ls bqml_tutorial

    輸出結果會與下列內容相似:

    tableId             Type
    ------------------- -------
    imported_tf_model   MODEL

API

插入新工作,並在要求主體中填入 jobs#configuration.query 屬性。

{
  "query": "CREATE MODEL `PROJECT_ID:bqml_tutorial.imported_tf_model` OPTIONS(MODEL_TYPE='TENSORFLOW' MODEL_PATH='gs://cloud-training-demos/txtclass/export/exporter/1549825580/*')"
}

PROJECT_ID 替換為專案和資料集的名稱。

BigQuery DataFrames

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

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

使用 TensorFlowModel 物件匯入模型。

import bigframes
from bigframes.ml.imported import TensorFlowModel

bigframes.options.bigquery.project = PROJECT_ID
# You can change the location to one of the valid locations: https://cloud.google.com/bigquery/docs/locations#supported_locations
bigframes.options.bigquery.location = "US"

imported_tensorflow_model = TensorFlowModel(
    model_path="gs://cloud-training-demos/txtclass/export/exporter/1549825580/*"
)

如要進一步瞭解如何將 TensorFlow 模型匯入至 BigQuery ML (包括格式和儲存空間需求),請參閱 CREATE MODEL 陳述式一文

使用匯入的 TensorFlow 模型進行預測

匯入 TensorFlow 模型後,您可以使用 ML.PREDICT 函式,透過模型進行預測。

以下查詢會使用 imported_tf_model,根據公開資料集 hacker_newsfull 資料表的輸入資料進行預測。在查詢中,TensorFlow 模型的 serving_input_fn 函式會指定模型預期一個名為 input 的輸入字串。子查詢會將別名 input 指派給子查詢 SELECT 陳述式中的 title 資料欄。

如要使用匯入的 TensorFlow 模型進行預測,請按照下列步驟操作。

控制台

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

    前往「BigQuery」頁面

  2. 在「建立新內容」下方,點選「SQL 查詢」

  3. 在查詢編輯器中輸入以下使用 ML.PREDICT 函式的查詢。

    SELECT *
      FROM ML.PREDICT(MODEL `bqml_tutorial.imported_tf_model`,
        (
         SELECT title AS input
         FROM bigquery-public-data.hacker_news.full
        )
    )

    查詢結果應如下所示:

    查詢結果

bq

輸入下列指令,執行使用 ML.PREDICT 的查詢。

bq query \
--use_legacy_sql=false \
'SELECT *
FROM ML.PREDICT(
  MODEL `bqml_tutorial.imported_tf_model`,
  (SELECT title AS input FROM `bigquery-public-data.hacker_news.full`))'

結果應如下所示:

+------------------------------------------------------------------------+----------------------------------------------------------------------------------+
|                               dense_1                                  |                                       input                                      |
+------------------------------------------------------------------------+----------------------------------------------------------------------------------+
|   ["0.6251608729362488","0.2989124357700348","0.07592673599720001"]    | How Red Hat Decides Which Open Source Companies t...                             |
|   ["0.014276246540248394","0.972910463809967","0.01281337533146143"]   | Ask HN: Toronto/GTA mastermind around side income for big corp. dev?             |
|   ["0.9821603298187256","1.8601855117594823E-5","0.01782100833952427"] | Ask HN: What are good resources on strategy and decision making for your career? |
|   ["0.8611106276512146","0.06648492068052292","0.07240450382232666"]   | Forget about promises, use harvests                                              |
+------------------------------------------------------------------------+----------------------------------------------------------------------------------+

API

插入新工作,並填入 jobs#configuration.query 屬性,如下列要求主體所示。將 project_id 替換為您的專案名稱。

{
  "query": "SELECT * FROM ML.PREDICT(MODEL `project_id.bqml_tutorial.imported_tf_model`, (SELECT * FROM input_data))"
}

BigQuery DataFrames

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

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

使用 predict 函式執行遠端模型:

import bigframes.pandas as bpd

df = bpd.read_gbq("bigquery-public-data.hacker_news.full")
df_pred = df.rename(columns={"title": "input"})
predictions = imported_tensorflow_model.predict(df_pred)
predictions.head(5)

結果應如下所示:

Result_visualization

在查詢結果中,dense_1 資料欄包含機率值陣列,input 資料欄則包含輸入資料表中的對應字串值。每個陣列元素值表示相應輸入字串是某出版內容中的文章標題的機率。

清除所用資源

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

刪除專案

控制台

  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.

gcloud

    Delete a Google Cloud project:

    gcloud projects delete PROJECT_ID

刪除個別資源

或者,您也可以移除本教學課程中使用的個別資源:

  1. 刪除匯入的模型

  2. 選用步驟:刪除資料集

後續步驟