python - 在python中计算大数据集相似度矩阵的有效方法

标签 python matrix nltk similarity

我正在使用亲和传播聚类对句子进行聚类。作为中间步骤,我正在计算相似度矩阵。它适用于小型数据集,但会引发大型数据集的内存错误。我有一个包含句子的数据集。

示例数据集:

'open contacts',
'open music player',
'play song',
'call john',
'open camera',
'video download',
...

我的代码:

import nltk, string
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.cluster import AffinityPropagation
import pandas as pd

punctuation_map = dict((ord(char), None) for char in string.punctuation)
stemmer = nltk.stem.snowball.SpanishStemmer()

def stem_tokens(tokens):
    return [stemmer.stem(item) for item in tokens]

def normalize(text):
    return stem_tokens(nltk.word_tokenize(text.lower().translate(punctuation_map)))

vectorizer = TfidfVectorizer(tokenizer=normalize)

def get_clusters(sentences):
    tf_idf_matrix = vectorizer.fit_transform(sentences)
    similarity_matrix = (tf_idf_matrix * tf_idf_matrix.T).A
    affinity_propagation = AffinityPropagation(affinity="precomputed", damping=0.5)
    affinity_propagation.fit(similarity_matrix)

#     global labels
    labels = affinity_propagation.labels_

#     global cluster_centers
    cluster_centers = affinity_propagation.cluster_centers_indices_

    tagged_sentences = zip(sentences, labels)
    clusters = {}

    for sentence, cluster_id in tagged_sentences:
        clusters.setdefault(sentences[cluster_centers[cluster_id]], []).append(sentence)
        #print(len(sentence))

    return clusters

#csv file
filename = "/home/ubuntu/VA_data/first_50K.csv"
df = pd.read_csv(filename, header = None)

sentences = df.iloc[:, 0].values.tolist()

clusters = get_clusters(sentences)

任何人都可以建议我找到相似矩阵的有效方法吗?我的数据集包含 100 万个句子。

最佳答案

一种可能的方法是将数据存储在 Spark 中,Spark 还提供可扩展的矩阵乘法。

关于python - 在python中计算大数据集相似度矩阵的有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48678848/

相关文章:

python - 在 Python 中创建一个 "actual"for 循环?

python - 创建超过 100000 个项目的 TreeView 时代码速度很慢

opencv - 如何在opencv中将3个矩阵合并为1个?

python - 来自 NLTK、Gensim、Scikit Learn 的 API 调用

python - 在 x 秒后运行某些代码,在 python 中每 n 秒运行一次

python - 在 Web 应用程序中使用 Postgres : "transaction aborted" errors

algorithm - 如何用常数值填充二维数组,效率比 n^2 更高?

matrix - 用函数初始化矩阵

python - 从Python中的句子中提取子句

python - 使用NLTK在文本中查找原因