python - 如何创建矩阵模板来检查句子相似度?

标签 python scikit-learn text-mining tf-idf tfidfvectorizer

我是文本挖掘和Python的新手,我正在尝试做一个简单的任务。 我想从句子创建 TF 矩阵: ['这是第一句', '这是第二句', '这是第三句']

并在循环中(或以某种方式)将新句子与该矩阵进行比较。

在 Stack Overflow 上,我找到了一个很好的例子,它工作得很好,但在我的例子中,它每次都会计算例句和新句子的 TF 矩阵。它在大型数据集上运行会有点慢。

from sklearn.feature_extraction.text import TfidfVectorizer

vect = TfidfVectorizer()
text = []
text = ['This is the first sentence','This is the second sentence', 'This is the third sentence']
text.append('new sentence')
tfidf = vect.fit_transform(text)

# Get an array of results
results = ( tfidf * tfidf.T ).A

我想知道如何以其他更准确的方式做到这一点,谢谢。

最佳答案

我们可以先对原句子进行拟合

from sklearn.feature_extraction.text import TfidfVectorizer
vect = TfidfVectorizer()
text = ['This is the first test ','This is the sentence', 'this is a third sentence']
vect.fit(text)

tfidf = vect.transform(text).A
>>> tfidf
array([[0.55249005, 0.32630952, 0.        , 0.55249005, 0.42018292,
    0.        , 0.32630952],
   [0.        , 0.43370786, 0.55847784, 0.        , 0.55847784,
    0.        , 0.43370786],
   [0.        , 0.39148397, 0.50410689, 0.        , 0.        ,
    0.66283998, 0.39148397]])

然后用它来改造新的:

new = vect.transform(['this sentence 1','new sentence 2']).A
>>> new
array([[0.        , 0.        , 0.78980693, 0.        , 0.        ,
        0.        , 0.61335554],
       [0.        , 0.        , 1.        , 0.        , 0.        ,
        0.        , 0.        ]])

然后使用一些距离度量来计算句子之间的相似度:

import scipy
>>> scipy.spatial.distance.cdist(tfidf, new, 'euclidean')
array([[1.26479741, 1.41421356],
       [0.76536686, 0.93970438],
       [0.85056925, 0.99588464]])

关于python - 如何创建矩阵模板来检查句子相似度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52567035/

相关文章:

java - 在浏览器中查看正在运行的应用程序输出,如何?

machine-learning - 为什么我在 scikit learn 中 SVM 的所有结果都相同?

python - 如何在sklearn中为SpectralCluster使用曼哈顿距离

java - 如何使用文本挖掘进行文档分析?

python - 从 CSV 读取数据并将数据写入 CSV - 字符串到整数

python - 在 Python 中检测计算机/程序关闭?

python - 在 numpy 或 pandas 中处理巨大的数字

python - `data` 数据集(scikit learn)中的 "Labelled Faces in the Wild"字段的性质是什么?

python - 用 Python 文本挖掘 PDF 文件?

android - Android 机器学习库