2013-08-25 10 views
7

Ho questo codice per calcolare la somiglianza del testo con tf-idf.algoritmo tfidf per python

from sklearn.feature_extraction.text import TfidfVectorizer 

documents = [doc1,doc2] 
tfidf = TfidfVectorizer().fit_transform(documents) 
pairwise_similarity = tfidf * tfidf.T 
print pairwise_similarity.A 

Il problema è che questo codice prende come input stringhe semplici e voglio preparare i documenti, eliminando stopwords, diraspatura e tokkenize. Quindi l'input sarebbe una lista. L'errore, se io chiamo la documents = [doc1,doc2] con i documenti tokkenized è:

Traceback (most recent call last): 
    File "C:\Users\tasos\Desktop\my thesis\beta\similarity.py", line 18, in <module> 
    tfidf = TfidfVectorizer().fit_transform(documents) 
    File "C:\Python27\lib\site-packages\scikit_learn-0.14.1-py2.7-win32.egg\sklearn\feature_extraction\text.py", line 1219, in fit_transform 
    X = super(TfidfVectorizer, self).fit_transform(raw_documents) 
    File "C:\Python27\lib\site-packages\scikit_learn-0.14.1-py2.7-win32.egg\sklearn\feature_extraction\text.py", line 780, in fit_transform 
    vocabulary, X = self._count_vocab(raw_documents, self.fixed_vocabulary) 
    File "C:\Python27\lib\site-packages\scikit_learn-0.14.1-py2.7-win32.egg\sklearn\feature_extraction\text.py", line 715, in _count_vocab 
    for feature in analyze(doc): 
    File "C:\Python27\lib\site-packages\scikit_learn-0.14.1-py2.7-win32.egg\sklearn\feature_extraction\text.py", line 229, in <lambda> 
    tokenize(preprocess(self.decode(doc))), stop_words) 
    File "C:\Python27\lib\site-packages\scikit_learn-0.14.1-py2.7-win32.egg\sklearn\feature_extraction\text.py", line 195, in <lambda> 
    return lambda x: strip_accents(x.lower()) 
AttributeError: 'unicode' object has no attribute 'apply_freq_filter' 

C'è un modo per cambiare il codice e renderlo accettare lista oppure ho di modificare i documenti tokkenized alle stringhe di nuovo?

+0

Sembra che manchi il messaggio di errore effettivo (è stato incluso il traceback, ma non l'errore generato). –

+0

Oops. Lo modifico – Tasos

+0

@Tasos La mia risposta ha funzionato o hai ancora problemi? Puoi dare un esempio minimo di 'doc1' /' doc2' se la mia soluzione non ha funzionato? – chlunde

risposta

5

Provate saltare la pre-elaborazione in caratteri minuscoli e fornire il proprio tokenizer "NOP":

tfidf = TfidfVectorizer(tokenizer=lambda doc: doc, lowercase=False).fit_transform(documents) 

Si dovrebbe anche controllare altri parametri come stop_words per evitare di duplicare il vostro pre-elaborazione.