【Rによるデータサイエンス】クラスター分析(つづき) 〜 非階層的クラスター分析

【Rによるデータサイエンス】クラスター分析」では、クラスター分析の定義から入り、階層的クラスター分析のケーススタディまで行った。
今回は、階層的クラスター分析が適さない場合に使用する、非階層的クラスター分析についてメモする。
まず、階層的クラスター分析が適さない場合とは。。。

個体数が多い時、階層的クラスター分析では計算量が膨大になるため、あまり適さない

階層的クラスター分析のアルゴリズムを把握していないので、非階層的クラスター分析にすると計算量を抑えられるというのが分からない(計算量の問題だけなら常に非階層的クラスター分析でいいんじゃね?と思ってしまう)が、それに関しては現段階では掘り下げないことにする。

さて、非階層的クラスター分析には、k-means法やISODATA法など、いくつかの手法があるらしい。
今回は、k-means法(k平均法)について学習する。

k-means法による分析ステップは次のようになる。

1.k個のクラスター中心(seeds)の初期値を適当に与える
2.全てのデータをk個のクラスター中心との距離を求め、最も近いクラスターに分類する
3.形成されたクラスターの中心を求める
4.クラスターの中心が変化しない時点までステップ2,3を繰り返す

◎k-means法のケーススタディ

kmeans(x, centers, iter.max = 10, nstart = 1, algorithm = c("Hartigan-Wong", "Lloyd", "Forgy", "MacQueen"))

x:データ
centers:クラスターの数、あるいはクラスターの中心
iter.max:繰り返しの最大値
nstart:初期中心を与える方法
algorithm:4つの方法("Hartigan-Wong", "Lloyd", "Forgy", "MacQueen")がある。デフォルトはHartigan-Wongであり、その他の方法より良いと報告されているらしい。

> (seiseki.km<-kmeans(seiseki,2))
K-means clustering with 2 clusters of sizes 4, 3

Cluster means:
      math  science japanese english society
1 71.75000 81.25000 49.25000    46.5   53.75
2 67.33333 73.33333 82.66667    84.0   90.00

Clustering vector:
  tanaka     sato   suzuki    honda kawabata  yoshino    saito 
       1        2        1        1        1        2        2 

Within cluster sum of squares by cluster:
[1] 2754 1228
 (between_SS / total_SS =  62.8 %)

Available components:

[1] "cluster"      "centers"      "totss"        "withinss"    
[5] "tot.withinss" "betweenss"    "size"         "iter"        
[9] "ifault"  

> summary(seiseki.km)
             Length Class  Mode   
cluster       7     -none- numeric
centers      10     -none- numeric
totss         1     -none- numeric
withinss      2     -none- numeric
tot.withinss  1     -none- numeric
betweenss     1     -none- numeric
size          2     -none- numeric
iter          1     -none- numeric
ifault        1     -none- numeric
    

k-means法によって得られるクラスタ分類は次のようになる。

> seiseki.km$cluster
  tanaka     sato   suzuki    honda kawabata  yoshino    saito 
       1        2        1        1        1        2        2 

ここで、階層的クラスター分析にて得られた結果を思い出すと次である。
一致していることが分かる。

> sei.single<-hclust(dist(seiseki),"single")
> cutree(sei.single,k=2)
  tanaka     sato   suzuki    honda kawabata  yoshino    saito 
       1        2        1        1        1        2        2 
> seiseki.km$centers
      math  science japanese english society
1 71.75000 81.25000 49.25000    46.5   53.75
2 67.33333 73.33333 82.66667    84.0   90.00

◎可視化

> library(cluster)
> plot(pam(iris[,1:4],3),ask = TRUE)

Make a plot selection (or 0 to exit):
 

1: plot  All
2: plot  Clusplot
3: plot  Silhouette Plot

Selection: 2