使用预训练的 TensorFlow 模型嵌入文本
本教程介绍如何使用预训练的 TensorFlow 模型在 BigQuery 中生成 NNLM、SWIVEL 和 BERT 文本嵌入。文本嵌入是一段文本的密集矢量表示,如果两段文本在语义上是相似的,则它们的嵌入在嵌入向量空间中彼此接近。
NNLM、SWIVEL 和 BERT 模型
NNLM、SWIVEL 和 BERT 模型的大小、准确性、可扩缩性和费用各不相同。使用下表帮助您确定要使用的模型:
| 模型 | 模型大小 | 嵌入维度 | 使用场景 | 说明 | 
|---|---|---|---|---|
| NNLM | <150MB | 50 | 简短短语、新闻、推文、评价 | 神经网络语言模型 | 
| SWIVEL | <150MB | 20 | 简短短语、新闻、推文、评价 | 子矩阵矢量嵌入学习器 | 
| BERT | ~200MB | 768 | 简短短语、新闻、推文、评价、短段落 | 基于转换器的双向编码器表示法 | 
在本教程中,NNLM 和 SWIVEL 模型是导入的 TensorFlow 模型,而 BERT 模型是 Vertex AI 上的远程模型。
所需权限
- 如需创建数据集,您需要拥有 - bigquery.datasets.createIdentity and Access Management (IAM) 权限。
- 如需创建存储桶,您需要拥有 - storage.buckets.createIAM 权限。
- 如需将模型上传到 Cloud Storage,您需要拥有 - storage.objects.create和- storage.objects.getIAM 权限。
- 如需创建连接资源,您需要以下 IAM 权限: - bigquery.connections.create
- bigquery.connections.get
 
- 如需将模型加载到 BigQuery ML 中,您需要以下 IAM 权限: - bigquery.jobs.create
- bigquery.models.create
- bigquery.models.getData
- bigquery.models.updateData
 
- 如需运行推断,您需要以下 IAM 权限: - 对象表的 bigquery.tables.getData权限
- 模型的 bigquery.models.getData权限
- bigquery.jobs.create
 
- 对象表的 
费用
在本文档中,您将使用 Google Cloud的以下收费组件:
- BigQuery: You incur costs for the queries that you run in BigQuery.
- BigQuery ML: You incur costs for the model that you create and the inference that you perform in BigQuery ML.
- Cloud Storage: You incur costs for the objects that you store in Cloud Storage.
- Vertex AI: If you follow the instructions for generating the BERT model, then you incur costs for deploying the model to an endpoint.
 
 
 
  如需根据您的预计使用量来估算费用,请使用价格计算器。
  
如需了解详情,请参阅以下资源:
准备工作
- 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.
- 
    
    
      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
      (roles/resourcemanager.projectCreator), which contains theresourcemanager.projects.createpermission. Learn how to grant roles.
 
- 
  
    Verify that billing is enabled for your Google Cloud project. 
- 
  
  
    
      Enable the BigQuery, BigQuery Connection, and Vertex AI APIs. Roles required to enable APIs To enable APIs, you need the Service Usage Admin IAM role ( roles/serviceusage.serviceUsageAdmin), which contains theserviceusage.services.enablepermission. Learn how to grant roles.
- 
    
    
      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
      (roles/resourcemanager.projectCreator), which contains theresourcemanager.projects.createpermission. Learn how to grant roles.
 
- 
  
    Verify that billing is enabled for your Google Cloud project. 
- 
  
  
    
      Enable the BigQuery, BigQuery Connection, and Vertex AI APIs. Roles required to enable APIs To enable APIs, you need the Service Usage Admin IAM role ( roles/serviceusage.serviceUsageAdmin), which contains theserviceusage.services.enablepermission. Learn how to grant roles.
- 在 Google Cloud 控制台中,前往 BigQuery 页面。 
- 在查询编辑器中,输入以下语句: - CREATE SCHEMA `PROJECT_ID.tf_models_tutorial`; - 将 - PROJECT_ID替换为您的项目 ID。
- 点击 运行。 
- 在 Google Cloud 控制台中,激活 Cloud Shell。 
- 如需创建数据集,请运行 - bq mk命令:- bq mk --dataset --location=us PROJECT_ID:tf_models_tutorial - 将 - PROJECT_ID替换为您的项目 ID。
- 使用 pip 安装 - bigquery-ml-utils库:- pip install bigquery-ml-utils
- 生成 NNLM 模型。以下 Python 代码从 TensorFlow Hub 加载了 NNLM 模型,并为其准备了 BigQuery: - from bigquery_ml_utils import model_generator import tensorflow_text # Establish an instance of TextEmbeddingModelGenerator. text_embedding_model_generator = model_generator.TextEmbeddingModelGenerator() # Generate an NNLM model. text_embedding_model_generator.generate_text_embedding_model('nnlm', OUTPUT_MODEL_PATH)- 将 - OUTPUT_MODEL_PATH替换为本地文件夹的路径,您可以在其中临时存储模型。
- 可选:输出生成的模型的签名: - import tensorflow as tf reload_embedding_model = tf.saved_model.load(OUTPUT_MODEL_PATH) print(reload_embedding_model.signatures["serving_default"])
- 如需将生成的模型从本地文件夹复制到 Cloud Storage 存储桶,请使用 Google Cloud CLI: - gcloud storage cp OUTPUT_MODEL_PATH gs://BUCKET_PATH/nnlm_model --recursive- 将 - BUCKET_PATH替换为要将模型复制到的 Cloud Storage 存储桶的名称。
- 使用 pip 安装 - bigquery-ml-utils库:- pip install bigquery-ml-utils
- 生成 SWIVEL 模型。以下 Python 代码从 TensorFlow Hub 加载 SWIVEL 模型,并为其准备 BigQuery: - from bigquery_ml_utils import model_generator import tensorflow_text # Establish an instance of TextEmbeddingModelGenerator. text_embedding_model_generator = model_generator.TextEmbeddingModelGenerator() # Generate a SWIVEL model. text_embedding_model_generator.generate_text_embedding_model('swivel', OUTPUT_MODEL_PATH)- 将 - OUTPUT_MODEL_PATH替换为本地文件夹的路径,您可以在其中临时存储模型。
- 可选:输出生成的模型的签名: - import tensorflow as tf reload_embedding_model = tf.saved_model.load(OUTPUT_MODEL_PATH) print(reload_embedding_model.signatures["serving_default"])
- 如需将生成的模型从本地文件夹复制到 Cloud Storage 存储桶,请使用 Google Cloud CLI: - gcloud storage cp OUTPUT_MODEL_PATH gs://BUCKET_PATH/swivel_model --recursive- 将 - BUCKET_PATH替换为要将模型复制到的 Cloud Storage 存储桶的名称。
- 使用 pip 安装 - bigquery-ml-utils库:- pip install bigquery-ml-utils
- 生成 BERT 模型。以下 Python 代码从 TensorFlow Hub 加载 BERT 模型,并为其准备了 BigQuery: - from bigquery_ml_utils import model_generator import tensorflow_text # Establish an instance of TextEmbeddingModelGenerator. text_embedding_model_generator = model_generator.TextEmbeddingModelGenerator() # Generate a BERT model. text_embedding_model_generator.generate_text_embedding_model('bert', OUTPUT_MODEL_PATH)- 将 - OUTPUT_MODEL_PATH替换为本地文件夹的路径,您可以在其中临时存储模型。
- 可选:输出生成的模型的签名: - import tensorflow as tf reload_embedding_model = tf.saved_model.load(OUTPUT_MODEL_PATH) print(reload_embedding_model.signatures["serving_default"])
- 如需将生成的模型从本地文件夹复制到 Cloud Storage 存储桶,请使用 Google Cloud CLI: - gcloud storage cp OUTPUT_MODEL_PATH gs://BUCKET_PATH/bert_model --recursive- 将 - BUCKET_PATH替换为要将模型复制到的 Cloud Storage 存储桶的名称。
- 在 Google Cloud 控制台中,前往 BigQuery 页面。 
- 在查询编辑器中,输入以下语句: - CREATE OR REPLACE MODEL - tf_models_tutorial.nnlm_modelOPTIONS ( model_type = 'TENSORFLOW', model_path = 'gs://BUCKET_NAME/nnlm_model/*');- 将 - BUCKET_NAME替换为您之前创建的存储桶的名称。
- 点击 运行。 
- 在 Google Cloud 控制台中,前往 BigQuery 页面。 
- 在查询编辑器中,输入以下语句: - CREATE OR REPLACE MODEL - tf_models_tutorial.swivel_modelOPTIONS ( model_type = 'TENSORFLOW', model_path = 'gs://BUCKET_NAME/swivel_model/*');- 将 - BUCKET_NAME替换为您之前创建的存储桶的名称。
- 点击 运行。 
- 在 Google Cloud 控制台中,前往 Vertex AI Model Registry 页面。 
- 点击导入,然后执行以下操作: - 对于名称,输入 BERT。
- 对于区域,选择与您的 Cloud Storage 存储桶的区域匹配的区域。
 
- 对于名称,输入 
- 点击继续,然后执行以下操作: - 对于模型框架版本,选择 2.8。
- 对于模型工件位置,输入您存储模型文件的 Cloud Storage 存储桶的路径。例如 gs://BUCKET_PATH/bert_model。
 
- 对于模型框架版本,选择 
- 点击导入。导入完成后,您的模型将显示在 Model Registry 页面上。 
- 在 Google Cloud 控制台中,前往 Vertex AI Model Registry 页面。 
- 点击您的模型的名称。 
- 点击部署和测试。 
- 点击部署到端点。 
- 对于端点名称,输入 - bert_model_endpoint。
- 点击继续。 
- 选择您的计算资源。 
- 点击部署。 
- 创建 BigQuery Cloud 资源连接并向该连接的服务账号授予访问权限。 
- 在 Google Cloud 控制台中,前往 BigQuery 页面。 
- 在查询编辑器中,输入以下语句: - CREATE OR REPLACE MODEL - tf_models_tutorial.bert_modelINPUT(- contentSTRING) OUTPUT(- embedding- ARRAY<FLOAT64>) REMOTE WITH CONNECTION `PROJECT_ID.CONNECTION_LOCATION.CONNECTION_ID` OPTIONS ( ENDPOINT = "https://ENDPOINT_LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/ENDPOINT_LOCATION/endpoints/ENDPOINT_ID");- 请替换以下内容: - PROJECT_ID:项目 ID
- CONNECTION_LOCATION:BigQuery 连接的位置
- CONNECTION_ID:BigQuery 连接的 ID- 当您在 Google Cloud 控制台中查看连接详细信息时,这是连接 ID 中显示的完全限定连接 ID 的最后一部分中的值,例如 - projects/myproject/locations/connection_location/connections/myconnection
- ENDPOINT_LOCATION:Vertex AI 端点的位置。例如:“us-central1”。
- ENDPOINT_ID:模型端点的 ID
 
- 点击 运行。 
- In the Google Cloud console, go to the Manage resources page.
- In the project list, select the project that you want to delete, and then click Delete.
- In the dialog, type the project ID, and then click Shut down to delete the project.
创建数据集
如需创建名为 tf_models_tutorial 的数据集以存储您创建的模型,请选择以下选项之一:
SQL
使用 CREATE SCHEMA 语句:
如需详细了解如何运行查询,请参阅运行交互式查询。
bq
生成模型并将其上传到 Cloud Storage
如需详细了解如何使用预训练的 TensorFlow 模型生成文本嵌入,请参阅 Colab 笔记本。否则,请选择以下模型之一:
NNLM
SWIVEL
BERT
将模型加载到 BigQuery 中
选择以下模型之一:
NNLM
使用 CREATE MODEL 语句:
如需详细了解如何运行查询,请参阅运行交互式查询。
SWIVEL
使用 CREATE MODEL 语句:
如需详细了解如何运行查询,请参阅运行交互式查询。
BERT
如需将 BERT 模型加载到 BigQuery,请将 BERT 模型导入 Vertex AI,将模型部署到 Vertex AI 端点,创建连接,然后在 BigQuery 中创建远程模型。
如需将 BERT 模型导入 Vertex AI,请按照以下步骤操作:
如需将 BERT 模型部署到 Vertex AI 端点并将其连接到 BigQuery,请按照以下步骤操作:
如需根据 Vertex AI 端点创建远程模型,请使用 CREATE MODEL 语句:
如需详细了解如何运行查询,请参阅运行交互式查询。
生成文本嵌入
在本部分中,您将使用 ML.PREDICT() 推断函数从公共数据集 bigquery-public-data.imdb.reviews 生成 review 列的文本嵌入。该查询将表限制为 500 行,以减少处理的数据量。
NNLM
SELECT * FROM ML.PREDICT( MODEL `tf_models_tutorial.nnlm_model`, ( SELECT review AS content FROM `bigquery-public-data.imdb.reviews` LIMIT 500) );
结果类似于以下内容:
+-----------------------+----------------------------------------+ | embedding | content | +-----------------------+----------------------------------------+ | 0.08599445223808289 | Isabelle Huppert must be one of the... | | -0.04862852394580841 | | | -0.017750458791851997 | | | 0.8658871650695801 | | | ... | | +-----------------------+----------------------------------------+
SWIVEL
SELECT * FROM ML.PREDICT( MODEL `tf_models_tutorial.swivel_model`, ( SELECT review AS content FROM `bigquery-public-data.imdb.reviews` LIMIT 500) );
结果类似于以下内容:
+----------------------+----------------------------------------+ | embedding | content | +----------------------+----------------------------------------+ | 2.5952553749084473 | Isabelle Huppert must be one of the... | | -4.015787601470947 | | | 3.6275434494018555 | | | -6.045154333114624 | | | ... | | +----------------------+----------------------------------------+
BERT
SELECT * FROM ML.PREDICT( MODEL `tf_models_tutorial.bert_model`, ( SELECT review AS content FROM `bigquery-public-data.imdb.reviews` LIMIT 500) );
结果类似于以下内容:
+--------------+---------------------+----------------------------------------+ | embedding | remote_model_status | content | +--------------+---------------------+----------------------------------------+ | -0.694072425 | null | Isabelle Huppert must be one of the... | | 0.439208865 | | | | 0.99988997 | | | | -0.993487895 | | | | ... | | | +--------------+---------------------+----------------------------------------+