In [1]:
from IPython.core.display import display, HTML
display(HTML("<style>.container { width:1200px !important; }</style>"))
평균 이동 군집화¶
중심을 데이터가 모여 있는 밀도가 가장 높을 곳으로 이동. 데이터의 분포도를 이용해 군집 중심점을 찾는다.
군집 중심점은 데이터 포인트가 모여있는 곳> 확률 밀도 함수를 이용
가장 집붖ㅇ적으로 데이터가 모여있어 확률 밀도 함수가 피크인 점을 군집 중심점으로 선정. 주어진 모델의 확률 밀도 함수를 찾기 위해서 KDE를 이용.
KDE : 커널 함수를 통해 어떤 변수의 확률 밀도 함수를 추정하는 대표적인 방법. 관측된 데이터 각각에 커널 함수를 적용한 값을 모두 더한 뒤 데이터 건수로 나눠 확률 밀도 함수를 추정
확률 밀도 함수 : 정규분포 함수, 감마 분포, t-분포
대역폭(h = bandwidth)이 클수록 적은 수의 군집 중심점을 가지며, 대역폭이 작을수록 많은 수의 군집 중심점을 가진다. 평균 이동 군집화는 군집의 개수를 지정하지 않으며 대역폭의 크기에 따라 군집화를 수행한다.
In [2]:
# cluster_std =0.7(생성할 군집화들의 표준 편차)
import numpy as np
from sklearn.datasets import make_blobs
from sklearn.cluster import MeanShift
X, y = make_blobs(n_samples=200, n_features=2, centers=3,
cluster_std=0.7, random_state=0)
meanshift= MeanShift(bandwidth=0.8)
cluster_labels = meanshift.fit_predict(X)
print('cluster labels 유형:', np.unique(cluster_labels))
cluster labels 유형: [0 1 2 3 4 5]
In [3]:
meanshift= MeanShift(bandwidth=1)
cluster_labels = meanshift.fit_predict(X)
print('cluster labels 유형:', np.unique(cluster_labels))
cluster labels 유형: [0 1 2]
In [5]:
from sklearn.cluster import estimate_bandwidth
bandwidth = estimate_bandwidth(X)
print('bandwidth 값 = bandwidth의 최적화 값:', round(bandwidth,3))
bandwidth 값 = bandwidth의 최적화 값: 1.816
In [6]:
import pandas as pd
clusterDF = pd.DataFrame(data=X, columns=['ftr1', 'ftr2'])
clusterDF['target'] = y
# estimate_bandwidth()로 최적의 bandwidth 계산
best_bandwidth = estimate_bandwidth(X)
meanshift= MeanShift(bandwidth=best_bandwidth)
cluster_labels = meanshift.fit_predict(X)
print('cluster labels 유형:',np.unique(cluster_labels))
cluster labels 유형: [0 1 2]
In [7]:
import matplotlib.pyplot as plt
%matplotlib inline
clusterDF['meanshift_label'] = cluster_labels
centers = meanshift.cluster_centers_
unique_labels = np.unique(cluster_labels)
markers=['o', 's', '^', 'x', '*']
for label in unique_labels:
label_cluster = clusterDF[clusterDF['meanshift_label']==label]
center_x_y = centers[label]
# 군집별로 다른 marker로 scatter plot 적용
plt.scatter(x=label_cluster['ftr1'], y=label_cluster['ftr2'], edgecolor='k',
marker=markers[label] )
# 군집별 중심 시각화
plt.scatter(x=center_x_y[0], y=center_x_y[1], s=200, color='white',
edgecolor='k', alpha=0.9, marker=markers[label])
plt.scatter(x=center_x_y[0], y=center_x_y[1], s=70, color='k', edgecolor='k',
marker='$%d$' % label)
plt.show()
In [8]:
print(clusterDF.groupby('target')['meanshift_label'].value_counts())
target meanshift_label 0 0 67 1 1 67 2 2 66 Name: meanshift_label, dtype: int64
데이터 세트의 형태를 특정 형태로 가정, 특정 분포도 기반의 모델로 가정하지 않기 때문에 유연한 군집화가 가능
이상치의 영향력이 크지 않다. 미리 군집의 개수를 정하지 않아도 된다.
In [ ]:
'머신러닝' 카테고리의 다른 글
[파이썬 머신러닝] 7장. 실습-고객 세그먼테이션 (0) | 2021.02.09 |
---|---|
[파이썬 머신러닝] 7장. GMM, DBSCAN (0) | 2021.02.07 |
[파이썬 머신러닝] 7장. 군집 평가 (0) | 2021.02.07 |
[파이썬 머신러닝] 7장. K-Means (0) | 2021.02.07 |
[파이썬 머신러닝] 6장.차원 축소 - SVD, NMF (0) | 2021.02.01 |