私は最初のkmeansアルゴリズムをRで書いてみようとしています。私はこの分野では新しいので、明白ではないと私を判断してはいけません。自分のkmeansアルゴリズムを書くR
アルゴリズムは2つのベクトルx
,y
を受け取り、各データ点のクラスタ中心までの距離を計算し、その中心からデータ点までの距離を最小にしてクラスタを割り当てます。アルゴリズムは、割り当てに変化がなく、したがってクラスタ中心に変化がないときに停止する。
# Sample data
set.seed(100)
xval <- rnorm(12, mean = rep(1:3, each = 4), sd = 0.2)
yval <- rnorm(12, mean = rep(c(1,2,1), each = 4), sd = 0.2)
# Kmeans function
kclus <- function(x, y, nclus) {
# start with random cluster centers
xcen <- runif(n = nclus, min = min(x), max = max(x))
ycen <- runif(n = nclus, min = min(y), max = max(y))
# data points and cluster assignment in "data"
# cluster coordinates in "clus"
data <- data.frame(xval = x, yval = y, clus = NA)
clus <- data.frame(name = 1:nclus, xcen = xcen, ycen = ycen)
finish <- FALSE
while(finish == FALSE) {
# assign cluster with minimum distance to each data point
for(i in 1:length(x)) {
dist <- sqrt((x[i]-clus$xcen)^2 + (y[i]-clus$ycen)^2)
data$clus[i] <- which.min(dist)
}
xcen_old <- clus$xcen
ycen_old <- clus$ycen
# calculate new cluster centers
for(i in 1:nclus) {
clus[i,2] <- mean(subset(data$xval, data$clus == i))
clus[i,3] <- mean(subset(data$yval, data$clus == i))
}
# stop the loop if there is no change in cluster coordinates
if(identical(xcen_old, clus$xcen) & identical(ycen_old, clus$ycen)) finish <- TRUE
}
data
}
# apply kmeans function to sample data
cluster <- kclus(xval, yval, 4)
# plot the result
ggplot(cluster, aes(xval, yval, color = as.factor(clus))) + geom_point()
これはこれまで比較的うまくいきました。しかし、私はどのように特定の数のクラスタにアルゴリズムを強制することができないのか、手がかりはありません。私のkclus()
機能ではすでにパラメータnclus
として実装されていますが、どのように使用するのか分かりません。
与えられたサンプルデータについて、このアルゴリズムは私に3つのクラスターを与えます。私は彼に私に4つのクラスターを戻すように強制したい。私はその上の助言を与えることができ、ここで
誰?
は 、そんなに作品を、kは、意味だけの方法であるマーカス