각 클러스터링 방법에 대해 포인트를 잘 잡고 과제를 진행해주시며 마지막에 결론에 해당하는 시각화까지 완벽하게 해주셔서 우수과제로 선정되었습니다.
Load Dataset
Import packages
In [1]:
# data
import pandas as pd
import numpy as np
import warnings
warnings.filterwarnings("ignore")
# visualization
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
# preprocessing
from sklearn.preprocessing import StandardScaler
from sklearn.preprocessing import MinMaxScaler
from sklearn.decomposition import PCA
from sklearn.model_selection import train_test_split
# model
from sklearn.cluster import KMeans
from sklearn.cluster import DBSCAN
from scipy.cluster.hierarchy import dendrogram, ward
from sklearn.cluster import AgglomerativeClustering
from sklearn.cluster import AffinityPropagation
from sklearn.cluster import MeanShift, estimate_bandwidth
# grid search
from sklearn.model_selection import GridSearchCV
# evaluation
from sklearn.metrics.cluster import silhouette_score
from sklearn.model_selection import cross_val_score
from sklearn import metrics
from sklearn.metrics import *
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 200 entries, 0 to 199
Data columns (total 4 columns):
Gender 200 non-null int64
Age 200 non-null int64
Annual Income (k$) 200 non-null int64
Spending Score (1-100) 200 non-null int64
dtypes: int64(4)
memory usage: 6.4 KB
In [9]:
df.isnull().sum()
Out[9]:
Gender 0
Age 0
Annual Income (k$) 0
Spending Score (1-100) 0
dtype: int64
null 값이 존재하지 않는다 !
In [10]:
df.describe()
Out[10]:
Gender
Age
Annual Income (k$)
Spending Score (1-100)
count
200.000000
200.000000
200.000000
200.000000
mean
0.440000
38.850000
60.560000
50.200000
std
0.497633
13.969007
26.264721
25.823522
min
0.000000
18.000000
15.000000
1.000000
25%
0.000000
28.750000
41.500000
34.750000
50%
0.000000
36.000000
61.500000
50.000000
75%
1.000000
49.000000
78.000000
73.000000
max
1.000000
70.000000
137.000000
99.000000
Visualization
In [11]:
sns.countplot('Gender' , data = df)
plt.show()
Female인 경우가 더 많은 것을 알 수 있다.
In [12]:
sns.pairplot(df, hue="Gender")
plt.show()
성별에 따른 pairplot을 찍어보았는데 구분할 수 있을 정도의 차이를 보이지는 않았다.
In [13]:
g = sns.heatmap(df.corr(), annot=True, linewidths=.5)
bottom, top = g.get_ylim() # heatmap plot이 잘리는 것 방지하기 위한 방법
g.set_ylim(bottom+0.5, top-0.5)
plt.show()
평가는 시각화 및 Silhouette Coefficient, Davies bouldin score로 진행하였다.
Silhouette Coefficient는 실루엣 계수로 -1 부터 1사이의 값을 가지며 1에 가까울 수록 최적화된 군집이라고 할 수 있다.
Davies Bouldin Index는 Group 내에서의 Distribution과 비교하여 다른 Group간의 분리 정도의 비율로 계산되는 값으로 모든 두 개의 Group 쌍에 대해 각 Group의 크기의 합을 각 Group의 중심 간 거리로 나눈 값으로서 표현되는 함수이다. 즉, 값이 작을수록 최적화된 군집이라고 할 수 있다.
1. K-Means
In [15]:
distortions = []
for k in range(2, 20):
kmeans = KMeans(n_clusters=k)
kmeans.fit(reduced_df)
distortions.append(kmeans.inertia_)
fig = plt.figure(figsize=(10, 5))
plt.plot(range(2, 20), distortions)
plt.grid(True)
plt.title('Elbow curve')
plt.show()
K-Means의 k를 설정하기 위해 Elbow curve를 그려보았다.
k=5 일때 급격한 distortions의 변화가 일어난 것으로 보아 cluster 수를 5로 설정하기로 하였다.