提供带有空格的单词的词汇表来scikit-learn CountVectorizer

时间:2016-06-17 04:13:06

标签: python machine-learning scikit-learn

参考此post。我想知道我们如何为CountVectorizer模型提供空格词汇,例如distributed systemsmachine learning?这是一个例子:

import numpy as np
from itertools import chain

tags = [
  "python, tools",
  "linux, tools, ubuntu",
  "distributed systems, linux, networking, tools",
]

vocabulary = list(map(lambda x: x.split(', '), tags))
vocabulary = list(np.unique(list(chain(*vocabulary))))

我们可以将这个词汇表提供给模型

from sklearn.feature_extraction.text import CountVectorizer
vec = CountVectorizer(vocabulary=vocabulary)
print(vec.fit_transform(tags).toarray())

在这里,我丢失了单词distributed systems(第一列)的计数。结果如下:

[[0 0 0 1 1 0]
 [0 1 0 0 1 1]
 [0 1 1 0 1 0]]

我是否需要更改token_pattern或其他地方?

1 个答案:

答案 0 :(得分:2)

我认为您已经预先定义了要分析的词汇表,并希望通过拆分'来标记您的标记。

您可以通过以下方式欺骗CountVectorizer

from sklearn.feature_extraction.text import CountVectorizer
vec = CountVectorizer(vocabulary=vocabulary, tokenizer=lambda x: x.split(', '))
print(vec.fit_transform(tags).toarray())

,它给出了:

[[0 0 0 1 1 0]
 [0 1 0 0 1 1]
 [1 1 1 0 1 0]]