私はファイルとクエリ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を作成することができるということです。 答えは歓迎です。