如何使用Kmeans对术语(1-2个单词)进行聚类。我读了一篇研究论文,他们使用K均值使用Levenshtein距离对相似的术语进行聚类。请通过显示示例代码来帮助我。
谢谢
注意:在研究论文中,他们使用Levenshtein距离计算了相似度矩阵,并将其用于聚类。
答案 0 :(得分:0)
def get_levenshtein_distance(word1, word2):
word2 = word2.lower()
word1 = word1.lower()
matrix = [[0 for x in range(len(word2) + 1)] for x in range(len(word1) + 1)]
for x in range(len(word1) + 1):
matrix[x][0] = x
for y in range(len(word2) + 1):
matrix[0][y] = y
print(matrix)
答案 1 :(得分:0)
from nltk.metrics import distance
import scipy.spatial as spatial
import numpy as np
from scipy.cluster.vq import kmeans
# sample vocabulary list
words = ['test', 'text', 'best', 'fast', 'context', 'boost', 'faster', 'border']
# similarity matrix
word_vectors = np.array([
[
distance.edit_distance(w, _w)
for _w in words
]
for w in words
], dtype=np.float)
centroids, _ = kmeans(word_vectors, k_or_guess=3)
word_clusters = np.argmin([
[spatial.distance.euclidean(wv, cv) for cv in centroids]
for wv in word_vectors
], 1)
for k in range(centroids.shape[0]):
print('k =', k)
print([word for i, word in enumerate(words) if word_clusters[i] == k])
结果为:
k = 0
['faster', 'border']
k = 1
['test', 'text', 'best', 'fast', 'boost']
k = 2
['context']
备注:
spatial.distance.euclidean
。np.argmin([...], 1)
正在为每个单词找到这样的分配。答案 2 :(得分:0)
初始化一个矩阵,在(m,n)单元中测量一个m字符前缀与另一个单词n前缀之间的Levenshtein距离。矩阵可以从左上角到右下角填充。