針對向量嵌入使用 textembedding-gecko@003

1. 簡介

上次更新時間:2024 年 4 月 8 日

文字嵌入

文字嵌入是指將文字資料轉換為數值表示法的程序。這些數值表示法通常是向量,可擷取文字中的語意意義和字詞之間的關係。想像一下:

文字就像複雜的語言,充滿細微差異和模糊之處。

文字嵌入功能會將該語言轉換為電腦可解讀及操作的簡單數學格式。

文字嵌入的優點

  • 可實現高效率的處理:與原始文字相比,電腦處理數值表示法時的速度會快得多。這對於搜尋引擎、推薦系統和機器翻譯等工作至關重要。
  • 擷取語意含義:嵌入功能不侷限於字詞的字義。這些模型可擷取字詞之間的背景資訊和關係,進行更精細的分析。
  • 改善機器學習成效:文字嵌入資料可用於機器學習模型中的特徵,有助於改善情緒分析、文字分類和主題建模等任務的成效。

文字嵌入的用途

文字嵌入會將文字轉換為數值表示法,進而開啟自然語言處理 (NLP) 的各種應用。以下是一些主要用途:

1. 搜尋引擎和資訊擷取:

文字嵌入可讓搜尋引擎瞭解查詢背後的語意,並與相關文件進行比對,即使沒有出現確切關鍵字也沒關係。

搜尋引擎能將搜尋查詢的嵌入與文件嵌入進行比較,找出包含類似主題或概念的文件。

2. 推薦系統:

推薦系統會使用文字嵌入,分析使用者透過評論、評分或瀏覽記錄表達的行為和偏好。

這樣一來,系統就會比較使用者所互動的產品、文章或其他內容的嵌入項目,藉此推薦類似項目。

3. 抄襲偵測:

比較兩段文字的嵌入資料,可以找出兩者語意結構中的顯著相似之處,進而識別潛在的抄襲行為。

以上只是其中幾個例子,隨著文字嵌入技術的演進,應用範圍將持續擴大。隨著電腦透過嵌入法更瞭解語言,我們可以預期未來會有更多創新的應用程式。

textembedding-gecko@003

Textembedding-gecko@003 是 Google Cloud Platform (GCP) 透過 Vertex AI 和 AI 工具與服務套件提供的預先訓練文字嵌入模型的特定版本。

建構項目

在本程式碼研究室中,您將建構 Python 指令碼。這個指令碼將:

  • 使用 Vertex API 呼叫 textembedding-gecko@003,並將文字轉換為文字嵌入 (向量)。
  • 建立由文字和向量組成的模擬資料庫
  • 比較向量並取得最可能的回應,對模擬向量資料庫執行查詢。

課程內容

  • 如何在 GCP 中使用文字嵌入
  • 如何呼叫 textembedding-gecko@003
  • 如何在 Workbench 中執行這個程式碼
  • 如何使用 Vertex AI - Workbench 執行指令碼

軟硬體需求

  • 最新版 Chrome
  • 具備 Python 相關知識
  • Google Cloud 專案
  • 存取 Vertex AI - Workbench

2. 開始設定

建立 Vertex AI Workbench 執行個體

  1. 在 Google Cloud 控制台的專案選取器頁面中,選取或建立 Google Cloud 專案。
  1. 前往專案選取器
  2. 請確認 Google Cloud 專案已啟用計費功能。
  3. 啟用 Notebooks API。

您可以使用 Google Cloud 控制台、gcloud CLI 或 Terraform 建立 Vertex AI Workbench 執行個體。為配合本教學課程,我們將使用 Google Cloud 控制台建立。如要進一步瞭解其他方法,請參閱這篇文章

  1. 前往 Google Cloud 控制台,前往「Vertex AI」選單的「Notebooks」部分前往「執行個體」頁面,然後按一下「Workbench」。56c087d619c464dd.png
  2. 前往「執行個體」頁面。
  3. 按一下「新建」。381ff9b895e77641.png
  4. 在「Create instance」對話方塊的「Details」部分,為新執行個體提供下列資訊:

「Name」(名稱):提供新執行個體的名稱。名稱開頭須為英文字母,後面最多可接 62 個小寫英文字母、數字或連字號 (-),但結尾不得為連字號。

區域和可用區:選取新執行個體的區域和可用區。如要獲得最佳網路效能,請選取離您最近的地區。

不必安裝 GPU

在「Networking」(網路) 部分提供下列資訊:

網路:調整網路選項,以便使用目前專案中的網路,或是主專案中的共用虛擬私有雲網路 (如有設定)。如果在主專案中使用共用虛擬私有雲,您必須為服務專案中的 Notebooks Service Agent 授予 Compute 網路使用者角色 (roles/compute.networkUser)。

在「Network」欄位中:選取所需網路。您可以選取虛擬私人雲端網路,只要該網路已啟用私人 Google 存取權或可以存取網際網路即可

在「子網路」欄位中:選取所需子網路。您可以選擇預設語言。

在執行個體的屬性中,您可以保留預設值,也就是 e2-standard-4。

d47bdc2d7f516c46.png

  1. 按一下「建立」。

Vertex AI Workbench 會建立執行個體並自動啟動。執行個體可供使用時,Vertex AI Workbench 會啟用「開啟 JupyterLab」連結。按一下該按鈕。

建立 Python 3 筆記本

  1. 在 JupyterLab 中,從啟動器的「Notebook」部分,按一下 Python 標誌的圖示,該圖示上會顯示「Python3」。e16bb118cd28256f.png
  2. 系統會建立名為「Untitled」且副檔名為「ipynb」的 Jupyter 筆記本。da9bd34cf307156c.png
  3. 你可以使用左側的檔案瀏覽器部分重新命名,也可以保留原本的設定。

現在,我們可以開始將程式碼放入筆記本了。

3. 匯入必要的程式庫

建立執行個體並開啟 JupyterLab 後,我們需要安裝程式碼研究室所需的所有程式庫。

我們需要:

  1. numpy
  2. pandas
  3. 來自 vertexai.language_models 的 TextEmbeddingInput、TextEmbeddingModel

複製以下程式碼並貼到儲存格中:

from vertexai.language_models import TextEmbeddingInput, TextEmbeddingModel

import numpy as np
import pandas as pd

網址看起來會像這樣:

6852d323eedcac93.png

4. 建立模擬向量資料庫

為了測試程式碼,我們會建立一個資料庫,其中包含文字和使用 gecko@003 文字嵌入模型轉譯的文字對應向量。

目標是讓使用者搜尋文字、將文字轉換為向量,然後在資料庫中搜尋,並傳回最接近的結果。

我們的向量資料庫將保留 3 個記錄,我們會以以下方式建立資料庫:

複製以下程式碼並貼到新的儲存格中。

DOCUMENT1 = {
    "title": "Operating the Climate Control System",
    "content": "Your Googlecar has a climate control system that allows you to adjust the temperature and airflow in the car. To operate the climate control system, use the buttons and knobs located on the center console.  Temperature: The temperature knob controls the temperature inside the car. Turn the knob clockwise to increase the temperature or counterclockwise to decrease the temperature. Airflow: The airflow knob controls the amount of airflow inside the car. Turn the knob clockwise to increase the airflow or counterclockwise to decrease the airflow. Fan speed: The fan speed knob controls the speed of the fan. Turn the knob clockwise to increase the fan speed or counterclockwise to decrease the fan speed. Mode: The mode button allows you to select the desired mode. The available modes are: Auto: The car will automatically adjust the temperature and airflow to maintain a comfortable level. Cool: The car will blow cool air into the car. Heat: The car will blow warm air into the car. Defrost: The car will blow warm air onto the windshield to defrost it."}

DOCUMENT2 = {
    "title": "Touchscreen",
    "content": "Your Googlecar has a large touchscreen display that provides access to a variety of features, including navigation, entertainment, and climate control. To use the touchscreen display, simply touch the desired icon.  For example, you can touch the \"Navigation\" icon to get directions to your destination or touch the \"Music\" icon to play your favorite songs."}

DOCUMENT3 = {
    "title": "Shifting Gears",
    "content": "Your Googlecar has an automatic transmission. To shift gears, simply move the shift lever to the desired position.  Park: This position is used when you are parked. The wheels are locked and the car cannot move. Reverse: This position is used to back up. Neutral: This position is used when you are stopped at a light or in traffic. The car is not in gear and will not move unless you press the gas pedal. Drive: This position is used to drive forward. Low: This position is used for driving in snow or other slippery conditions."}

documents = [DOCUMENT1, DOCUMENT2, DOCUMENT3]

df_initial_db = pd.DataFrame(documents)
df_initial_db.columns = ['Title', 'Text']
df_initial_db

程式碼應會如下所示:

26baa3b876c0605d.png

分析程式碼

在變數 DOCUMENT1、DOCUMENT2 和 DOCUMENT3 中,我們會儲存字典,以模擬含有標題和內容的文件。這些「文件」參考 Google 製造的模擬手冊

下一行中,我們從這 3 份文件 (字典) 中建立清單。

documents = [DOCUMENT1, DOCUMENT2, DOCUMENT3]

最後,利用 pandas,我們從該清單建立 DataFrame,稱為 df_initial_db。

df_initial_db = pd.DataFrame(documents)
df_initial_db.columns = ['Title', 'Text']
df_initial_db

5. 建立文字嵌入

我們現在會針對模擬文件資料庫中的每筆記錄,使用 gecko@003 模型取得文字嵌入。

複製以下程式碼並貼到新的儲存格中:

def embed_fn(df_input):
    list_embedded_values = []
    for index, row in df_input.iterrows():        
        model = TextEmbeddingModel.from_pretrained("textembedding-gecko@003")
        embeddings = model.get_embeddings([(row['Text'])])        
        list_embedded_values.append(embeddings[0].values)
    df_input['Embedded text'] = list_embedded_values
    return df_input        
                                           
df_embedded_values_db = embed_fn(df_initial_db)
df_embedded_values_db      

程式碼應會如下所示:

4c4af091c7a82861.png

分析程式碼

我們定義了名為「embed_fn」的函式,該函式會接收為含有要執行嵌入之文字的 pandas DataFrame 輸入內容。接著,函式會傳回編碼為向量的文字。

def embed_fn(df_input):
    list_embedded_values = []
    for index, row in df_input.iterrows():        
        model = TextEmbeddingModel.from_pretrained("textembedding-gecko@003")
        embeddings = model.get_embeddings([(row['Text'])])        
        list_embedded_values.append(embeddings[0].values)
    df_input['Embedded text'] = list_embedded_values
    return df_input             

在名為 list_embedded_values 的清單中,我們會儲存並附加每列的編碼文字。

我們可以使用 pandas 的 iterrows 方法,對資料框架中的每個資料列進行疊代,從 Text 資料欄 (內含模擬資料庫的手動資訊) 取得值。

為了傳送一般文字並使用 gecko@003 模型傳回其向量,我們會初始化變數模型,並透過呼叫 TextEmbeddingModel.from_pretrained 函式,設定要使用的模型。

model = TextEmbeddingModel.from_pretrained("textembedding-gecko@003")
embeddings = model.get_embeddings([(row['Text'])])                     

接著,我們會在變數嵌入中,透過 model.get_embeddings 函式擷取傳送的文字向量。

在函式結尾,我們會在 DataFrame 中建立名為「嵌入的文字」的新資料欄,其中會包含根據 gecko@003 模型建立的向量清單。

df_input['Embedded text'] = list_embedded_values
return df_input             

最後,在 df_embedded_values_db 變數中,我們會擷取含有模擬資料庫原始資料的 DataFrame,再加入一個新資料欄,其中含有每個資料列的向量清單。

df_embedded_values_db = embed_fn(df_initial_db)
df_embedded_values_db      

6. 向向量資料庫提問

現在,我們的資料庫包含文字及其向量,接著就能提出問題,然後查詢我們的資料庫,找出解答。

為此,請複製以下程式碼並貼到新儲存格中:

question='How do you shift gears in the Google car?'
model = TextEmbeddingModel.from_pretrained("textembedding-gecko@003")
embeddings = model.get_embeddings([(question)])        
text_to_search=embeddings[0].values
len(text_to_search)

結果如下所示:

6b7cf9b08e3b4573.png

分析程式碼

與上一步驟中的函式類似,我們會先使用我們想詢問資料庫的內容,初始化問題變數。

question='How do you shift gears in the Google car?'

接著,我們會透過 TextEmbeddingModel.from_pretrained 函式,在模型變數中設定要使用的模型,在本例中為 gecko@003 模型。

model = TextEmbeddingModel.from_pretrained("textembedding-gecko@003")

在 embeddings 變數中,我們呼叫 model.get_embeddings 函式,並傳遞要轉換為向量的文字,在本例中,我們會傳遞要詢問的問題。

embeddings = model.get_embeddings([(question)])        

最後,text_to_search 變數會列出從題目翻譯的向量清單。

我們會列印向量長度做為參照。

text_to_search=embeddings[0].values
len(text_to_search)

7. 比較向量

現在我們已在模擬的資料庫中取得向量清單,並在一個將問題轉換成向量問題後找到。也就是說,我們現在可以將問題的向量與資料庫中的所有向量進行比較,找出最接近問題答案的向量。

為此,我們會測量題型與資料庫各向量之間的距離。有多種方法可用來測量向量之間的距離,在本程式碼研究室中,我們將使用歐幾里得距離或 L2 範數。

73ea8635c4570bea.png

在 Python 中,我們可以利用 numpy 函式來完成這項操作。

複製並貼上以下程式碼到新儲存格中:

list_embedded_text_from_db = df_embedded_values_db['Embedded text']
shortest_distance=1
for position, embedded_value in enumerate(list_embedded_text_from_db):
    distance=np.linalg.norm((np.array(embedded_value) - np.array(text_to_search)), ord = 2)
    print(distance)
    if distance<shortest_distance:
        shortest_distance=distance
        shortest_position=position
        
print(f'The shortest distance is {shortest_distance} and the position of that value is {shortest_position}')

結果看起來會像這樣:

b70563b50ea86668.png

我們來分析程式碼

我們會先將資料庫中用於儲存嵌入文字或向量的資料欄轉換為清單,並儲存在 list_embedded_text_from_db 中。

我們也將 shortest_distance 變數初始化為 1,以便持續更新,直到找到實際的最短距離為止。

list_embedded_text_from_db = df_embedded_values_db['Embedded text']
shortest_distance=1

然後,使用 FOR 迴圈,系統會反覆執行運算,並從問題中取得向量與資料庫中每個向量之間的距離。

我們使用 numpy linalg.norm 函式計算距離。

如果計算出的距離小於 shortest_distance 變數中的距離,系統會將計算出的距離設為這個變數

接著,我們擷取最短距離,以及該物件在清單中所發現的位置。在 shortest_distance 和 shortest_position 變數中。

for position, embedded_value in enumerate(list_embedded_text_from_db):
    distance=np.linalg.norm((np.array(embedded_value) - np.array(text_to_search)), ord = 2)
    print(distance)
    if distance<shortest_distance:
        shortest_distance=distance
        shortest_position=position

8. 結果

只要知道向量清單中,與問題和資料庫之間最短距離的向量位置,就可以列印結果。

複製以下程式碼並貼到新的儲存格中:

print("Your question was:\n "+question+ " \nAnd our answer is:\n "+
      df_embedded_values_db.at[shortest_position, 'Title']+": "+
      df_embedded_values_db.at[shortest_position, 'Text'])

執行後,您會看到類似以下的內容:

7a0e429171a19afe.png

9. 恭喜

恭喜,您已成功在實際用途中使用 textembedding-gecko@003 模型建構第一個應用程式!

您已瞭解文字嵌入的基礎知識,以及如何在 GCP Workbench 上使用 gecko003 模型。

您現已瞭解必須完成哪些重要步驟,才能持續將知識運用於更多應用情境。

後續步驟

查看一些程式碼研究室…

參考文件