RでK-meansクラスタリングを行う方法を自分用にまとめておきます。
理論は省略。
メイン関数stats::kmeans
stats
は基本ロードされるので個別にライブラリを入れる必要は無し。- 第一引数に分析対象の数値行列。ただし行列に変換できる(つまりすべて数値変数)データフレームでも可
- 第二引数にクラスタ数(いわゆるk)
- オプション
nstart
でアルゴリズムの初期状態を作るためのデータサンプル数の設定。小さいと局所最適に落ち込んでしまう可能性があるので参考文献では20~50程度の大きめの数字を推奨している
例
km.out <- kmeans(iris[-5], 3, nstart = 20)
結果取得
- kmeansクラスのオブジェクト
$cluster
で分類結果
km.out #K-means clustering with 3 clusters of sizes 38, 50, 62 # #Cluster means: # Sepal.Length Sepal.Width Petal.Length Petal.Width #1 6.850000 3.073684 5.742105 2.071053 #2 5.006000 3.428000 1.462000 0.246000 #3 5.901613 2.748387 4.393548 1.433871 # #Clustering vector: # [1] 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 3 3 1 3 3 3 3 3 3 3 3 3 3 3 3 3 3 # [68] 3 3 3 3 3 3 3 3 3 3 1 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 1 3 1 1 1 1 3 1 1 1 1 1 1 3 3 1 1 1 1 3 1 3 1 3 1 1 3 3 1 1 1 1 1 3 #[135] 1 1 1 1 3 1 1 1 3 1 1 1 3 1 1 3 # #Within cluster sum of squares by cluster: #[1] 23.87947 15.15100 39.82097 # (between_SS / total_SS = 88.4 %) # #Available components: # #[1] "cluster" "centers" "totss" "withinss" "tot.withinss" "betweenss" "size" "iter" "ifault" km.out$cluster # [1] 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 3 3 1 3 3 3 3 3 3 3 3 3 3 3 3 3 3 # [68] 3 3 3 3 3 3 3 3 3 3 1 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 1 3 1 1 1 1 3 1 1 1 1 1 1 3 3 1 1 1 1 3 1 3 1 3 1 1 3 3 1 1 1 1 1 3 #[135] 1 1 1 1 3 1 1 1 3 1 1 1 3 1 1 3 library(dplyr) iris %>% mutate(km = km.out$cluster) %>% count(Species, km) ## A tibble: 5 x 3 # Species km n # <fct> <int> <int> #1 setosa 2 50 #2 versicolor 1 2 #3 versicolor 3 48 #4 virginica 1 36 #5 virginica 3 14 library(ggplot2) iris %>% mutate(kmeans = factor(km.out$cluster)) %>% ggplot(aes(Petal.Width, Petal.Length)) + geom_point(aes(color = Species, shape = kmeans), alpha = 0.8, size = 5)

対象
- K-meansはクラスタ数kを事前に与えなければならない。つまりkが事前に分かっている場合(男と女とで2分類したい、など)に使うのが好ましい