我一直在使用scikit-learn中的CountVectorizer
类进行工作。
我明白,如果按照下面的方式使用,最终输出将包含特征或标记的计数数组。
这些标记是从一组关键词中提取的,例如:
tags = [ "python, tools", "linux, tools, ubuntu", "distributed systems, linux, networking, tools",]
下一步是:
from sklearn.feature_extraction.text import CountVectorizervec = CountVectorizer(tokenizer=tokenize)data = vec.fit_transform(tags).toarray()print data
我们得到的结果是:
[[0 0 0 1 1 0] [0 1 0 0 1 1] [1 1 1 0 1 0]]
这很好,但我的情况略有不同。
我想以相同的方式提取特征,但我不想让data
中的行与提取特征的文档相同。
换句话说,如何统计另一组文档的计数,例如:
list_of_new_documents = [ ["python, chicken"], ["linux, cow, ubuntu"], ["machine learning, bird, fish, pig"]]
并得到:
[[0 0 0 1 0 0] [0 1 0 0 0 1] [0 0 0 0 0 0]]
我阅读了CountVectorizer
类的文档,并发现了vocabulary
参数,它是术语到特征索引的映射。然而,我似乎无法利用这个参数来解决我的问题。
任何建议都将不胜感激。
PS: 以上示例的所有功劳归于Matthias Friedrich的博客。
回答:
你是对的,vocabulary
正是你需要的。它是这样工作的:
>>> cv = sklearn.feature_extraction.text.CountVectorizer(vocabulary=['hot', 'cold', 'old'])>>> cv.fit_transform(['pease porridge hot', 'pease porridge cold', 'pease porridge in the pot', 'nine days old']).toarray()array([[1, 0, 0], [0, 1, 0], [0, 0, 0], [0, 0, 1]], dtype=int64)
所以你传递一个字典,其中包含你想要的特征作为键。
如果你在一组文档上使用了CountVectorizer
,然后你想将这些文档的特征集用于一组新的文档,可以使用原始CountVectorizer的vocabulary_
属性,并将其传递给新的CountVectorizer。所以在你的例子中,你可以这样做:
newVec = CountVectorizer(vocabulary=vec.vocabulary_)
来创建一个使用第一个CountVectorizer词汇表的新标记器。