栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Python:tf-idf-cosine:查找文档相似性

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python:tf-idf-cosine:查找文档相似性

通过@excray注释的帮助,我设法弄清楚答案,实际上,我们需要编写一个简单的for循环,以迭代表示火车数据和测试数据的两个数组。

首先实现一个简单的lambda函数来保存用于余弦计算的公式:

cosine_function = lambda a, b : round(np.inner(a, b)/(LA.norm(a)*LA.norm(b)), 3)

然后只需编写一个简单的for循环以遍历to向量,每个逻辑都是“对于trainVectorizerArray中的每个向量,必须在testVectorizerArray中找到与向量的余弦相似度。”

from sklearn.feature_extraction.text import CountVectorizerfrom sklearn.feature_extraction.text import TfidfTransformerfrom nltk.corpus import stopwordsimport numpy as npimport numpy.linalg as LAtrain_set = ["The sky is blue.", "The sun is bright."] #documentstest_set = ["The sun in the sky is bright."] #QuerystopWords = stopwords.words('english')vectorizer = CountVectorizer(stop_words = stopWords)#print vectorizertransformer = TfidfTransformer()#print transformertrainVectorizerArray = vectorizer.fit_transform(train_set).toarray()testVectorizerArray = vectorizer.transform(test_set).toarray()print 'Fit Vectorizer to train set', trainVectorizerArrayprint 'Transform Vectorizer to test set', testVectorizerArraycx = lambda a, b : round(np.inner(a, b)/(LA.norm(a)*LA.norm(b)), 3)for vector in trainVectorizerArray:    print vector    for testV in testVectorizerArray:        print testV        cosine = cx(vector, testV)        print cosinetransformer.fit(trainVectorizerArray)printprint transformer.transform(trainVectorizerArray).toarray()transformer.fit(testVectorizerArray)print tfidf = transformer.transform(testVectorizerArray)print tfidf.todense()

这是输出:

Fit Vectorizer to train set [[1 0 1 0] [0 1 0 1]]Transform Vectorizer to test set [[0 1 1 1]][1 0 1 0][0 1 1 1]0.408[0 1 0 1][0 1 1 1]0.816[[ 0.70710678  0.          0.70710678  0.        ] [ 0.          0.70710678  0.          0.70710678]][[ 0.          0.57735027  0.57735027  0.57735027]]


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/634186.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号