Menu

Predictive Analytics - (LAB PROGRAMS)


Aim:

  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

 

 



Related Content :

1. Simple Linear regression.   View Solution


2. Multiple Linear regression.   View Solution


3. Logistic Regression.   View Solution


4. CHAID.   View Solution


5. CART.   View Solution


6. ARIMA - stock market data.   View Solution


7. Exponential Smoothing.   View Solution


8. Hierarchical clustering.   View Solution


9. Ward's method of clustering.   View Solution


10. Crowdsource predictive analytics- Netflix data.   View Solution