1. 程式人生 > >k-means的分類數目

k-means的分類數目

k-means聚類的類數確定

根據類內離差平方和最小,類間離差平方和最大的原則

自定義函式

tot.wssplot <- function(data, nc, seed=1234){
#假設分為一組時的總的離差平方和
tot.wss <- (nrow(data)-1)*sum(apply(data,2,var))
for (i in 2:nc){
#必須指定隨機種子數
set.seed(seed)
tot.wss[i] <- kmeans(data, centers=i, iter.max = 100)$tot.withinss
}
plot(1:nc, tot.wss, type=”b”, xlab=”Number of Clusters”,
ylab=”Within groups sum of squares”,col = ‘blue’,
lwd = 2, main = ‘Choose best Clusters’)
}

kmeans()函式的返回值中,tot.withiness表示總的類內平方和;withiness向量表示每個類的組內平方和。