SciPy - dendrogram() Method



The SciPy dendrogram() method is referenced from the module "scipy.cluster.hierarchy" that determine its functionality by cutting clusters at a particular height.

This method help us to visualize the clustering graph and show the arrangements.

Syntax

Following is the syntax of the SciPy dendrogram() method −

dendrogram(res)

Parameters

Below is the explanation −

  • res: This parameter store the linkage() method which accepts two paramters which are "data" and "method = 'type'" to generate the graph in the form of heirarchical clustering.

Return value

The method render the dendrogram which means it returns the result as a graphical views.

Example 1

Following is the SciPy example that shows the usage of dendrogram() method.

import numpy as np
from scipy.cluster.hierarchy import dendrogram, linkage
import matplotlib.pyplot as plt

# given data
data = np.array([[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]])

# hierarchical clustering using ward
res = linkage(data, method='ward')

# create a dendrogram
dendrogram(res)

# show the plot
plt.show()

Output

The above code produces the following output −

dendrogram_example_one

Example 2

Here, we perform the task of truncated dendrogram and it shows the last 4 merges.

import numpy as np
from scipy.cluster.hierarchy import dendrogram, linkage
import matplotlib.pyplot as plt

# input data
data = np.random.rand(15, 4)

# hierarchical clustering
res = linkage(data, method='average')

# create a truncated dendrogram
dendrogram(res, truncate_mode='lastp', p=4)

# show the plot
plt.show()

Output

The above code produces the following output −

dendrogram_example_two

Example 3

Below the example shows the dendrogram with a color threshold. Here, you get the graph color as orange.

Note that, color threshold define the better visibility of a graph.

import numpy as np
from scipy.cluster.hierarchy import dendrogram, linkage
import matplotlib.pyplot as plt

# input data
data = np.random.rand(15, 3)

# hierarchical clustering
res = linkage(data, method='single')

# create dendrogram with color threshold
dendrogram(res, color_threshold=0.5)

# show the plot
plt.show()

Output

The above code produces the following output −

dendrogram_example_three
scipy_reference.htm
Advertisements