본문 바로가기

자격증/빅데이터 분석기사

K-means in R

 

 

 

비슷한 iris 품종끼리 클러스터링

library(dplyr)
library(ggplot2)

data(iris)
df <-iris
summary(df)

# 데이터 전처리
# ★ Species 컬럼에 대해 레이블 인코딩 수행  
df$Species <- as.numeric(factor(df$Species),level=c("serosa","versicolor","virginica"))

# MIn-Max 정규화
normal <- function(x){
  return((x-min(x))/(max(x)-min(x)))
}

df[1:4] <- as.data.frame(lapply(df[1:4],normal))
summary(df)

# 데이터 특징 핵심인자 탐색을 위한 사전 시각화
# 변수간 상관관계 시각화
pairs(df[,-5])   # Petal.Length 를 통해 종류구분이 가능함을 판단할 수 있다.

# ★  K-means 클러스터링
# ★ 학습에 df$species 값을 사용하지 않는다 !!!
cluster1 <- kmeans(df[,-5],centers=2, iter.max=1000)  # 2개의 클러스터로 분류(centers), 알고리즘 반복횟수 1000번(iter.max)
cluster1

## 군집 내 분산을 계산하여 최적의 K값 찾기
## total within-cluster sum of square
tot_withinss <- c()
for(i in 1:10){
  cluster1 <- kmeans(df[,-5],centers=i,iter.max=1000)
  tot_withinss[i] = cluster1$tot.withinss
}

plot(c(1:10),tot_withinss, type="b")    # 군집 내 분산

 

 

iris 데이터 전처리 후 summary(df)
데이터 특징 핵심인자 탐색을 위한 사전 시각화로 pair() 함수 이용

 

 

K-means 적합 결과

 

 

 

kmeans(df[,-5], centers=2, iter.max=1000)

→  centers :  클러스터 개수

→  iter.max : kmeans 알고리즘의 반복횟수, K가  큰 경우 1000 이상으로 조정한다.

 

between_SS / total_SS  = 70.5 %

→  between_SS / total_SS : 전체 변동에서 군집간 변동이 차지하는 비율

                                              : 1에 가까울수록 군집이 잘 분류되었다고 판단할 수 있다.

 

 

  비지도학습인 K-means 는 실제 정답이 없으므로 일반적인 성능평가 대신

     적절한 K개를 설정하였는지 평가한다.

→  tot.withinSS : 각 군집별 오차의 제곱합 (군집 내 분산) 

→  Elbow 기법은 tot.withinSS 가 빠르게 줄어드는 변화시점을 최적의 K 로 설정하는 방법이다.

 

→  K 개수와 tot.withinSS 의 비교시각화로  K=3 일 때가 군집 내 분산이 빠르게 줄어든다.

 

 

 

  •  K-means 클러스터링을 위해 사용하는 함수 : kmeans(data, centers= , iter.max = )
  • K-means 함수는 별도의 패키지 설치가 필요없다.
  • 종속변수가 Factor (문자열) 인 경우 레이블 인코딩을 수행한다.