2016-08-23 9 views
8

क्या मौजूदा कॉर्पस में जोड़ने के लिए कोई फ़ंक्शन है? मैंने पहले से ही अपने मैट्रिक्स को जेनरेट कर लिया है, मैं समय-समय पर पूरे शा-बैंग को फिर से क्रंच किए बिना तालिका में जोड़ना चाहता हूंSklearn TFIDIF वेक्टरिज़र (पायथन) में नया टेक्स्ट जोड़ना

उदाहरण;

articleList = ['here is some text blah blah','another text object', 'more foo for your bar right now'] 
tfidf_vectorizer = TfidfVectorizer(
         max_df=.8, 
         max_features=2000, 
         min_df=.05, 
         preprocessor=prep_text, 
         use_idf=True, 
         tokenizer=tokenize_text 
        ) 
tfidf_matrix = tfidf_vectorizer.fit_transform(articleList) 

#### ADDING A NEW ARTICLE TO EXISTING SET? 
bigger_tfidf_matrix = tfidf_vectorizer.fit_transform(['the last article I wanted to add']) 

उत्तर

6

आप सीधे अपने vectoriser की vocabulary_ विशेषता का उपयोग कर सकते हैं, और आप _tfidf._idf_diag के माध्यम से idf_ वेक्टर उपयोग कर सकते हैं, तो यह इस तरह बंदर-पैच कुछ संभव हो जाएगा:

import re 
import numpy as np 
from scipy.sparse.dia import dia_matrix 
from sklearn.feature_extraction.text import TfidfVectorizer 

def partial_fit(self, X): 
    max_idx = max(self.vocabulary_.values()) 
    for a in X: 
     #update vocabulary_ 
     if self.lowercase: a = a.lower() 
     tokens = re.findall(self.token_pattern, a) 
     for w in tokens: 
      if w not in self.vocabulary_: 
       max_idx += 1 
       self.vocabulary_[w] = max_idx 

     #update idf_ 
     df = (self.n_docs + self.smooth_idf)/np.exp(self.idf_ - 1) - self.smooth_idf 
     self.n_docs += 1 
     df.resize(len(self.vocabulary_)) 
     for w in tokens: 
      df[self.vocabulary_[w]] += 1 
     idf = np.log((self.n_docs + self.smooth_idf)/(df + self.smooth_idf)) + 1 
     self._tfidf._idf_diag = dia_matrix((idf, 0), shape=(len(idf), len(idf))) 

TfidfVectorizer.partial_fit = partial_fit 
articleList = ['here is some text blah blah','another text object', 'more foo for your bar right now'] 
vec = TfidfVectorizer() 
vec.fit(articleList) 
vec.n_docs = len(articleList) 
vec.partial_fit(['the last text I wanted to add']) 
vec.transform(['the last text I wanted to add']).toarray() 

# array([[ 0.  , 0.  , 0.  , 0.  , 0.  , 
#   0.  , 0.  , 0.  , 0.  , 0.  , 
#   0.  , 0.  , 0.27448674, 0.  , 0.43003652, 
#   0.43003652, 0.43003652, 0.43003652, 0.43003652]]) 
+0

के लिए धन्यवाद जवाब देने के लिए समय लेना। मैं प्रासंगिकता के परिणामों की एक सूची उत्पन्न करने के लिए cosine_similarity का उपयोग करके, एक खोज अनुक्रमणिका के रूप में इसका उपयोग करने की कोशिश कर रहा हूं। हर बार जब मैं एक नया दस्तावेज़ जोड़ने की इच्छा जोड़ता हूं तो मेरे पूरे कॉर्पस को दोबारा शुरू करना अच्छा नहीं होगा। –

+1

हे हावर्ड, मैंने 'idf_' को अपडेट करने का तरीका बताया, मेरा संपादित उत्तर – maxymoo

+0

बहुत बढ़िया देखें! महान प्रतिक्रिया के लिए धन्यवाद! –

संबंधित मुद्दे