【问题标题】:kmeans classification to predetermined centroidskmeans 分类到预定的质心
【发布时间】:2013-04-23 09:31:18
【问题描述】:

我正在尝试将数据点(通过欧几里得距离)分配给已知的、预定义的一组中心点,将点分配给最接近的固定中心点。

我觉得我可能过于复杂/遗漏了一些基本的东西,但我尝试使用具有预定中心且没有迭代的 kmeans 实现来做到这一点。但是,根据下面的代码,可能是因为算法将进行一次迭代,这无法正常工作(cl$centers 已“移动”并且不等于原始质心)

还有另一种简单的方法可以将矩阵 X 中的点分配到最近的中心吗?

非常感谢,W

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

【问题讨论】:

    标签: r classification k-means


    【解决方案1】:

    您可以直接计算每个点和每个中心之间的距离和 查看最近的中心。

    # 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 )
    

    【讨论】:

      猜你喜欢
      • 2016-11-16
      • 2014-10-29
      • 2020-05-03
      • 2021-03-03
      • 1970-01-01
      • 2018-08-12
      • 2020-06-13
      • 2021-06-13
      • 1970-01-01
      相关资源
      最近更新 更多