# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: Python 3
#     language: python
#     name: python3
# ---

# # K-Means Clustering



# # Hierarchical Clustering

# +
# Title: Hierarchical Clustering Project in Python

# Importing the needed libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# -

# Importing the dataset
dataset = pd.read_csv('datasets/Customers.csv')
dataset.head()

X = dataset.loc[:, ['AnnualSalary(k$)', 'Spendings(1-100)']].values
XX = pd.DataFrame(X)
XX.head()

print(XX.shape)
XX.describe()

# +
# Visualising the clusters and interpretation
plt.scatter(X[:,0], X[:, 1], s = 80, c = 'blue', label = 'Data')

plt.title('Clusters of customers')
plt.xlabel('Annual Salary (k$)')
plt.ylabel('Spendings (1 to 100)')
plt.legend()
plt.show()
# -

# Using the dendrogram to find optimal number of clusters
import scipy.cluster.hierarchy as sch

dendrogram = sch.dendrogram(sch.linkage(X, method = 'ward'))
#ward is to minimize the variance of each cluster
plt.title('Dendrogram')
plt.xlabel('Customers')
plt.ylabel('Euclidean distances')
plt.show()

# Fitting Hierarchical Clustering to our Data
from sklearn.cluster import AgglomerativeClustering

#Making predictions
hc = AgglomerativeClustering(n_clusters = 4, affinity = 'euclidean', linkage = 'ward')
y_hc = hc.fit_predict(X)

type(y_hc) # numpy.ndarray
y_hc.shape # (250,)
y_hc

# +
# Visualising the clusters and interpretation
plt.scatter(X[y_hc == 0, 0], X[y_hc == 0, 1], s = 80, c = 'cyan', label = '1st Cluster')
plt.scatter(X[y_hc == 1, 0], X[y_hc == 1, 1], s = 80, c = 'green', label = '2nd Cluster')
plt.scatter(X[y_hc == 2, 0], X[y_hc == 2, 1], s = 80, c = 'red', label = '3rd Cluster')
plt.scatter(X[y_hc == 3, 0], X[y_hc == 3, 1], s = 80, c = 'blue', label = '4th Cluster')

plt.title('Clusters of customers')
plt.xlabel('Annual Salary (k$)')
plt.ylabel('Spendings (1 to 100)')
plt.legend()
plt.show()
# -



StarcoderdataJupyterScriptsDedupFiltered