Skip to content

Instantly share code, notes, and snippets.

@DFoly
Last active February 8, 2019 09:15
Show Gist options
  • Select an option

  • Save DFoly/b6ed3566f1c6f2af86c6a9dc18ffcac9 to your computer and use it in GitHub Desktop.

Select an option

Save DFoly/b6ed3566f1c6f2af86c6a9dc18ffcac9 to your computer and use it in GitHub Desktop.
def get_top_features_cluster(tf_idf_array, prediction, n_feats):
labels = np.unique(prediction)
dfs = []
for label in labels:
id_temp = np.where(prediction==label) # indices for each cluster
x_means = np.mean(tf_idf_array[id_temp], axis = 0) # returns average score across cluster
sorted_means = np.argsort(x_means)[::-1][:n_feats] # indices with top 20 scores
features = tf_idf_vectorizor.get_feature_names()
best_features = [(features[i], x_means[i]) for i in sorted_means]
df = pd.DataFrame(best_features, columns = ['features', 'score'])
dfs.append(df)
return dfs
dfs = get_top_features_cluster(tf_idf_array, prediction, 15)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment