tf-idf 詞頻陣列
在這個練習中,你將為一組簡單的文件建立 tf-idf 詞頻陣列。請使用 sklearn 的 TfidfVectorizer。它會將文件清單轉換成詞頻陣列,並以 csr_matrix 輸出。它和其他 sklearn 物件一樣具有 fit() 與 transform() 方法。
你會拿到一個關於寵物的簡易文件清單 documents。
本練習屬於課程
Unsupervised Learning in Python
練習說明
- 從
sklearn.feature_extraction.text匯入TfidfVectorizer。 - 建立一個名為
tfidf的TfidfVectorizer實例。 - 對
documents套用tfidf的.fit_transform()方法,並將結果指定給csr_mat。這是一個以 csr_matrix 格式表示的詞頻陣列。 - 透過呼叫
.toarray()並列印結果來檢視csr_mat。這部分已為你完成。 - 陣列的欄對應到字詞。透過呼叫
tfidf的.get_feature_names_out()方法取得字詞清單,並將結果指定給words。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Import TfidfVectorizer
from ____ import ____
# Create a TfidfVectorizer: tfidf
tfidf = ____
# Apply fit_transform to document: csr_mat
csr_mat = ____
# Print result of toarray() method
print(csr_mat.toarray())
# Get the words: words
words = ____
# Print words
print(words)