군집화, K-Means Clustering

2025. 10. 28. 13:12·AI Study/Machine Learning

K-Means 군집화

개체들 간 거리가 가까운 것끼리 K개의 그룹을 만드는 군집화의 한 방법

 

군집 수는(K) 데이터의 분포에 따라 달라진다.

K를 정하는 방법: 군집의 수에 따라 TWSS의 기울기가 급격히 작아지는 지점(elbow point)의 K로 채택.

 

WSS: within-cluster sum of squares

각 군집 내에서 개체들과 군집 중심 간 유클리디안 거리의 합


TWSS: total WSS


군집화 절차

 


[간단한 데이터로 실습]

 

라이브러리 임포트

from sklearn.cluster import KMeans
from sklearn.preprocessing import StandardScaler

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns

1단계: 데이터 작성

X = np.array([[45,3],[9,12],[15,10],[60,5],[21,15],[43,15],[45,13],[52,14]])
X

2단계: 탐색적 데이터 분석

plt.scatter(X[:,0],X[:,1])
plt.xlabel('X')
plt.ylabel('Y')
plt.xlim(0,70)
plt.ylim(0,20)
for i in range(len(X)):
  plt.annotate(str(i+1),(X[i][0],X[i][1]))

3단계: 피처 스케일링

scaler = StandardScaler()
scaler.fit(X)
X_std = scaler.transform(X)

4단계: 군집화

TWSS = {}

for k in range(1,6):
  model = KMeans(n_clusters=k)
  model.fit(X_std)
  model.transform(X_std)
  TWSS[k] = model.inertia_

plt.plot(TWSS.keys(),TWSS.values(),'o-')

K=3으로 채택

 

k = 3

model = KMeans(n_clusters=k)
model.fit(X_std)
model.transform(X_std)

clusters = model.cluster_centers_

plt.scatter(X_std[:,0],X_std[:,1])
plt.xlabel("X")
plt.ylabel("Y")
plt.xlim(-2,2)
plt.ylim(-2,2)
plt.scatter(clusters[:,0],clusters[:,1],c="r",alpha=0.5,s=300)

 

5단계: 결과분석

정답지가 없으므로 패스.


[Iris 데이터로 실습]

라이브러리 임포트

from sklearn.cluster import KMeans
from sklearn.preprocessing import StandardScaler
from sklearn import datasets

from sklearn.metrics import confusion_matrix # 평가용
from sklearn.metrics import accuracy_score # 평가용

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns

 

1단계: 데이터 작성

# 또이리스 데이터 활용
data = datasets.load_iris()
X = data['data']
target = data['target']
features = data['feature_names']

2단계: 탐색적 데이터 분석

df = pd.DataFrame(data=X, columns=features)
df['target'] = target

plt.figure()
ax = sns.pairplot(df,hue='target')
plt

 

# feature별 평균 분산 확인
plt.boxplot([X[:,0],X[:,1],X[:,2],X[:,3]],labels=features)
plt

 

3단계: 피처 스케일링

scaler = StandardScaler()
scaler.fit(X)
X_std = scaler.transform(X)
X_std

4단계: 군집화

TWSS = {}

for K in range(1,11):
  model = KMeans(n_clusters=K)
  model.fit_transform(X_std)
  TWSS[K] = model.inertia_

plt.plot(TWSS.keys(),TWSS.values(),'o-')

K = 3으로 채택

K = 3

model = KMeans(n_clusters=K)
model.fit_transform(X_std)

plt.scatter(X_std[:,0],X_std[:,3],c=target)
plt.xlabel(f"{features[0]}_std")
plt.ylabel(f"{features[3]}_std")
plt.xlim(-3,3)
plt.ylim(-2,2)
print(model.cluster_centers_)
for i in range(len(model.cluster_centers_)):
  plt.scatter(model.cluster_centers_[i][0],model.cluster_centers_[i][3], c='r',alpha=0.5,s=300)

5단계: 결과분석

test_data = X_std
result = model.predict(test_data)
print(target)

# 결과 싱크 맞추기
for i in range(len(result)):
  if result[i] == 1:
    result[i] = 0
  elif result[i] == 2:
    result[i] = 1
  else:
    result[i] = 2

print(result)

 

# confusion matrix
print(confusion_matrix(target,result))

# 정확도
accuracy_score(target,result,normalize = False) # 정답 개수
accuracy_score(target,result) # 정답률

 


요약

  • k-means 군집분석 : 객체들을 거리 기반 유사성을 측정하여 K 개의 군집으로 분류하는 방법.
  • 표준 알고리즘:
    • 먼저 데이터를 표준화하고, K개에 해당하는 군집의 초기 중심을 정한 후에 각 개체들을 가까운 군집으로 할당.
    • 군집화가 이루어지면 군집 중심을 다시 계산하고 군집 중심이 변하지 않으면 반복을 종료.
  • k-means 군집분석 절차
    • 데이터 작성→ 탐색적 데이터 분석 → 피처 스케일링 → 군집의 수 지정 → 군집화 과정
    • 테스트 데이터가 있는 경우에는 정확도로 모형의 성능을 평가.
  • 군집 수(K)는 데이터의 분포에 따라 달라짐
    • 군집 내 거리 제곱합 WSS (within-cluster sum of squares)
    • 각 군집내에서 개체들과 군집 중심 간 거리 제곱의 합
    • TWSS(total WSS) :군집의 수가 증가할수록 감소
  • Elbow method: 군집의 수에 따라 WSS의 기울기가 급격히 작아지는 지점(elbow point)의 군집 수로 정함
  • Confusion matrix, 정확도

'AI Study > Machine Learning' 카테고리의 다른 글

의사결정나무: Decision Tree  (0) 2025.12.15
SVM: Support Vector Machine  (0) 2025.12.15
K-최근접 이웃: KNN, K-nearest neighbors  (0) 2025.12.15
연관분석: Apriori Algorithm  (0) 2025.12.15
주성분 분석, PCA: Principal Component Analysis  (0) 2025.10.28
'AI Study/Machine Learning' 카테고리의 다른 글
  • SVM: Support Vector Machine
  • K-최근접 이웃: KNN, K-nearest neighbors
  • 연관분석: Apriori Algorithm
  • 주성분 분석, PCA: Principal Component Analysis
Yun Lab.
Yun Lab.
Yun Lab.
  • Yun Lab.
    윤랩
    Yun Lab.
  • 글쓰기 방명록 관리자
  • 전체
    오늘
    어제
    • 분류 전체보기 (26)
      • CS (13)
        • 컴퓨터구조 (6)
        • 운영체제 (7)
        • 네트워크 (0)
        • 시스템 프로그래밍 (0)
        • 데이터베이스 (0)
      • Git (0)
      • AI Study (6)
        • LLM (0)
        • Machine Learning (6)
      • 자격증 (2)
        • AICE (1)
        • 리눅스마스터 (1)
      • 논문리뷰 (4)
        • NeurIPS (0)
        • ICLR (1)
        • ICML (1)
        • 기타 (2)
      • 코딩테스트 (1)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    명렁어
    교착상태
    의사결정나무
    디시전트리
    도커
    ICML
    머신러닝
    리눅스마스터
    ML
    K-최근접이웃
    SVM
    운영체제
    multi-agent
    Machine Learning
    2025ICML
    쿠버네티스
    프로세스와 스레드
    ICLR2025
    LLM
    서포트벡터머신
  • 최근 댓글

  • hELLO· Designed By정상우.v4.10.5
Yun Lab.
군집화, K-Means Clustering
상단으로

티스토리툴바