2012-02-28 8 views
2

私はファイルとクエリdocのセットを持っています。私の目的は各文書のquery docと比較して最も類似した文書を返すことです。余弦類似性を使用するには、最初に文書の文字列をベクトルにマップする必要があります。また、文書のそれぞれを計算するtf-idf関数をすでに作成しています。Pythonのコサイン類似度を使用してクエリ文書と比較して最も類似した文書を返します

文字列のインデックスを取得するには、そのような関数があります。

def getvectorKeywordIndex(self, documentList): 
    """ create the keyword associated to the position of the elements within the document vectors """ 
    #Mapped documents into a single word string 
    vocabularyString = " ".join(documentList) 
    vocabularylist= vocabularyString.split(' ') 
    vocabularylist= list(set(vocabularylist)) 
    print 'vocabularylist',vocabularylist 
    vectorIndex={} 
    offset=0 
    #Associate a position with the keywords which maps to the dimension on the vector used to represent this word 
    for word in vocabularylist: 
     vectorIndex[word]=offset 
     offset+=1 
    print vectorIndex 
    return vectorIndex,vocabularylist #(keyword:position),vocabularylist 

とコサイン類似性のために私の関数は次のとおりです。

def cosine_distance(self,index, queryDoc): 

    vector1= self.makeVector(index) 
    vector2= self.makeVector(queryDoc) 

    return numpy.dot(vector1, vector2)/(math.sqrt(numpy.dot(vector1, vector1)) * math.sqrt(numpy.dot(vector2, vector2))) 

TF-IDFは、

def tfidf(self, term, key): 

    return (self.tf(term,key) * self.idf(term)) 

私の問題は、どのように私は、この関数の内部で、インデックスと語彙リストともTF-IDFを使用してmakevectorを作成することができるということです。 答えは歓迎です。

答えて

1

vectorIndexからmakeVectorにも渡す必要があります。これを使用して、ドキュメントやクエリの用語のインデックスを参照してください。 vectorIndexに表示されない項目は無視してください。

ドキュメントを扱う際には、Numpy配列の代わりにscipy.sparse行列を実際に使用する必要があります。そうしないと、すぐにメモリが使い果たされます。

(また、scikit-学ぶれ、あなたのためにこれをすべて処理scipy.sparse行列を使用し、TF-IDF値を計算免責事項にVectorizerを使用することを検討してください:。。私は、そのクラスの一部を書いた)

関連する問題