Mat*_*ien 41 python machine-learning tf-idf scikit-learn
我一直在和CountVectorizerscikit-learn 一起上课.
据我所知,如果以下面显示的方式使用,最终输出将包含一个包含要素计数或标记的数组.
这些令牌是从一组关键字中提取的,即
tags = [
"python, tools",
"linux, tools, ubuntu",
"distributed systems, linux, networking, tools",
]
Run Code Online (Sandbox Code Playgroud)
下一步是:
from sklearn.feature_extraction.text import CountVectorizer
vec = CountVectorizer(tokenizer=tokenize)
data = vec.fit_transform(tags).toarray()
print data
Run Code Online (Sandbox Code Playgroud)
我们得到的地方
[[0 0 0 1 1 0]
[0 1 0 0 1 1]
[1 1 1 0 1 0]]
Run Code Online (Sandbox Code Playgroud)
这很好,但我的情况有点不同.
我想以与上面相同的方式提取功能,但我不希望这些行data与从中提取功能的文档相同.
换句话说,我怎样才能得到另一组文件的计数,比方说,
list_of_new_documents = [
["python, chicken"],
["linux, cow, ubuntu"],
["machine learning, bird, fish, pig"]
]
Run Code Online (Sandbox Code Playgroud)
得到:
[[0 0 0 1 0 0]
[0 1 0 0 0 1]
[0 0 0 0 0 0]]
Run Code Online (Sandbox Code Playgroud)
我已经阅读了CountVectorizer该类的文档,并且遇到了这个vocabulary参数,它是术语到特征索引的映射.但是,我似乎无法得到这个论点来帮助我.
任何建议表示赞赏.
PS:由于我上面使用的例子Matthias Friedrich的博客所有信用.
Bre*_*arn 51
你是对的,这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)
Run Code Online (Sandbox Code Playgroud)
因此,您将一个带有所需功能的字典作为键传递给它.
如果您CountVectorizer在一组文档上使用,然后想要将这些文档中的一组功能用于新集,请使用vocabulary_原始CountVectorizer 的属性并将其传递给新文档.所以在你的例子中,你可以做到
newVec = CountVectorizer(vocabulary=vec.vocabulary_)
Run Code Online (Sandbox Code Playgroud)
使用第一个词汇表创建一个新的tokenizer.
你应该打电话fit_transform或者只打电话给fit你原来的词汇来源,以便矢量化器学习词汇.
然后,您可以fit通过该transform()方法在任何新数据源上使用此矢量化器.
您可以通过vectorizer.vocabulary_(假设您命名您CountVectorizer的名称)获取拟合产生的词汇(即单词到令牌ID的映射)vectorizer.