2017-01-10 43 views
0

有沒有人有任何關於如何使用Python和scikit-learn將文檔中的單詞轉換爲LSA向量的建議?我發現這些網站herehere,它們規定了如何將整個文檔轉換爲lsa矢量,但我有興趣轉換單個單詞本身。將單詞轉化爲潛在語義分析(LSA)向量

最終結果是從每個句子中總結所有向量(表示每個詞),然後比較連續句子以評估語義相似性。

回答

1

將一個句子或一個單詞轉換爲一個向量與對文檔的轉換沒有什麼不同,一個句子就像一個短文檔,一個單詞就像一個非常短的文檔。從第一link我們有用於映射文檔的向量的代碼:

def makeVector(self, wordString): 
     """ @pre: unique(vectorIndex) """ 

     #Initialise vector with 0's 
     vector = [0] * len(self.vectorKeywordIndex) 
     wordList = self.parser.tokenise(wordString) 
     wordList = self.parser.removeStopWords(wordList) 
     for word in wordList: 
       vector[self.vectorKeywordIndex[word]] += 1; #Use simple Term Count Model 
     return vector 

相同功能可以被用於映射一個句子或一個字到一個載體中。只需將它們傳遞給此函數。對於一個字,wordList的結果將是一個數組,其中包含單個值,如:["word"],然後映射後,結果向量將爲unit vector,其中包含關聯維中的1和其他地方的0

實施例:

vectorKeywordIndex(表示詞彙的所有字):

{"hello" : 0, "world" : 1, "this" : 2, "is" : 3, "me" : 4, "answer" : 5} 

"this is me"文件:[0, 0, 1, 1, 1, 0]

文件"hello answer me"[1, 0, 0, 0, 1, 1]

"hello"[1, 0, 0, 0, 0, 0]

"me"[0, 0, 0, 0, 1, 0]

這種相似後,可以通過以下的標準像餘弦相似度使用此代碼進行評估:

def cosine(vector1, vector2): 
     """ related documents j and q are in the concept space by comparing the vectors using the code: 
       cosine = (V1 * V2)/||V1|| x ||V2|| """ 
     return float(dot(vector1,vector2)/(norm(vector1) * norm(vector2))) 

或使用scikit學習的sklearn.metrics.pairwise.cosine_similarity

from sklearn.metrics.pairwise import cosine_similarity 
sim = cosine_similarity(x, y)