클러스터링 실습 (2)(EDA,Sklearn)

Assignment 3

- Clustering 해보기

우수과제 선정이유

각 클러스터링 방법에 대해 포인트를 잘 잡고 과제를 진행해주시며 마지막에 결론에 해당하는 시각화까지 완벽하게 해주셔서 우수과제로 선정되었습니다.

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 *

Load mall customers data

In [2]:

Out[2]:

CustomerID

Gender

Age

Annual Income (k$)

Spending Score (1-100)

0

1

Male

19

15

39

1

2

Male

21

15

81

2

3

Female

20

16

6

3

4

Female

23

16

77

4

5

Female

31

17

40

In [3]:

  • ID 값은 clustering을 하는데 있어 필요하지 않아 보이므로 제거하기로 하였다.

In [4]:

Out[4]:

In [5]:

  • 문자형 데이터를 encoding 하였다.

In [6]:

Out[6]:

Gender

Age

Annual Income (k$)

Spending Score (1-100)

0

1

19

15

39

1

1

21

15

81

2

0

20

16

6

3

0

23

16

77

4

0

31

17

40

In [7]:

Out[7]:

EDA

Describe

In [8]:

In [9]:

Out[9]:

  • null 값이 존재하지 않는다 !

In [10]:

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]:

  • Female인 경우가 더 많은 것을 알 수 있다.

In [12]:

  • 성별에 따른 pairplot을 찍어보았는데 구분할 수 있을 정도의 차이를 보이지는 않았다.

In [13]:

  • 변수 간 선형상관관계가 거의 없어 보인다.

Modeling

PCA

In [14]:

Out[14]:

  • 평면에 시각화를 위해 PCA를 이용해 2차원으로 차원 축소를 진행하였다.

  • 평가는 시각화 및 Silhouette Coefficient, Davies bouldin score로 진행하였다.

  • Silhouette Coefficient는 실루엣 계수로 -1 부터 1사이의 값을 가지며 1에 가까울 수록 최적화된 군집이라고 할 수 있다.

  • Davies Bouldin Index는 Group 내에서의 Distribution과 비교하여 다른 Group간의 분리 정도의 비율로 계산되는 값으로 모든 두 개의 Group 쌍에 대해 각 Group의 크기의 합을 각 Group의 중심 간 거리로 나눈 값으로서 표현되는 함수이다. 즉, 값이 작을수록 최적화된 군집이라고 할 수 있다.

1. K-Means

In [15]:

  • K-Means의 k를 설정하기 위해 Elbow curve를 그려보았다.

  • k=5 일때 급격한 distortions의 변화가 일어난 것으로 보아 cluster 수를 5로 설정하기로 하였다.

In [16]:

2. DBScan

In [17]:

In [18]:

  • standard scaler로 스케일링을 진행한 데이터에 대해서 DBScan으로 군집을 확인해보았다.

  • eps가 변화하면서 생성되는 군집의 변화를 알 수 있다.

  • Scaled data와 Not Scaled data 모두 Silhouette Coefficient가 0.5를 넘지 않아 좋은 결과를 보이고 있지는 않은 것 같다.

  • Not Scaled Data는 ep가 8일 때, Scaled Data는 ep가 0.3일 때가 가장 적절해 보인다.

3. Hierarchical agglomerative clustering

In [19]:

  • 5개의 cluster보다 많아질 경우 Cluster간 거리가 급격히 줄어드는 것으로 보아 5개의 Cluster로 자르는 것이 적절해 보인다.

4. Agglomerative Clustering

In [20]:

  • Silhouette Coefficient 계수가 가장 큰 것은 5개의 클러스터로 나눈 경우이다.

  • Davies Bouldin Index가 가장 작은 것 또한 5개의 클러스터로 나눈 경우이다.

  • 따라서 5개의 클러스터로 나눈 경우가 가장 적절해 보인다.

5. Affinity Propagation

In [21]:

6. Mean Shift

In [22]:

  • sample의 수가 100개일 때 가장 좋은 성능을 보이고 있다.

Evaluation

No Scaled Data

In [23]:

Scaled Data

In [24]:

  • 마지막으로 모든 알고리즘을 한 번에 시각화해 보았다.

  • 실루엣 계수에 의하면 K Means Clustering이 가장 최적화된 군집을 생성해냈다고 할 수 있다.

  • Scaled Data와 Not Scaled Data를 비교해보았을 때, Affinity Propagation과 Meanshift 알고리즘에서는 Scaling 된 데이터가 더 잘 군집을 생성해냈다.

Last updated

Was this helpful?