開始使用免費開始

詞向量投影

你可以用散佈圖視覺化詞向量,幫助你理解詞彙如何被分群。要視覺化詞向量,必須先把它們投影到二維空間。你可以透過主成分分析(Principal Component Analysis,PCA)擷取前兩個主成分來完成投影。

在這個練習中,你將練習如何擷取詞向量,並使用 sklearnPCA 函式庫將它們投影到二維空間。

words 清單中已提供一小串單字,並可使用 en_core_web_md 模型。模型已載入為 nlp。所有必要的函式庫與套件都已為你匯入(PCA、將 numpy 匯入為 np)。

本練習屬於課程

使用 spaCy 的自然語言處理

檢視課程

練習說明

  • 從給定的單字中擷取其 ID,並將結果存入 word_ids 清單。
  • 擷取這些單字之詞向量的前五個元素,接著使用 np.vstack() 垂直堆疊,存入 word_vectors
  • 給定 pca 物件,使用 pca 類別的 .fit_transform() 函式計算轉換後的詞向量。
  • 使用 [:, 0] 索引列印轉換後詞向量的第一個成分。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

words = ["tiger", "bird"]

# Extract word IDs of given words
word_ids = [nlp.____.____[w] for w in words]

# Extract word vectors and stack the first five elements vertically
word_vectors = np.vstack([nlp.____.____[i][:5] for i in word_ids])

# Calculate the transformed word vectors using the pca object
pca = PCA(n_components=2)
word_vectors_transformed = pca.____(____)

# Print the first component of the transformed word vectors
print(____[:, 0])
編輯並執行程式碼