首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >潜在语义分析与学习

潜在语义分析与学习
EN

Stack Overflow用户
提问于 2013-09-25 06:38:50
回答 1查看 7.8K关注 0票数 6

我正在尝试写一个脚本,在那里我将计算几个文档的相似性。我想用LSA来做。我已经找到了下面的代码,并对其做了一些修改。我有一个输入3个文档,然后输出一个3x3矩阵,其中包含它们之间的相似性。我想做同样的相似度计算,但只对sklearn库。这有可能吗?

代码语言:javascript
运行
复制
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的回答:

我运行了下面的代码,但我的嘴还是张开的:)当TF下手在两个主题相同的文档上有最大80%的相似性时,这个代码给我99.99%。这就是为什么我认为这是不对的:

代码语言:javascript
运行
复制
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)
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-09-25 07:49:39

您可以使用sklearn 0.14+中的0.14+转换器:在文档数据库中使用fit_transform调用它,然后调用查询文档上的transform方法(来自相同的TruncatedSVD方法),然后使用sklearn.metrics.pairwise.cosine_similaritynumpy.argsort函数计算转换后的查询文档与转换后的数据库之间的余弦相似度,以查找最相似文档的索引。

请注意,在引擎盖下,scikit-learn也使用NumPy,但使用的方式比您提供的代码片段更有效(通过使用Halko、Martinsson和Tropp的Randomized SVD技巧)。

票数 10
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/18997905

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档