您应该调用fit_transform
或只fit
原始词汇来源,以便矢量化程序学习词汇。
然后,您可以通过transform()
方法在所有新数据源上使用此fit
矢量化器。
您可以通过vectorizer.vocabulary_
(假设您将CountVectorizer
命名为vectorizer
)来获取由匹配产生的词汇(即单词到令牌ID的映射)。
0
您应该调用fit_transform
或只fit
原始词汇来源,以便矢量化程序学习词汇。
然后,您可以通过transform()
方法在所有新数据源上使用此fit
矢量化器。
您可以通过vectorizer.vocabulary_
(假设您将CountVectorizer
命名为vectorizer
)来获取由匹配产生的词汇(即单词到令牌ID的映射)。
0
>>> tags = [
"python, tools",
"linux, tools, ubuntu",
"distributed systems, linux, networking, tools",
]
>>> list_of_new_documents = [
["python, chicken"],
["linux, cow, ubuntu"],
["machine learning, bird, fish, pig"]
]
>>> from sklearn.feature_extraction.text import CountVectorizer
>>> vect = CountVectorizer()
>>> tags = vect.fit_transform(tags)
# vocabulary learned by CountVectorizer (vect)
>>> print(vect.vocabulary_)
{'python': 3, 'tools': 5, 'linux': 1, 'ubuntu': 6, 'distributed': 0, 'systems': 4, 'networking': 2}
# counts for tags
>>> tags.toarray()
array([[0, 0, 0, 1, 0, 1, 0],
[0, 1, 0, 0, 0, 1, 1],
[1, 1, 1, 0, 1, 1, 0]], dtype=int64)
# to use `transform`, `list_of_new_documents` should be a list of strings
# `itertools.chain` flattens shallow lists more efficiently than list comprehensions
>>> from itertools import chain
>>> new_docs = list(chain.from_iterable(list_of_new_documents)
>>> new_docs = vect.transform(new_docs)
# finally, counts for new_docs!
>>> new_docs.toarray()
array([[0, 0, 0, 1, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 1],
[0, 0, 0, 0, 0, 0, 0]])
要验证CountVectorizer
使用来自学到的词汇tags
上new_docs
:打印vect.vocabulary_
再次或输出比较new_docs.toarray()
到的tags.toarray()
0
您是对的,您的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_
属性并将其传递给新的。因此,在您的示例中,您可以
newVec = CountVectorizer(vocabulary=vec.vocabulary_)
使用第一个词汇创建一个新的令牌生成器。
0
我一直在使用scikit-learn中的
CountVectorizer
类。我了解,如果以下面所示的方式使用,则最终输出将由一个包含特征或标记计数的数组组成。
这些令牌是从一组关键字中提取的,即
下一步是:
我们到哪里
很好,但是我的情况略有不同。
我想以与上述相同的方式提取特征,但我不希望
data
的行与提取特征的文档相同。换句话说,我如何获得另一组文档的数量,例如
得到:
我已经阅读了
CountVectorizer
类的文档,并遇到了vocabulary
参数,该参数是术语到功能索引的映射。但是,我似乎无法获得这种论点来帮助我。任何建议表示赞赏。
附言:我上面使用的示例均归功于Matthias Friedrich的Blog 。