hsh*_*hed 17 python text-processing machine-learning
我正在使用大型文本数据集处理预测问题.我正在实施Bag of Words Model.
什么是最好的方式来获得一揽子文字?现在,我有各种单词的tf-idf,单词的数量太大,无法用于进一步的分配.如果我使用tf-idf标准,那么获取单词包的tf-idf阈值应该是多少?或者我应该使用其他一些算法.我正在使用python.
Pad*_*118 26
>>> import collections, re
>>> texts = ['John likes to watch movies. Mary likes too.',
'John also likes to watch football games.']
>>> bagsofwords = [ collections.Counter(re.findall(r'\w+', txt))
for txt in texts]
>>> bagsofwords[0]
Counter({'likes': 2, 'watch': 1, 'Mary': 1, 'movies': 1, 'John': 1, 'to': 1, 'too': 1})
>>> bagsofwords[1]
Counter({'watch': 1, 'games': 1, 'to': 1, 'likes': 1, 'also': 1, 'John': 1, 'football': 1})
>>> sumbags = sum(bagsofwords, collections.Counter())
>>> sumbags
Counter({'likes': 3, 'watch': 2, 'John': 2, 'to': 2, 'games': 1, 'football': 1, 'Mary': 1, 'movies': 1, 'also': 1, 'too': 1})
>>>
Run Code Online (Sandbox Code Playgroud)
Pra*_*mit 14
可以将词袋定义为矩阵,其中每行表示文档,列表示单个令牌.还有一件事,不保持文本的连续顺序.建立一个"袋子"包含3个步骤
要记住的局限性:1.无法捕捉短语或多词表达2.对拼写错误敏感,可以使用拼写纠正器或角色表示来解决这个问题,
例如
from sklearn.feature_extraction.text import CountVectorizer
vectorizer = CountVectorizer()
data_corpus = ["John likes to watch movies. Mary likes movies too.",
"John also likes to watch football games."]
X = vectorizer.fit_transform(data_corpus)
print(X.toarray())
print(vectorizer.get_feature_names())
Run Code Online (Sandbox Code Playgroud)
词袋模型是一种很好的文本表示方法,可以应用于不同的机器学习任务中。但是第一步,您需要从不必要的数据中清除数据,例如标点符号,html标记,停用词等。对于这些任务,您可以轻松利用Beautiful Soup(删除HTML标记)或NLTK(在Python中删除停用词)。清理数据后,您需要创建矢量特征(用于机器学习的数据的数字表示),这是单词袋的作用。scikit-learn有一个模块(feature_extraction模块),可以帮助您创建单词袋功能。
你可能会发现你在细节需要在这个教程中也这个人可以是非常有益的。我发现它们都很有用。