参考这个帖子。我想知道如何向CountVectorizer
模型提供包含空格的词汇,例如distributed systems
或machine learning
?这是一个例子:
import numpy as npfrom itertools import chaintags = [ "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 CountVectorizervec = 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
还是其他地方?
回答:
我认为你已经预定义了要分析的词汇,并且你希望通过分割’, ‘来标记你的标签。
你可以通过以下方式欺骗CountVectorizer
来实现这一点:
from sklearn.feature_extraction.text import CountVectorizervec = 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]]