[英]k-means cluster analysis in r: setting only one center, leaving the other centers to be computed
我想用k均值將數據點分為三類。 我知道這三個小組之一的中心,但不知道其他兩個小組的中心。 因此,我想預設一組的中心,並相應地對算法進行聚類,以保持該中心的固定。 但是,我不確定是否以及如何使用R中的k-means包來做到這一點。
如果我在沒有預先設置中心的情況下進行聚類,那么我所知道的組的中心就會移向其他聚類中心的方向,這很可能導致錯誤的分類。
感謝您的投入。
朱莉安
當然,我們可以創建自己的初始化例程。 例如,我們可以像這樣修改Forgy方法
# modified Forgy
set.seed(1)
c1 <- c(7.8, 4.3, 6.8, 2.4)
cn <- rbind(c1, iris[sample(nrow(iris), 2),-5])
kmeans(iris[,-5], cn)$centers
# Sepal.Length Sepal.Width Petal.Length Petal.Width
# 1 6.684427 2.626896 6.512092 2.09042298
# 2 5.078494 3.646351 1.485264 0.05223007
# 3 6.012102 2.553765 3.869828 1.66717281
第一個初始中心是固定的,其余的則是從數據集中的行中隨機選擇的。
當然,這會使nstart
參數不適用,但是我們可以通過重復多次上述計算,然后選擇具有最高BCSS的結果,輕松地復制此功能。
# modified Forgy with nstart
set.seed(1)
data(iris)
m <- iris[,-5]
# initializing with the actual centroid of the first species
c1 <- colMeans(m[as.integer(iris[,5]) == 1,])
c1
# Sepal.Length Sepal.Width Petal.Length Petal.Width
# 5.006 3.428 1.462 0.246
kf <- function(x, clust, nc) {
cn <- rbind(clust, x[sample(nrow(x), nc-1),])
kmeans(x, cn)
}
l <- replicate(100, kf(m, c1, 3), simplify=FALSE)
bss <- sapply(l, '[[', "betweenss")
table(signif(bss, 4))
#
# 538.6 602.5
# 37 63
kmo <- l[[which.max(bss)]]
kmo$centers
# Sepal.Length Sepal.Width Petal.Length Petal.Width
# 1 5.006000 3.428000 1.462000 0.246000
# 2 5.901613 2.748387 4.393548 1.433871
# 3 6.850000 3.073684 5.742105 2.071053
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.