Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
debakarr
GitHub Repository: debakarr/machinelearning
Path: blob/master/Part 4 - Clustering/Hierarchical Clustering/hc.py
1009 views
1
# Hierarchical Clustering
2
3
# Importing the libraries
4
import numpy as np
5
import matplotlib.pyplot as plt
6
import pandas as pd
7
8
# Importing the dataset
9
dataset = pd.read_csv('Mall_Customers.csv')
10
X = dataset.iloc[:, [3, 4]].values
11
# y = dataset.iloc[:, 3].values
12
13
# Splitting the dataset into the Training set and Test set
14
"""from sklearn.cross_validation import train_test_split
15
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0)"""
16
17
# Feature Scaling
18
"""from sklearn.preprocessing import StandardScaler
19
sc_X = StandardScaler()
20
X_train = sc_X.fit_transform(X_train)
21
X_test = sc_X.transform(X_test)
22
sc_y = StandardScaler()
23
y_train = sc_y.fit_transform(y_train)"""
24
25
# Using the dendrogram to find the optimal number of clusters
26
import scipy.cluster.hierarchy as sch
27
dendrogram = sch.dendrogram(sch.linkage(X, method = 'ward'))
28
plt.title('Dendrogram')
29
plt.xlabel('Customers')
30
plt.ylabel('Euclidean distances')
31
plt.show()
32
33
# Fitting Hierarchical Clustering to the dataset
34
from sklearn.cluster import AgglomerativeClustering
35
hc = AgglomerativeClustering(n_clusters = 5, affinity = 'euclidean', linkage = 'ward')
36
y_hc = hc.fit_predict(X)
37
38
# Visualising the clusters
39
plt.scatter(X[y_hc == 0, 0], X[y_hc == 0, 1], s = 100, c = 'red', label = 'Cluster 1')
40
plt.scatter(X[y_hc == 1, 0], X[y_hc == 1, 1], s = 100, c = 'blue', label = 'Cluster 2')
41
plt.scatter(X[y_hc == 2, 0], X[y_hc == 2, 1], s = 100, c = 'green', label = 'Cluster 3')
42
plt.scatter(X[y_hc == 3, 0], X[y_hc == 3, 1], s = 100, c = 'cyan', label = 'Cluster 4')
43
plt.scatter(X[y_hc == 4, 0], X[y_hc == 4, 1], s = 100, c = 'magenta', label = 'Cluster 5')
44
plt.title('Clusters of customers')
45
plt.xlabel('Annual Income (k$)')
46
plt.ylabel('Spending Score (1-100)')
47
plt.legend()
48
plt.show()
49