gpt4 book ai didi

python - 您可以添加到 scikit-learn 中的 CountVectorizer 吗?

转载 作者:行者123 更新时间:2023-11-28 22:38:50 24 4
gpt4 key购买 nike

我想在 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 算法来说是必需的(尽管有趣的不是您描述的应用程序),所以有没有更新功能。

有一种方法可以通过略微不同的方式来获得您想要的东西,请参见以下代码

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}

关于python - 您可以添加到 scikit-learn 中的 CountVectorizer 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35372008/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com