图书标题的 Bag-of-words
PyBooks 现在有一份需要进行编码以便后续分析的图书标题列表。数据团队认为,词袋模型(Bag of Words,BoW)可能是最佳方法。
以下包已为您导入:torch、torchtext。
本练习是课程的一部分
使用 PyTorch 的文本深度学习
练习说明
- 导入用于实现词袋模型的
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])