2013-07-20 2 views
2

gensim 자습서를 사용하여 텍스트 간의 유사점을 찾습니다. 코드는 다음과 같습니다python gensim : indices 배열에 정수가 아닌 dtype이 있습니다. (float64)

from gensim import corpora, models, similarities 
from gensim.models import hdpmodel, ldamodel 
from itertools import izip 

import logging 
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO) 

''' 
documents = ["Human machine interface for lab abc computer applications", 
       "bags loose tea water second ingredient tastes water", 
       "The EPS user interface management system", 
       "System and human system engineering testing of EPS", 
       "Relation of user perceived response time to error measurement", 
       "The generation of random binary unordered trees", 
       "The intersection graph of paths in trees", 
       "Graph minors IV Widths of trees and well quasi ordering", 
       "Graph minors A survey", 
       "red cow butter oil"] 
''' 
documents = ["Human machine interface for lab abc computer applications", 
       "bags loose tea water second ingredient tastes water"] 

# remove common words and tokenize 
stoplist = set('for a of the and to in'.split()) 
texts = [[word for word in document.lower().split() if word not in stoplist] 
     for document in documents] 

# remove words that appear only once 
all_tokens = sum(texts, []) 
tokens_once = set(word for word in set(all_tokens) if all_tokens.count(word) == 1) 
texts = [[word for word in text if word not in tokens_once] 
     for text in texts] 

dictionary = corpora.Dictionary(texts) 
corpus = [dictionary.doc2bow(text) for text in texts] 

#print corpus 

tfidf = models.TfidfModel(corpus) 

#print tfidf 

corpus_tfidf = tfidf[corpus] 

#print corpus_tfidf 

lsi = models.LsiModel(corpus_tfidf, id2word=dictionary, num_topics=2) 
lsi.print_topics(1) 

lda = models.LdaModel(corpus_tfidf, id2word=dictionary, num_topics=2) 
lda.print_topics(1) 

corpora.MmCorpus.serialize('dict.mm', corpus) 
corpus = corpora.MmCorpus('dict.mm') 
#print corpus 

lsi = models.LsiModel(corpus, id2word=dictionary, num_topics=2) 
doc = "human computer interaction" 
vec_bow = dictionary.doc2bow(doc.lower().split()) 
vec_lsi = lsi[vec_bow] 
#print vec_lsi 

index = similarities.MatrixSimilarity(lsi[corpus]) 
index.save('dict.index') 
index = similarities.MatrixSimilarity.load('dict.index') 

sims = index[vec_lsi] 
#print list(enumerate(sims)) 

sims = sorted(enumerate(sims),key=lambda item: -item[1]) 
for sim in sims: 
    print documents[sim[0]], " ==> ", sim[1] 

여기에는 두 개의 문서가 있습니다. 하나에는 10 개의 텍스트가 있고 다른 하나에는 2 개의 텍스트가 있습니다. 첫 번째 문서 목록을 사용하면 모든 것이 잘되어 의미있는 결과를 얻습니다. 두 번째 문서 목록 (두 개의 텍스트가있는 경우)을 사용하면 오류가 발생합니다. 여기에 그것입니다

/usr/lib/python2.7/dist-packages/scipy/sparse/compressed.py:122: UserWarning: indices array has non-integer dtype (float64) 
% self.indices.dtype.name) 

이 오류의 배경은 무엇이며 어떻게 해결할 수 있습니까? 64 비트 시스템을 사용하고 있습니다.

답변

2

0과 1 차원의 행렬에 대해 행렬 연산을 수행하려고 시도 할 때, 두 번째 목록이 단일성을 제거 할 때까지 [[], ['water']]이 될 것이기 때문에 모든 문제가 발생할 수 있습니다. 당신이 그것을에 models.TfidfModel(corpus)를 호출하기 전에 corpus하지은 빈 목록을 가지고 있는지 확인해야합니다 위에 말했듯이

>>> corpus = [dictionary.doc2bow(text) for text in texts] 
>>> corpus 
[[], [(0, 2)]] 
>>> tfidf = models.TfidfModel(corpus) 
2013-07-21 09:23:31,415 : INFO : collecting document frequencies 
2013-07-21 09:23:31,415 : INFO : PROGRESS: processing document #0 
2013-07-21 09:23:31,415 : INFO : calculating IDF weights for 2 documents and 1 features (1 matrix non-zeros) 
>>> corpus = [[(1,)], [(0,2)]] 
>>> tfidf = models.TfidfModel(corpus) 
2013-07-21 09:24:16,452 : INFO : collecting document frequencies 
2013-07-21 09:24:16,452 : INFO : PROGRESS: processing document #0 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
    File "/usr/local/lib/python2.7/dist-packages/gensim/models/tfidfmodel.py", line 96, in __init__ 
    self.initialize(corpus) 
    File "/usr/local/lib/python2.7/dist-packages/gensim/models/tfidfmodel.py", line 119, in initialize 
    for termid, _ in bow: 
ValueError: need more than 1 value to unpack 
>>> corpus = [[(1,3)], [(0,2)]] 
>>> tfidf = models.TfidfModel(corpus) 
2013-07-21 09:24:26,892 : INFO : collecting document frequencies 
2013-07-21 09:24:26,892 : INFO : PROGRESS: processing document #0 
2013-07-21 09:24:26,892 : INFO : calculating IDF weights for 2 documents and 2 features (2 matrix non-zeros) 
>>> 

:

코드와 연극을 가졌어요.

+0

조금 설명해 주시겠습니까? – qmaruf

+0

업데이트 된 답변보기 –

+0

빈 목록 (= 빈 문서)은 완벽합니다. 두 번째 예제는'(1,)'1-tuple이 유효한 스파 스 항목이 아니기 때문에 실패합니다. 반드시 (token_id, token_weight) 2-tuple이어야합니다. – Radim

0

이것은 오류가 아니며 경고입니다. 당신은 그것을 무시할 수 있습니다.

두 번째 경우에는 쿼리 문서 doc이 비어있어 경고가 발생합니다. 그래도 어쨌든 정답을 얻을 수 있습니다 (= 공란 vec_lsi).

관련 문제