SciPy Dendrogram Plotting - PullRequest
       31

SciPy Dendrogram Plotting

0 голосов
/ 21 февраля 2020

Я играю с кластеризацией иерархических документов, и фактически мой рабочий процесс примерно такой:

df = pandas.read_csv(file, delimiter='\t', index_col=0) # documents-terms matrix (very sparse)
dist_matrix = cosine_similarity(df)

linkage_matrix = ward(dist_matrix)
labels = fcluster(linkage_matrix, 5, criterion='maxclust')

Тогда я ожидаю получить 5 кластеров, но когда я строю дендрограмму

fig, ax = plt.subplots(figsize=(15, 20))  # set size
    ax = dendrogram(linkage_matrix, orientation="right")
    plt.tick_params( \
        axis='x',  # changes apply to the x-axis
        which='both',  # both major and minor ticks are affected
        bottom='off',  # ticks along the bottom edge are off
        top='off',  # ticks along the top edge are off
        labelbottom='off')

    plt.tight_layout()  # show plot with tight layout

    plt.savefig('ward_clusters.png', dpi=200)  # save figure as ward_clusters

Я получаю следующий график

enter image description here

На основе цветов я вижу 3 кластера, а не 5! Неужели я неправильно понимаю значение дендрограммы?

1 Ответ

1 голос
/ 21 февраля 2020
  • Прежде всего, если вы просто хотите создать 5 кластеров, просто используйте метки (строка с fcluster, которую вы не использовали).

В метках: каждая точка из вашего набора данных представлен числом. Эти числа являются идентификаторами ваших кластеров.

  • Если вы хотите использовать дендограмму и построить 5 различных кластеров, вам придется «вырезать» вашу дендограмму.

Нарисуйте вертикальную линию в точке x = 5 (около 5), учтите, что каждая дендограмма слева независима.

enter image description here

Искусственно, вы Разрежьте свою дендограмму на 5 частей (или 5 кластеров).

Чтобы добавить немного цвета для их дифференциации, просто адаптируйте следующий код (так как вы не предоставили свой набор данных, я использовал набор данных iris, чтобы показать вам один из них). возможное решение)

from scipy.cluster.hierarchy import *
from sklearn.datasets import load_iris
from sklearn.metrics.pairwise import cosine_similarity
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

iris= load_iris()

data = iris['data']
df = pd.DataFrame(data, columns = iris['feature_names'])

# Somehow, we have something equivalent to work with now
dist_matrix = cosine_similarity(df)
linkage_matrix = ward(dist_matrix)

fig, ax = plt.subplots(figsize=(20, 10))

#here just put 5 for the color_threshold, which correspond to the position of the vertical line
ax = dendrogram(linkage_matrix, color_threshold =0.7)

plt.tick_params( \
    axis='x',
    which='both',
    bottom='off',
    top='off',
    labelbottom='off')

plt.show()

enter image description here

...