머신러닝

Hierarchical Clustering 과 Dendrogram 보기

HooSL 2022. 3. 28. 15:49

구글드라이브 import

from google.colab import drive
drive.mount('/content/drive')

필요한 라이브러리 한글 가능 import

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
df=pd.read_csv('/content/drive/MyDrive/위치/Mall_Customers.csv')

 

 

X값 설정

X=df.iloc[:,3:]

 

Dendrogram 그리고, 최적의 클러스터 개수를 찾아봅니다.

필요한 라이브러리 먼저 import 합니다.

import scipy.cluster.hierarchy as sch

 

sch.dendrogram(sch.linkage(X,method='ward'))
plt.title('Dendrogram')
plt.xlabel('Customers')
plt.ylabel('Euclidean Distances')
plt.show()

Training the Hierarchical Clustering model

 

from sklearn.cluster import AgglomerativeClustering

hc = AgglomerativeClustering(n_clusters = 5)
y_pred=hc.fit_predict(X)
df['Group']=y_pred
df

 

그루핑 정보를 확인

plt.scatter(X.values[y_pred == 0, 0], X.values[y_pred == 0, 1], s = 100, c = 'red', label = 'Cluster 1')
plt.scatter(X.values[y_pred == 1, 0], X.values[y_pred == 1, 1], s = 100, c = 'blue', label = 'Cluster 2')
plt.scatter(X.values[y_pred == 2, 0], X.values[y_pred == 2, 1], s = 100, c = 'green', label = 'Cluster 3')
plt.scatter(X.values[y_pred == 3, 0], X.values[y_pred == 3, 1], s = 100, c = 'cyan', label = 'Cluster 4')
plt.scatter(X.values[y_pred == 4, 0], X.values[y_pred == 4, 1], s = 100, c = 'magenta', label = 'Cluster 5')
plt.title('Clusters of customers')
plt.xlabel('Annual Income (k$)')
plt.ylabel('Spending Score (1-100)')
plt.legend()
plt.show()