簡體   English   中英

使用潛在語義分析和sklearn

[英]Use Latent Semantic Analysis with sklearn

我正在嘗試編寫一個腳本,我將計算幾個文檔的相似性。 我想通過使用LSA來做到這一點。 我找到了以下代碼並稍微改了一下。 我輸入3個文檔,然后作為輸出3x3矩陣,它們之間具有相似性。 我想進行相同的相似度計算,但只能使用sklearn庫。 那可能嗎?

from numpy import zeros
from scipy.linalg import svd
from math import log
from numpy import asarray, sum
from nltk.corpus import stopwords
from sklearn.metrics.pairwise import cosine_similarity

titles = [doc1,doc2,doc3]
ignorechars = ''',:'!'''

class LSA(object):
    def __init__(self, stopwords, ignorechars):
        self.stopwords = stopwords.words('english')
        self.ignorechars = ignorechars
        self.wdict = {}
        self.dcount = 0        
    def parse(self, doc):
        words = doc.split();
        for w in words:
            w = w.lower()
            if w in self.stopwords:
                continue
            elif w in self.wdict:
                self.wdict[w].append(self.dcount)
            else:
                self.wdict[w] = [self.dcount]
        self.dcount += 1
    def build(self):
        self.keys = [k for k in self.wdict.keys() if len(self.wdict[k]) > 1]
        self.keys.sort()
        self.A = zeros([len(self.keys), self.dcount])
        for i, k in enumerate(self.keys):
            for d in self.wdict[k]:
                self.A[i,d] += 1
    def calc(self):
        self.U, self.S, self.Vt = svd(self.A)
        return -1*self.Vt

    def TFIDF(self):
        WordsPerDoc = sum(self.A, axis=0)        
        DocsPerWord = sum(asarray(self.A > 0, 'i'), axis=1)
        rows, cols = self.A.shape
        for i in range(rows):
            for j in range(cols):
                self.A[i,j] = (self.A[i,j] / WordsPerDoc[j]) * log(float(cols) / DocsPerWord[i])

mylsa = LSA(stopwords, ignorechars)
for t in titles:
    mylsa.parse(t)
mylsa.build()
a = mylsa.calc()
cosine_similarity(a)

來自@ ogrisel的回答:

我運行以下代碼,但我的嘴仍然打開:)當TFIDF在具有相同主題的兩個文檔上具有最大80%的相似性時,此代碼給出99.99%。 這就是為什么我認為這是錯誤的:P

dataset = [doc1,doc2,doc3]
vectorizer = TfidfVectorizer(max_df=0.5,stop_words='english')
X = vectorizer.fit_transform(dataset)
lsa = TruncatedSVD()
X = lsa.fit_transform(X)
X = Normalizer(copy=False).fit_transform(X)

cosine_similarity(X)

您可以使用sklearn 0.14+中的TruncatedSVD轉換器:在文檔數據庫中使用fit_transform調用它,然后在查詢文檔上調用transform方法(來自相同的TruncatedSVD方法),然后可以計算轉換后的查詢文檔的余弦相似度用轉換后的數據庫與函數: sklearn.metrics.pairwise.cosine_similaritynumpy.argsort結果來查找最相似文檔的索引。

請注意,在引擎蓋下,scikit-learn也使用NumPy,但是比你給出的片段更有效(通過使用Halko,Martinsson和Tropp的Randomized SVD技巧)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM