什么是词袋模型:
Bag-of-words模型是信息检索领域常用的文档表示方法。在信息检索中,BOW模型假定对于一个文档,忽略它的单词顺序和语法、句法等要素,将其仅仅看作是若干个词汇的集合,文档中每个单词的出现都是独立的,不依赖于其它单词是否出现。也就是说,文档中任意一个位置出现的任何单词,都不受该文档语意影响而独立选择的
看着有点懵?直接上例子吧:
给出两个英文句子:
- Jane wants to go to Shenzhen.
- Bob wants to go to Shanghai.
我们统计一下这两个句子一共有几个单词:
1.Jane 2.wants 3.to 4.go 5.Shenzhen 6.Bob 7.Shanghai
很明显有七个单词,因此我们可以开始构造一个长度为7的数组,来表示每一个单词的位置
于是,上面两个句子就可以用下列向量表示了: - 例句1:[1,1,2,1,1,0,0] (统计句子中每个单词出现的次数Jane:1,wants:1, to:2,go:1,Shenzhen:1,Bob:0,Shanghai:0)
- 例句2:[0,1,2,1,0,1,1] (统计句子中每个单词出现的次数Jane:0,wants:1, to:2,go:1,Shenzhen:0,Bob:1,Shanghai:1)
以上。
在sklearn中可以通过调用CountVectorizer 实现:
from sklearn.feature_extraction.text import CountVectorizer
corpus = [
'This is the first document.',
'This document is the second document.',
'And this is the third one.',
'Is this the first document?',
]
vectorizer = CountVectorizer()
vectorizer.fit_transform(corpus).toarray()
array([[0, 1, 1, 1, 0, 0, 1, 0, 1],
[0, 2, 0, 1, 0, 1, 1, 0, 1],
[1, 0, 0, 1, 1, 0, 1, 1, 1],
[0, 1, 1, 1, 0, 0, 1, 0, 1]], dtype=int64)
位置编号(词汇表,应该是按开头字母顺序排的)
sorted(vectorizer.vocabulary_.items(),key=lambda x:x[1],reverse=False)
[('and', 0),
('document', 1),
('first', 2),
('is', 3),
('one', 4),
('second', 5),
('the', 6),
('third', 7),
('this', 8)]