[英]How to find string similar to 2 other strings (in terms of Levenshtein distance)?
[英]How to cluster strings by Hamming or Levenshtein distance
作为练习,我想通过 Hamming 或 Levenshtein 距离对一组英语单词进行聚类。 如果是汉明距离,它们都必须具有相同的长度(或填充到相同的长度),但对于 Levenshtein 距离而言并非如此。
我通常使用scikit-learn ,它有很多聚类算法,但似乎没有一个接受分类变量的 arrays ,这是表示字符串的最明显方式。
我可以预先计算一个巨大的距离矩阵,但如果字符串的数量很大,这是不现实的。
如何有效地聚类字符串?
这似乎是相关的。
这似乎也很相关。
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 来计算余弦相似度,但我还没有看到它用于聚类。 将余弦相似度和聚类在一起,似乎是有道理的。 希望有人在这里发布关于这件事的解决方案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.