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 執行個體
- 在 Google Cloud 控制台的專案選取器頁面中,選取或建立 Google Cloud 專案。
- 前往專案選取器
- 請確認 Google Cloud 專案已啟用計費功能。
- 啟用 Notebooks API。
您可以使用 Google Cloud 控制台、gcloud CLI 或 Terraform 建立 Vertex AI Workbench 執行個體。為了配合本教學課程,我們將使用 Google Cloud 控制台建立這個專案。如要進一步瞭解其他方法,請參閱這篇文章。
- 在 Google Cloud 控制台中,前往「執行個體」頁面,可在「Vertex AI」選單的「筆記本」專區中找到,然後按一下「Workbench」。
- 前往「Instances」(執行個體)。
- 按一下「新建」。
- 在「Create instance」對話方塊的「Details」部分,為新執行個體提供下列資訊:
名稱:提供新執行個體的名稱。名稱開頭須為英文字母,後面最多可接 62 個小寫英文字母、數字或連字號 (-),但結尾不得為連字號。
區域和可用區:選取新執行個體的區域和可用區。為取得最佳網路效能,請選取最靠近您所在地理位置的區域。
不需要安裝 GPU
在「Networking」(網路) 部分提供下列資訊:
網路:調整網路選項,以便使用目前專案中的網路,或主專案中的共用虛擬私人雲端網路 (如果已設定)。如果在主專案中使用共用虛擬私有雲,您必須為服務專案中的 Notebooks Service Agent 授予 Compute 網路使用者角色 (roles/compute.networkUser)。
在「Network」欄位中:選取所需網路。您可以選取虛擬私人雲端網路,只要該網路已啟用私人 Google 存取權或可以存取網際網路即可
在「子網路」欄位中:選取所需子網路。您可以選擇預設值。
在執行個體的屬性中,您可以保留預設值,也就是 e2-standard-4。
- 按一下「建立」。
Vertex AI Workbench 會建立執行個體並自動啟動。執行個體可供使用時,Vertex AI Workbench 會啟用「Open JupyterLab」(開啟 JupyterLab) 連結。按一下該按鈕。
建立 Python 3 筆記本
- 在 Jupyterlab 中,從啟動器的「Notebook」部分,按一下 Python 標誌圖示,該圖示上會顯示「Python3」。
- 系統會建立名為「Untitled」且副檔名為「ipynb」的 Jupyter 筆記本。
- 您可以使用左側的檔案瀏覽器區段重新命名檔案,也可以保留原始名稱。
接下來,我們可以開始在筆記本中輸入程式碼。
3. 匯入必要的程式庫
建立執行個體並開啟 JupyterLab 後,我們需要安裝程式碼研究室所需的所有程式庫。
我們需要:
- numpy
- pandas
- 來自 vertexai.language_models 的 TextEmbeddingInput、TextEmbeddingModel
複製並貼入下列程式碼:
from vertexai.language_models import TextEmbeddingInput, TextEmbeddingModel
import numpy as np
import pandas as pd
網址看起來會像這樣:
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
如下所示:
讓我們分析程式碼
在變數 DOCUMENT1、DOCUMENT2 和 DOCUMENT3 中,我們會儲存字典,以模擬含有標題和內容的文件。這些「文件」是指 Google 製造車輛的模擬手冊。
在下一行中,我們會根據這 3 份文件 (字典) 建立清單。
documents = [DOCUMENT1, DOCUMENT2, DOCUMENT3]
最後,我們利用 pandas 從該清單建立資料框架,並將其命名為 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
如下所示:
分析程式碼
我們定義了名為 embed_fn 的函式,該函式會接收 pandas 資料框架做為輸入內容,其中包含要執行嵌入的文字。函式會傳回以向量編碼的文字。
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 函式擷取傳送的文字向量。
在函式結尾,我們會在資料框架中建立名為「Embedded text」的新欄,其中包含根據 gecko@003 模型建立的向量清單。
df_input['Embedded text'] = list_embedded_values
return df_input
最後,我們會在 df_embedded_values_db 變數中擷取資料框架,其中包含模擬資料庫的原始資料,以及包含每個資料列向量清單的新資料欄。
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)
結果如下所示:
讓我們分析程式碼
與上一個步驟的函式類似,我們會先初始化問題變數,並將要向資料庫提出的問題填入其中。
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 範數。
在 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}')
結果看起來會像這樣:
讓我們分析程式碼
我們會先將資料庫中用於儲存嵌入文字或向量的資料欄轉換為清單,並儲存在 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'])
執行後,您會看到類似以下的內容:
9. 恭喜
恭喜,您已成功在實際用途中使用 textembedding-gecko@003 模型建構第一個應用程式!
您已瞭解文字嵌入的基礎知識,以及如何在 GCP Workbench 上使用 gecko003 模型。
您現在已瞭解如何繼續將所學知識應用於更多用途的重要步驟。
後續步驟
查看一些程式碼研究室…