2016-02-12 3 views
0

Я хотел бы создать CountVectorizer в scikit-learn, основанный на корпусе текста, а затем добавить больше текста в CountVectorizer позже (добавив в исходный словарь).Можете ли вы добавить к CountVectorizer в scikit-learn?

Если я использую 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} 

Есть ли способ сделать это?

ответ

2

Алгоритмы, реализованные в 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} 
Смежные вопросы