書名的 Bag-of-Words
PyBooks 現在有一份書名清單,需要先編碼後才能進一步分析。資料團隊認為可採用 Bag of Words(BoW)模型會是最合適的做法。
下列套件已為你匯入:torch、torchtext。
本練習屬於課程
Deep Learning for Text with PyTorch
練習說明
- 匯入可用來實作 bag-of-words 的
CountVectorizer類別。 - 建立你所匯入類別的物件,並使用該物件將
titles轉換為矩陣表示。 - 使用
get_feature_names_out()方法擷取並顯示前 5 個特徵名稱與編碼後的標題。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Import from sklearn
from sklearn.feature_extraction.text import ____
titles = ['The Great Gatsby','To Kill a Mockingbird','1984','The Catcher in the Rye','The Hobbit', 'Great Expectations']
# Initialize Bag-of-words with the list of book titles
vectorizer = ____()
bow_encoded_titles = ____.fit_transform(____)
# Extract and print the first five features
print(vectorizer.____[:5])
print(bow_encoded_titles.toarray()[0, :5])