fastText 與 Hugging Face Hub 整合

Hugging Face 已將 fastText 模型的官方鏡像整合到 Hugging Face Hub,提供對 157 種語言的詞向量以及一個專門的語言識別模型的便捷存取。此整合使開發者能夠使用 huggingface_hub 庫下載並部署這些可擴展的文本表示和分類工具。

fastText 技術架構

fastText 由 Meta AI 在 2016 年首次開源,旨在實現高效的文本表示與分類。它採用了幾項關鍵的 NLP 技術來實現可擴展性和性能:

  • Subword Information: 該庫利用次詞資訊來改進文本表示。
  • N-gram Representation: 句子使用詞袋和 n-gram 袋來表示。
  • Hidden Representations: 它使用隱藏表示來跨不同類別共享資訊。
  • Hierarchical Softmax: 為了優化計算速度,fastText 實施了層次式 softmax,利用類別分布的不平衡。

Hub 整合與模型可用性

這些模型的官方鏡像託管在 Hugging Face Hub 的 Meta AI 組織下。此整合提供兩個主要類別的模型:

  1. Word Vectors: 157 種不同語言的預訓練詞向量。
  2. Language Identification: 用於檢測給定文本語言的專用模型。

為了方便測試,Hugging Face 在模型頁面直接加入了文本分類和特徵提取小工具的支援,使用戶能夠在瀏覽器中與語言識別和詞向量模型進行互動。

實作與使用

使用者可以使用 huggingface_hub 庫的 hf_hub_download 函式從 Hub 載入 fastText 模型。

語言識別

若要偵測文字字串的語言,可以按以下方式載入並使用模型:

import fasttext
from huggingface_hub import hf_hub_download

model_path = hf_hub_download(repo_id="facebook/fasttext-language-identification", filename="model.bin
)
model = fasttext.load_model(model_path)
model.predict("Hello, world!
)

詞向量檢索與最近鄰居

對於特徵提取,使用者可以檢索特定詞的向量,或尋找詞向量的最近鄰居以識別語義相似的詞彙:

import fasttext
from huggingface_hub import hf_hub_download

# Loading word vectors
model_path = hf_hub_download(repo_id="facebook/fasttext-en-vectors", filename="model.bin
)
model = fasttext.load_model(model_path)
vector = model['bread']

# Querying nearest neighbors
model_path_nn = hf_hub_download(repo_id="facebook/fasttext-en-nearest-neighbors", filename="model.bin
)
model_nn = fasttext.load_model(model_path_nn)
model_nn.get_nearest_neighbors("bread", k=5)

Sources