我想在scikit-learn中基于文本语料库创建CountVectorizer,然后在CountVectorizer中添加更多文本(添加到原始字典中)。
如果使用transform()
,它的确会保留原始词汇,但不会添加新词。如果我使用fit_transform()
,它只是从头开始重新生成词汇表。见下文:
In [2]: count_vect = CountVectorizer()
In [3]: count_vect.fit_transform(["This is a test"])
Out[3]:
<1x3 sparse matrix of type '<type 'numpy.int64'>'
with 3 stored elements in Compressed Sparse Row format>
In [4]: count_vect.vocabulary_
Out[4]: {u'is': 0, u'test': 1, u'this': 2}
In [5]: count_vect.transform(["This not is a test"])
Out[5]:
<1x3 sparse matrix of type '<type 'numpy.int64'>'
with 3 stored elements in Compressed Sparse Row format>
In [6]: count_vect.vocabulary_
Out[6]: {u'is': 0, u'test': 1, u'this': 2}
In [7]: count_vect.fit_transform(["This not is a test"])
Out[7]:
<1x4 sparse matrix of type '<type 'numpy.int64'>'
with 4 stored elements in Compressed Sparse Row format>
In [8]: count_vect.vocabulary_
Out[8]: {u'is': 0, u'not': 1, u'test': 2, u'this': 3}
我想要一个等效的update()
功能。我希望它能像这样工作:
In [2]: count_vect = CountVectorizer()
In [3]: count_vect.fit_transform(["This is a test"])
Out[3]:
<1x3 sparse matrix of type '<type 'numpy.int64'>'
with 3 stored elements in Compressed Sparse Row format>
In [4]: count_vect.vocabulary_
Out[4]: {u'is': 0, u'test': 1, u'this': 2}
In [5]: count_vect.update(["This not is a test"])
Out[5]:
<1x3 sparse matrix of type '<type 'numpy.int64'>'
with 4 stored elements in Compressed Sparse Row format>
In [6]: count_vect.vocabulary_
Out[6]: {u'is': 0, u'not': 1, u'test': 2, u'this': 3}
有没有办法做到这一点?
scikit-learn
设计中实现的算法旨在一次适应所有数据,这对于大多数ML算法都是必需的(尽管有趣的是您所描述的应用程序),因此没有update
功能。
有一种方法可以通过稍微有所不同的方式来获得所需的内容,请参见以下代码
from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer
count_vect = CountVectorizer()
count_vect.fit_transform(["This is a test"])
print count_vect.vocabulary_
count_vect.fit_transform(["This is a test", "This is not a test"])
print count_vect.vocabulary_
哪个输出
{u'this': 2, u'test': 1, u'is': 0}
{u'this': 3, u'test': 2, u'is': 0, u'not': 1}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句