Hierarchical Clustering
Solution :
Library Installation:
To install required library files, Open Command Prompt or Terminal and execute the following commands
$ pip install scipy
$ pip install numpy
$ pip install matplotlib
PROGRAM: (HRC.py)
import numpy as np
import matplotlib.pyplot as plt
from scipy.cluster.hierarchy import linkage, dendrogram, fcluster
# Sample dataset
data = np.array([
[0.374540, 0.950714],
[0.731994, 0.598658],
[0.156019, 0.155995],
[0.058084, 0.866176],
[0.601115, 0.708073],
[0.020584, 0.969910],
[0.832443, 0.212340],
[0.181825, 0.183406],
[0.304242, 0.524757],
[0.431945, 0.291229]
])
# Perform Hierarchical Clustering
linked = linkage(data, method='ward')
# Form 3 clusters
clusters = fcluster(linked, t=3, criterion='maxclust')
# Print cluster assignments
print("Data Point\tFeature1\tFeature2\tCluster")
for i, point in enumerate(data):
print(f"{i+1}\t\t{point[0]:.6f}\t{point[1]:.6f}\t{clusters[i]}")
# Scatter Plot
plt.figure(figsize=(8, 6))
colors = ['red', 'green', 'blue']
for i in range(1, 4):
plt.scatter(
data[clusters == i, 0],
data[clusters == i, 1],
color=colors[i-1],
label=f'Cluster {i}',
s=80
)
plt.title("Hierarchical Clustering")
plt.xlabel("Feature 1")
plt.ylabel("Feature 2")
plt.legend()
plt.grid(True)
plt.show()
# Dendrogram
plt.figure(figsize=(10, 7))
dendrogram(
linked,
labels=np.arange(1, len(data) + 1)
)
plt.title("Dendrogram for Hierarchical Clustering")
plt.xlabel("Data Points")
plt.ylabel("Distance")
plt.grid(True)
plt.show()
OUTPUT:
Data Point Feature1 Feature2 Cluster
1 0.374540 0.950714 1
2 0.731994 0.598658 3
3 0.156019 0.155995 2
4 0.058084 0.866176 1
5 0.601115 0.708073 3
6 0.020584 0.969910 1
7 0.832443 0.212340 3
8 0.181825 0.183406 2
9 0.304242 0.524757 2
10 0.431945 0.291229 2
๐ป Run This Python Program
Hierarchical Clustering
The selected Python program is loaded
automatically into the editor.
Edit the program, provide input through
STDIN if required
and click Run.
The compiler is embedded using OneCompiler.
Your Python program runs inside the embedded
Python environment; Study Glance does not execute
Python code directly on your web server.
If the program asks for input, type the value in the
STDIN box before clicking Run.
These programs use libraries such as NumPy, Pandas,
Matplotlib, scikit-learn, SciPy and statsmodels, and
graph windows (
plt.show()) cannot be displayed
here. The data files shown in the lesson (CSV) are loaded
into the editor automatically. If a library is not
available in the embedded compiler, use
Copy Program and run the program on your
computer (after pip install of the libraries)
or in Google Colab.