1

I want to obtain a list of unique taggs from K-Means clustering. I have the following code:

def cluster_tagging(variable_a_taggear):

document = result[variable_a_taggear]
vectorizer = TfidfVectorizer(ngram_range=(1, 5))

X = vectorizer.fit_transform(document)

true_k = 180
puntos2= true_k

if model_setting == 'MiniBatchKMeans':
    #model = MiniBatchKMeans(n_clusters=true_k, init='k-means++', max_iter=1000, n_init=1)
    pass
elif model_setting == 'KMeans':
    model = KMeans(n_clusters=true_k, init='k-means++', max_iter=10000000, n_init=1)


model.fit(X)

order_centroids = model.cluster_centers_.argsort()[:, ::-1]
terms = vectorizer.get_feature_names()
#print(terms[:8])

cluster_ = []
key_ = []
ID = []

cluster_col = 'Cluster_%s'%(variable_a_taggear)
keywords_col = 'Keywords_%s'%(variable_a_taggear)
word_cloud = pd.DataFrame(columns=[cluster_col, keywords_col])

for i in range(puntos2):
    print('Cluster %s:' % (i))
    cluster_.append(i)
    key_1 = []
    key_1 = list(set(key_1))
    key_.append(key_1)

    for ind in order_centroids[i, :8]:
        print('%s' % terms[ind])
        terms_ = terms[ind]
        key_1.append(terms_)

print('first key_', key_)
info = {cluster_col:cluster_,keywords_col:key_}

word_cloud = pd.DataFrame(info)
word_cloud.head()


#print('Prediction')

predicted = model.predict(vectorizer.transform(document))
lst2 = result['Ticket ID']
predictions = pd.DataFrame(list(zip(predicted, lst2)), columns =[cluster_col, 'Ticket ID'])

#predictions = pd.DataFrame(predicted,result['Ticket ID'])
predictions.columns = [cluster_col, 'Ticket ID']
#print(predictions)

resultado = pd.merge(predictions, word_cloud, left_on=cluster_col, right_on=cluster_col, how='inner')
print(resultado.head())
return resultado

As you can observe with n-grams I obtain repeated words as part of different n-grams. For example, for one cluster I have the following taggs: [['fecha iniciar', 'iniciar', 'modificar fecha iniciar cc', 'proceder modificar fecha iniciar', 'proceder modificar fecha iniciar cc', 'fecha iniciar cc', 'iniciar cc', 'fecha'] How can I obtain a list of unique words for each cluster?

Thanks

Ley
  • 67
  • 6

1 Answers1

0

Question: How can I obtain a list of unique words for each cluster?

You can use nltk to separate words within a sentence and numpy.unique to get unique values within an array.

import numpy as np
from nltk.tokenize import word_tokenize

cluster_tags  = ['fecha iniciar', 'iniciar', ..., 'fecha']
one_string = ' '.join(cluster_tags)
np.unique(word_tokenize(one_string))

If you are certain that all words are always separated by a clean space ' ', you can simply split them...

np.unique(' '.join(cluster_tags).split())

Bonus tip: If you want, you could count the frequency of each word.

# See answer by Max Malysh: https://stackoverflow.com/questions/952914/how-to-make-a-flat-list-out-of-list-of-lists
from collections import Counter
from pandas.core.common import flatten

tokenized = [word_tokenize(text) for text in cluster_tags]
Counter(flatten(tokenized))
Florian Fasmeyer
  • 795
  • 5
  • 18