2013-04-29 9 views
4

데이터 포인트를 (유클리드 거리를 통해) 알려진 중심점 세트에 지정하려고합니다. 가장 가까운 고정 중심점에 포인트를 지정하려고합니다.kmeans를 미리 정해진 중심으로 분류합니다.

필자는 뭔가 기본적인 것을 놓치고있는 것 같은 느낌이 들지만, 나는 미리 설정된 센터와 반복이없는 kmeans 구현으로이 작업을 시도했다. 그러나, 아래의 코드에 따라, 그리고 아마도 algo가 하나의 반복을 할 것이기 때문에, 이것은 작동하지 않습니다 (cl $ 센터는 "움직 였고"원래 centroid와 동일하지 않습니다)

또 다른 간단한 할당 방법이 있습니까? 행렬 X의 점을 가장 가까운 중심에?

x <- rbind(matrix(rnorm(100, sd = 0.3), ncol = 2), matrix(rnorm(100, mean = 1, sd = 0.3), ncol = 2)) 
colnames(x) <- c("x", "y") 

vector=c(0.25,0.5,0.75,1) 
ccenters <- as.matrix(cbind(vector,vector)) 
colnames(ccenters) <- c("x", "y") 
ccenters 

(cl <- kmeans(x, centers=ccenters,iter.max=1)) 
plot(x, col = cl$cluster) 
points(cl$centers, col = 1:4, pch = 8, cex = 2) 
cl$centers 
cl$centers==ccenters 

답변

3

W 사전에

많은 감사, 직접 각 지점 및 각 센터와 가장 가까운 센터에서 보기 사이의 거리를 계산할 수 있습니다.

# All the distances (you could also use a loop) 
distances <- outer( 
    1:nrow(x), 
    1:nrow(ccenters), 
    Vectorize(function(i,j) { 
    sum((x[i,] - ccenters[j,])^2) 
    }) 
) 

# Find the nearest cluster 
clusters <- apply(distances, 1, which.min) 

# Plot 
plot(x, col=clusters, pch=15) 
segments(ccenters[clusters,1], ccenters[clusters,2], x[,1], x[,2], col=clusters) 
관련 문제