簡體   English   中英

如何通過 Hamming 或 Levenshtein 距離對字符串進行聚類

[英]How to cluster strings by Hamming or Levenshtein distance

作為練習,我想通過 Hamming 或 Levenshtein 距離對一組英語單詞進行聚類。 如果是漢明距離,它們都必須具有相同的長度(或填充到相同的長度),但對於 Levenshtein 距離而言並非如此。

我通常使用scikit-learn ,它有很多聚類算法,但似乎沒有一個接受分類變量的 arrays ,這是表示字符串的最明顯方式。

我可以預先計算一個巨大的距離矩陣,但如果字符串的數量很大,這是不現實的。

如何有效地聚類字符串?

這似乎是相關的。

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 來計算余弦相似度,但我還沒有看到它用於聚類。 將余弦相似度和聚類在一起,似乎是有道理的。 希望有人在這里發布關於這件事的解決方案。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM