Как классифицировать новое слово в кластеры распространения сродства? - PullRequest
0 голосов
/ 08 февраля 2019

Я читал здесь (первый ответ):

https://stats.stackexchange.com/questions/123060/clustering-a-long-list-of-strings-words-into-similarity-groups

И мне нужно выяснить, как определить расстояние для нового слова и получить кластер, в котором это слово лучше всего.вписывается в.

word_use = #random word here
lev_similarity = -1*np.array([distance.levenshtein(word_use,w1) for w1 in words])
affprop.fit(lev_similarity) 
exemplar = words[affprop.cluster_centers_indices_[cluster_id]]
cluster = np.unique(word_use[np.nonzero(affprop.labels_==cluster_id)])
print("%s: %s" % (exemplar, word_use))

Это столько, сколько я получил сейчас, но я получаю сообщение об ошибке в строке affprop.fit(lev_similarity):

Reshape your data either using array.reshape(-1, 1) if your data has a single feature 
or array.reshape(1, -1) if it contains a single sample.

И при попыткеисправить это, я сделал это в этой строке: affprop.fit(lev_similarity.reshape(-1, 1))

Но независимо от того, я делаю (-1,1) или (1, -1), я получаю:

S must be a square array (shape=(40, 1))

или

S must be a square array (shape=(1, 40))

И я потерян.

Соответствующая часть моего кода воспроизведена ниже, так что вы можете попробовать его (вставьте случайные слова):

import numpy as np
import sklearn.cluster
import distance
import random
import csv

words = "hi hello yes now please one two three greg test".split(" ") 
words = np.asarray(words)
lev_similarity = -1*np.array([[distance.levenshtein(w1,w2) for w1 in words] for w2 in words])

affprop = sklearn.cluster.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))

word_use = "cannon"
lev_similarity = -1*np.array([distance.levenshtein(word_use,w1) for w1 in words])
affprop.fit(lev_similarity.reshape(-1, 1)) 
exemplar = words[affprop.cluster_centers_indices_[cluster_id]]
cluster = np.unique(word_use[np.nonzero(affprop.labels_==cluster_id)])
print(word_use)
print("%s: %s" % (exemplar, word_use))
...