1 군집 분석이란?

군집 분석은 비지도학습(Unsupervised learning) 분석 기법 중 하나입니다. 쉽게 말해서, 사전 정보 없이 자료를 컴퓨터에게 주고, “유사한 대상끼리 묶어보아라!” 라고 명령을 내리는 분석 방법입니다. 따라서 군집분석에서는 어떤 변수를 컴퓨터에게 입력하느냐가 중요하다고 볼 수 있습니다. 예를 들어, PC방 플레이어의 유형을 분석하고 싶은 데 스킨 구매 데이터만 넣고 분석 하면 좋은 분석 결과를 얻기 힘들겠죠.

2 K-Means 군집분석이란?

군집 분석은 유사한 대상끼리 그룹핑 하는 분석입니다. 대상간의 유사도, 거리를 측정하는 방법에는 여러가지가 있습니다. K-means 군집 분석은 비계층적 군집 분석 방법을 사용하는데요, 계산량이 적기 때문에 대용량 데이터도 빠르게 처리할 수 있는 장점이 있습니다.

K-means 군집 분석의 알고리즘

3 R을 사용한 K-Means 군집 분석

3.1 데이터 준비

training 데이터로 모델(70%)을 만들고, testing 데이터로 모델(30%)을 평가 하기 위한 사전 작업입니다.

library(caret)
set.seed(1712)

inTrain <- createDataPartition(y = iris$Species, p = 0.7, list = F)
training <- iris[inTrain,]
testing <- iris[-inTrain,]
training
##     Sepal.Length Sepal.Width Petal.Length Petal.Width    Species
## 1            5.1         3.5          1.4         0.2     setosa
## 2            4.9         3.0          1.4         0.2     setosa
## 4            4.6         3.1          1.5         0.2     setosa
## 5            5.0         3.6          1.4         0.2     setosa
## 6            5.4         3.9          1.7         0.4     setosa
## 7            4.6         3.4          1.4         0.3     setosa
## 8            5.0         3.4          1.5         0.2     setosa
## 9            4.4         2.9          1.4         0.2     setosa
## 10           4.9         3.1          1.5         0.1     setosa
## 11           5.4         3.7          1.5         0.2     setosa
## 12           4.8         3.4          1.6         0.2     setosa
## 13           4.8         3.0          1.4         0.1     setosa
## 14           4.3         3.0          1.1         0.1     setosa
## 15           5.8         4.0          1.2         0.2     setosa
## 16           5.7         4.4          1.5         0.4     setosa
## 17           5.4         3.9          1.3         0.4     setosa
## 19           5.7         3.8          1.7         0.3     setosa
## 22           5.1         3.7          1.5         0.4     setosa
## 25           4.8         3.4          1.9         0.2     setosa
## 28           5.2         3.5          1.5         0.2     setosa
## 30           4.7         3.2          1.6         0.2     setosa
## 31           4.8         3.1          1.6         0.2     setosa
## 32           5.4         3.4          1.5         0.4     setosa
## 34           5.5         4.2          1.4         0.2     setosa
## 35           4.9         3.1          1.5         0.2     setosa
## 38           4.9         3.6          1.4         0.1     setosa
## 39           4.4         3.0          1.3         0.2     setosa
## 40           5.1         3.4          1.5         0.2     setosa
## 41           5.0         3.5          1.3         0.3     setosa
## 42           4.5         2.3          1.3         0.3     setosa
## 45           5.1         3.8          1.9         0.4     setosa
## 46           4.8         3.0          1.4         0.3     setosa
## 47           5.1         3.8          1.6         0.2     setosa
## 49           5.3         3.7          1.5         0.2     setosa
## 50           5.0         3.3          1.4         0.2     setosa
## 51           7.0         3.2          4.7         1.4 versicolor
## 52           6.4         3.2          4.5         1.5 versicolor
## 53           6.9         3.1          4.9         1.5 versicolor
## 54           5.5         2.3          4.0         1.3 versicolor
## 55           6.5         2.8          4.6         1.5 versicolor
## 57           6.3         3.3          4.7         1.6 versicolor
## 58           4.9         2.4          3.3         1.0 versicolor
## 59           6.6         2.9          4.6         1.3 versicolor
## 60           5.2         2.7          3.9         1.4 versicolor
## 61           5.0         2.0          3.5         1.0 versicolor
## 62           5.9         3.0          4.2         1.5 versicolor
## 63           6.0         2.2          4.0         1.0 versicolor
## 64           6.1         2.9          4.7         1.4 versicolor
## 67           5.6         3.0          4.5         1.5 versicolor
## 69           6.2         2.2          4.5         1.5 versicolor
## 72           6.1         2.8          4.0         1.3 versicolor
## 73           6.3         2.5          4.9         1.5 versicolor
## 74           6.1         2.8          4.7         1.2 versicolor
## 75           6.4         2.9          4.3         1.3 versicolor
## 76           6.6         3.0          4.4         1.4 versicolor
## 77           6.8         2.8          4.8         1.4 versicolor
## 81           5.5         2.4          3.8         1.1 versicolor
## 82           5.5         2.4          3.7         1.0 versicolor
## 83           5.8         2.7          3.9         1.2 versicolor
## 84           6.0         2.7          5.1         1.6 versicolor
## 87           6.7         3.1          4.7         1.5 versicolor
## 88           6.3         2.3          4.4         1.3 versicolor
## 89           5.6         3.0          4.1         1.3 versicolor
## 90           5.5         2.5          4.0         1.3 versicolor
## 91           5.5         2.6          4.4         1.2 versicolor
## 92           6.1         3.0          4.6         1.4 versicolor
## 93           5.8         2.6          4.0         1.2 versicolor
## 96           5.7         3.0          4.2         1.2 versicolor
## 99           5.1         2.5          3.0         1.1 versicolor
## 100          5.7         2.8          4.1         1.3 versicolor
## 102          5.8         2.7          5.1         1.9  virginica
## 103          7.1         3.0          5.9         2.1  virginica
## 105          6.5         3.0          5.8         2.2  virginica
## 107          4.9         2.5          4.5         1.7  virginica
## 109          6.7         2.5          5.8         1.8  virginica
## 110          7.2         3.6          6.1         2.5  virginica
## 112          6.4         2.7          5.3         1.9  virginica
## 113          6.8         3.0          5.5         2.1  virginica
## 115          5.8         2.8          5.1         2.4  virginica
## 116          6.4         3.2          5.3         2.3  virginica
## 119          7.7         2.6          6.9         2.3  virginica
## 120          6.0         2.2          5.0         1.5  virginica
## 121          6.9         3.2          5.7         2.3  virginica
## 122          5.6         2.8          4.9         2.0  virginica
## 123          7.7         2.8          6.7         2.0  virginica
## 124          6.3         2.7          4.9         1.8  virginica
## 125          6.7         3.3          5.7         2.1  virginica
## 128          6.1         3.0          4.9         1.8  virginica
## 129          6.4         2.8          5.6         2.1  virginica
## 130          7.2         3.0          5.8         1.6  virginica
## 131          7.4         2.8          6.1         1.9  virginica
## 132          7.9         3.8          6.4         2.0  virginica
## 134          6.3         2.8          5.1         1.5  virginica
## 135          6.1         2.6          5.6         1.4  virginica
## 136          7.7         3.0          6.1         2.3  virginica
## 138          6.4         3.1          5.5         1.8  virginica
## 139          6.0         3.0          4.8         1.8  virginica
## 141          6.7         3.1          5.6         2.4  virginica
## 142          6.9         3.1          5.1         2.3  virginica
## 143          5.8         2.7          5.1         1.9  virginica
## 144          6.8         3.2          5.9         2.3  virginica
## 147          6.3         2.5          5.0         1.9  virginica
## 148          6.5         3.0          5.2         2.0  virginica
## 149          6.2         3.4          5.4         2.3  virginica
## 150          5.9         3.0          5.1         1.8  virginica
testing
##     Sepal.Length Sepal.Width Petal.Length Petal.Width    Species
## 3            4.7         3.2          1.3         0.2     setosa
## 18           5.1         3.5          1.4         0.3     setosa
## 20           5.1         3.8          1.5         0.3     setosa
## 21           5.4         3.4          1.7         0.2     setosa
## 23           4.6         3.6          1.0         0.2     setosa
## 24           5.1         3.3          1.7         0.5     setosa
## 26           5.0         3.0          1.6         0.2     setosa
## 27           5.0         3.4          1.6         0.4     setosa
## 29           5.2         3.4          1.4         0.2     setosa
## 33           5.2         4.1          1.5         0.1     setosa
## 36           5.0         3.2          1.2         0.2     setosa
## 37           5.5         3.5          1.3         0.2     setosa
## 43           4.4         3.2          1.3         0.2     setosa
## 44           5.0         3.5          1.6         0.6     setosa
## 48           4.6         3.2          1.4         0.2     setosa
## 56           5.7         2.8          4.5         1.3 versicolor
## 65           5.6         2.9          3.6         1.3 versicolor
## 66           6.7         3.1          4.4         1.4 versicolor
## 68           5.8         2.7          4.1         1.0 versicolor
## 70           5.6         2.5          3.9         1.1 versicolor
## 71           5.9         3.2          4.8         1.8 versicolor
## 78           6.7         3.0          5.0         1.7 versicolor
## 79           6.0         2.9          4.5         1.5 versicolor
## 80           5.7         2.6          3.5         1.0 versicolor
## 85           5.4         3.0          4.5         1.5 versicolor
## 86           6.0         3.4          4.5         1.6 versicolor
## 94           5.0         2.3          3.3         1.0 versicolor
## 95           5.6         2.7          4.2         1.3 versicolor
## 97           5.7         2.9          4.2         1.3 versicolor
## 98           6.2         2.9          4.3         1.3 versicolor
## 101          6.3         3.3          6.0         2.5  virginica
## 104          6.3         2.9          5.6         1.8  virginica
## 106          7.6         3.0          6.6         2.1  virginica
## 108          7.3         2.9          6.3         1.8  virginica
## 111          6.5         3.2          5.1         2.0  virginica
## 114          5.7         2.5          5.0         2.0  virginica
## 117          6.5         3.0          5.5         1.8  virginica
## 118          7.7         3.8          6.7         2.2  virginica
## 126          7.2         3.2          6.0         1.8  virginica
## 127          6.2         2.8          4.8         1.8  virginica
## 133          6.4         2.8          5.6         2.2  virginica
## 137          6.3         3.4          5.6         2.4  virginica
## 140          6.9         3.1          5.4         2.1  virginica
## 145          6.7         3.3          5.7         2.5  virginica
## 146          6.7         3.0          5.2         2.3  virginica

3.2 표준화

K-means 군집 분석은 관측치 간의 거리를 이용하기 때문에 변수의 단위가 결과에 큰 영향을 미칩니다. 그래서 변수를 표준화 하는 작업이 필요한데요, scale 함수를 사용해서 표준화를 합니다.

training.data <- scale(training[-5])
summary(training.data)
##   Sepal.Length       Sepal.Width        Petal.Length      Petal.Width     
##  Min.   :-1.85375   Min.   :-2.22925   Min.   :-1.5183   Min.   :-1.4375  
##  1st Qu.:-0.89373   1st Qu.:-0.71493   1st Qu.:-1.2892   1st Qu.:-1.1727  
##  Median :-0.05372   Median :-0.06593   Median : 0.3721   Median : 0.1513  
##  Mean   : 0.00000   Mean   : 0.00000   Mean   : 0.0000   Mean   : 0.0000  
##  3rd Qu.: 0.66630   3rd Qu.: 0.58307   3rd Qu.: 0.7731   3rd Qu.: 0.8133  
##  Max.   : 2.46633   Max.   : 2.96272   Max.   : 1.8042   Max.   : 1.7401

3.3 모델 작성

training 데이터를 3개 군집으로 나눠 봅니다.

iris.kmeans <- kmeans(training.data[,-5], centers = 3, iter.max = 10000)
iris.kmeans$centers
##   Sepal.Length Sepal.Width Petal.Length Petal.Width
## 1 -0.006885142 -0.79407102    0.3958313   0.3450678
## 2  1.216652469  0.07580495    1.0140650   1.0278859
## 3 -1.000018022  0.86738766   -1.3039134  -1.2558991

3.4 군집 확인

군집 분석 결과를 training 데이터셋에 할당하고, 결과를 확인해 봅니다.

training$cluster <- as.factor(iris.kmeans$cluster)
qplot(Petal.Width, Petal.Length, colour = cluster, data = training)

결과를 보니 setosa는 잘 분류해 내었지만 versicolor나 virginica 종은 잘 구분해 내지 못한 것 같네요.

table(training$Species, training$cluster)
##             
##               1  2  3
##   setosa      0  0 35
##   versicolor 28  7  0
##   virginica  13 22  0

[잠깐!] K-means 군집분석에서 군집 중심의 갯수를 결정하는 방법

K-means 군집분석에서는 입력하는 변수와 함께 중심의 갯수를 지정하는 것이 중요한데요, 몇개의 군집 중심이 적당한지 결정하는 방법에는 여러가지가 있습니다. 그중 자주 사용하는 NbClust 패키지를 사용하는 방법과 군집 내 sum of squares를 사용하는 방법이 있습니다. 우선 NbClust 함수를 써보겠습니다.

#install.packages("NbClust")
library(NbClust)

nc <- NbClust(training.data, min.nc = 2, max.nc = 15, method = "kmeans")

## *** : The Hubert index is a graphical method of determining the number of clusters.
##                 In the plot of Hubert index, we seek a significant knee that corresponds to a 
##                 significant increase of the value of the measure i.e the significant peak in Hubert
##                 index second differences plot. 
## 

## *** : The D index is a graphical method of determining the number of clusters. 
##                 In the plot of D index, we seek a significant knee (the significant peak in Dindex
##                 second differences plot) that corresponds to a significant increase of the value of
##                 the measure. 
##  
## ******************************************************************* 
## * Among all indices:                                                
## * 8 proposed 2 as the best number of clusters 
## * 9 proposed 3 as the best number of clusters 
## * 2 proposed 5 as the best number of clusters 
## * 1 proposed 8 as the best number of clusters 
## * 3 proposed 14 as the best number of clusters 
## * 1 proposed 15 as the best number of clusters 
## 
##                    ***** Conclusion *****                            
##  
## * According to the majority rule, the best number of clusters is  3 
##  
##  
## *******************************************************************
par(mfrow=c(1,1))
barplot(table(nc$Best.n[1,]),
        xlab="Numer of Clusters", ylab="Number of Criteria",
        main="Number of Clusters Chosen")

NbClust 함수는 3개의 군집이 적당하다고 합니다. 이번에는 Some of square means를 보겠습니다.아래 그래프를 보면 군집이 3개를 넘어가면서 그룹 내 some of squares가 별로 낮아지지 않네요. 군집 간 격차가 줄어든다는 이야기입니다.

결론적으로 iris 데이터는 3개의 군집으로 구분하는 것이 좋습니다.

wssplot <- function(data, nc = 15, seed = 1234) {
  wss <- (nrow(data) - 1) * sum(apply(data, 2, var))
  for (i in 2:nc) {
    set.seed(seed)
    wss[i] <- sum(kmeans(data, centers=i)$withinss)}
  plot(1:nc, wss, type="b", xlab = "Number of Clusters",
       ylab = "Within groups sum of squares")}

wssplot(training.data)

3.5 새로운 데이터에 군집 할당

training 데이터 셋을 사용해서 예측 모델을 만들고, testing 데이터 셋으로 모델의 정확성을 다시 한번 확인해 보겠습니다.

training.data <- as.data.frame(training.data)
modFit <- train(x = training.data[,-5], 
                y = training$cluster,
                method = "rpart")

testing.data <- as.data.frame(scale(testing[-5]))
testClusterPred <- predict(modFit, testing.data) 
table(testClusterPred ,testing$Species)
##                
## testClusterPred setosa versicolor virginica
##               1      0         13         5
##               2      0          2        10
##               3     15          0         0

역시 setosa는 정확히 분류해 내지만 versicolor나 virginica에 대해서는 변별력이 약한 모습이네요.


Have fun!