python - 计算从 4 个 mysql 表中检索到的所有可能文本对的余弦相似度

标签 python numpy scikit-learn text-mining cosine-similarity

我有 4 个带有模式的表(app、text_id、title、text)。现在我想计算所有可能的文本对(标题和文本连接)之间的余弦相似度,并最终将它们存储在包含字段(app1、app2、text_id1、text1、text_id2、text2、cosine_similarity)的 csv 文件中。

由于有很多可能的组合,它应该会非常有效地运行。这里最常见的方法是什么?如有任何指点,我将不胜感激。

编辑: 尽管提供的引用资料可能会触及我的问题,但我仍然不知道如何解决这个问题。有人可以提供有关完成此任务的策略的更多详细信息吗?除了计算余弦相似度之外,我还需要相应的文本对作为输出。

最佳答案

以下是计算一组文档之间的成对余弦相似度的最小示例(假设您已成功从数据库中检索到标题和文本)。

from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity

# Assume thats the data we have (4 short documents)
data = [
    'I like beer and pizza',
    'I love pizza and pasta',
    'I prefer wine over beer',
    'Thou shalt not pass'
]

# Vectorise the data
vec = TfidfVectorizer()
X = vec.fit_transform(data) # `X` will now be a TF-IDF representation of the data, the first row of `X` corresponds to the first sentence in `data`

# Calculate the pairwise cosine similarities (depending on the amount of data that you are going to have this could take a while)
S = cosine_similarity(X)

'''
S looks as follows:
array([[ 1.        ,  0.4078538 ,  0.19297924,  0.        ],
       [ 0.4078538 ,  1.        ,  0.        ,  0.        ],
       [ 0.19297924,  0.        ,  1.        ,  0.        ],
       [ 0.        ,  0.        ,  0.        ,  1.        ]])

The first row of `S` contains the cosine similarities to every other element in `X`. 
For example the cosine similarity of the first sentence to the third sentence is ~0.193. 
Obviously the similarity of every sentence/document to itself is 1 (hence the diagonal of the sim matrix will be all ones). 
Given that all indices are consistent it is straightforward to extract the corresponding sentences to the similarities.
'''

关于python - 计算从 4 个 mysql 表中检索到的所有可能文本对的余弦相似度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41504454/

相关文章:

使用 dict 在 Pushover 中进行 python 确认

python - 通过 PIL 将 Numpy 数组保存为实验室图像

python - numpy 数组索引 : applying condition over the entire row/col

python - 使用 Numpy 或 Pandas 根据字符计数对字符串进行矢量化分割

python - scikit learn 截断SVD解释_方差_比率_不按降序排列?

python - Scikit-Learn/Pandas : make a prediction using a saved model based on user input

python - 安装了 html5lib 但 BeautifulSoup 找不到它

python - 将 Pandas 数据框列和索引转换为值

java - Twistd - Telnet - Python 服务器,Java 客户端,客户端在连接关闭之前永远不会接收字符串,此时所有字符串连接在一起并一起发送

python - Scikit Learn 中的 CountVectorizer