【问题标题】:How to cluster strings by Hamming or Levenshtein distance如何通过 Hamming 或 Levenshtein 距离对字符串进行聚类
【发布时间】:2021-08-30 07:03:21
【问题描述】:

作为练习,我想通过 Hamming 或 Levenshtein 距离对一组英语单词进行聚类。如果是汉明距离,则它们都必须具有相同的长度(或填充到相同的长度),但对于 Levenshtein 距离而言并非如此。

我通常使用scikit-learn,它有很多聚类算法,但似乎没有一个接受分类变量数组,这是表示字符串的最明显方式。

我可以预先计算一个巨大的距离矩阵,但如果字符串的数量很大,这是不现实的。

如何有效地对字符串进行聚类?

【问题讨论】:

  • 这套 N 是多少?这决定了 NxN 距离矩阵的大小,无论它是否庞大,即是否适合内存。
  • @smci 大约 100,000 个字符串。

标签: python cluster-analysis levenshtein-distance hamming-distance


【解决方案1】:

这似乎相关。

https://towardsdatascience.com/applying-machine-learning-to-classify-an-unsupervised-text-document-e7bb6265f52

这似乎也相关。

https://pythonprogramminglanguage.com/kmeans-text-clustering/

此示例使用 Affinity Propagation。

import numpy as np
from sklearn.cluster import AffinityPropagation
import distance
    
words = "kitten belly squooshy merley best eating google feedback face extension impressed map feedback google eating face extension climbing key".split(" ") #Replace this line
words = np.asarray(words) #So that indexing with a list will work
lev_similarity = -1*np.array([[distance.levenshtein(w1,w2) for w1 in words] for w2 in words])

affprop = AffinityPropagation(affinity="precomputed", damping=0.5)
affprop.fit(lev_similarity)
for cluster_id in np.unique(affprop.labels_):
    exemplar = words[affprop.cluster_centers_indices_[cluster_id]]
    cluster = np.unique(words[np.nonzero(affprop.labels_==cluster_id)])
    cluster_str = ", ".join(cluster)
    print(" - *%s:* %s" % (exemplar, cluster_str))
    
    

# Result
 - *squooshy:* squooshy
 - *feedback:* feedback
 - *extension:* extension
 - *impressed:* impressed
 - *google:* google
 - *eating:* climbing, eating
 - *face:* face, map
 - *key:* belly, best, key, kitten, merley

最后,我在数据科学领域工作了至少 8 年,听说过使用 Levenshtein Distance 来计算余弦相似度,但我还没有看到它用于聚类。将余弦相似度和聚类在一起,似乎是有道理的。希望有人在这里发布关于这件事的解决方案。

【讨论】:

  • AffinityPropagation 示例生成了一个预计算矩阵,只有在字符串集很小的情况下才有可能。您提供的第一个链接似乎与文档聚类有关。您是否建议我将单个字符串视为由字母组成的文档?在这种情况下,我们会丢失字符串中字母的所有排序信息。
  • 我对它的解释不同,就像每个“文档”都是一个文本字符串列表。也许这只是模糊的命名法,但我认为我分享的所有示例都说明了聚类文本字符串的意义。
猜你喜欢
  • 1970-01-01
  • 2012-07-25
  • 2016-12-07
  • 2014-07-09
  • 2014-03-16
  • 1970-01-01
  • 2014-02-26
  • 1970-01-01
  • 2012-10-24
相关资源
最近更新 更多