군집 분석
` 각 데이터의 유사성을 측정하여 높은 대상 집단을 분류하고 군집 간에 상이성을 규명
- K-means : 사용자가 지정한 k개의 군집으로 나누기
- Hierarchical : 나무 모양의 계층 구조를 형성해 나감.
- DBSCAN : 밀도 기반 군집, K개 설정 필요없음.
Hierarchical Clustering
- 가까운 집단부터 계층적으로 묶어나감
- dendogram을 통해 시각화 가능
- 군집의 개수를 정하지 않아도 되나 데이터가 많을 경우 시각화나 많은 계층으로 나누기가 힘들어 데이터가 적으면 보기 좋음.
방법
- 모든 개체들 사이의 유사도 행렬 계산
- 거리가 인접한 관측치끼리 cluster 형성
- 유사도 행렬 update
아래와 같이 A와D가 같은 군집으로 묶이면 AD로 묶임

- 유사도 계산은 cluster 거리의 최소, 최대를 기준으로 하거나 평균, centroid 기준으로 계산됨.
- 주로 ward 연결법이 쓰인다.
apply
1
2
|
customer_data = pd.read_csv('./data/shopping-data.csv')
customer_data.head()
|
|
CustomerID |
Genre |
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 |
1
|
data = customer_data.iloc[:, 3:5].values
|
덴드로그램 보기
1
2
3
4
5
6
|
import scipy.cluster.hierarchy as shc
plt.figure(figsize=(10, 7))
plt.title("Customer Dendograms")
# ward가 기준
dend = shc.dendrogram(shc.linkage(data, method='ward'))
|

군집 시각화
1
2
3
4
|
from sklearn.cluster import AgglomerativeClustering
cluster = AgglomerativeClustering(n_clusters=5, affinity='euclidean', linkage='ward')
cluster.fit_predict(data)
|
array([4, 3, 4, 3, 4, 3, 4, 3, 4, 3, 4, 3, 4, 3, 4, 3, 4, 3, 4, 3, 4, 3,
4, 3, 4, 3, 4, 3, 4, 3, 4, 3, 4, 3, 4, 3, 4, 3, 4, 3, 4, 3, 4, 1,
4, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 2, 1, 2, 0, 2, 0, 2,
1, 2, 0, 2, 0, 2, 0, 2, 0, 2, 1, 2, 0, 2, 1, 2, 0, 2, 0, 2, 0, 2,
0, 2, 0, 2, 0, 2, 1, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2,
0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2,
0, 2], dtype=int64)
1
2
|
plt.figure(figsize=(10, 7))
plt.scatter(data[:,0], data[:,1], c=cluster.labels_, cmap='rainbow')
|
