如何通过汉明或莱文斯坦距离对字符串进行聚类

问题描述

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

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

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

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

解决方法

这似乎很相关。

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

这似乎也很重要。

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

这个例子使用了亲和传播。

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 来计算余弦相似度,但我还没有看到它用于聚类。做余弦相似性和聚类在一起,似乎是有道理的。希望有人在这里发布关于这件事的解决方案。