【问题标题】:Writing own kmeans algorithm in R在 R 中编写自己的 kmeans 算法
【发布时间】:2017-06-14 06:01:10
【问题描述】:

我正在尝试在 R 中编写我自己的第一个 kmeans 算法。我是这个领域的新手,所以请不要因为没有看到明显的东西而评判我。

在当前状态下,该算法采用两个向量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实现了,但我不知道如何使用它。

对于给定的样本数据,算法只给了我三个集群。我要逼他把四簇还给我。

这里有人可以给我建议吗?

非常感谢, 马库斯

【问题讨论】:

    标签: r algorithm machine-learning data-mining k-means


    【解决方案1】:

    问题在于你的初始化。

    用随机数初始化是最糟糕的选择,除非你的数据是均匀随机分布的(然后你没有集群)。

    现在,如果您在左上角生成一个中心,它可能有 0 个点,您的代码接下来可能会生成一个 NaN 均值。

    相反,尝试从您的数据中选择 k 个点 作为中心。这不太可能变坏(尽管它可以)。

    【讨论】:

      【解决方案2】:

      您实现的算法总是为您提供 3 个集群,这不是真的,可能您没有运行足够多的次数。这是您的代码的轻微修改,我们将能够看到集群输出的数量取决于集群质心的初始化(随机选择并且可以用 random.seed 控制):

      # 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 with random.seed for initialization
      kclus <- function(x, y, nclus, random.seed=123) {
      
        set.seed(random.seed)
        # 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
      }
      
      # with default random seed 123, you should be able to reproduce the result
      # as you can see, in this case, no data points were assigned to the 4th cluster
      cluster <- kclus(xval, yval, 4)
      cluster.centers <- aggregate(.~clus, cluster, mean)
      ggplot(cluster, aes(xval, yval, color = as.factor(clus))) + 
        geom_point(size=5) + 
        geom_point(data=cluster.centers, aes(xval, yval, col=as.factor(clus)), pch=8, size=5)
      

      # run with a different random seed = 12
      # as you can see, in this case, the algorithm outputs 4 clusters, with the 2nd cluster having a single datapoint assigned to
          cluster <- kclus(xval, yval, 4, 12)
          cluster.centers <- aggregate(.~clus, cluster, mean)
          ggplot(cluster, aes(xval, yval, color = as.factor(clus))) + 
            geom_point(size=5) + 
            geom_point(data=cluster.centers, aes(xval, yval, col=as.factor(clus)), pch=8, size=5)
      

      # run with a different random seed = 12345
      # as you can see, in this case, the algorithm outputs 2 clusters, with the all the datapoints assigned to the 1st and the 2nd cluster
          cluster <- kclus(xval, yval, 4, 12345)
          cluster.centers <- aggregate(.~clus, cluster, mean)
          ggplot(cluster, aes(xval, yval, color = as.factor(clus))) + 
            geom_point(size=5) + 
            geom_point(data=cluster.centers, aes(xval, yval, col=as.factor(clus)), pch=8, size=5)
      

      从上面的例子中我们可以看出,一个聚类是否最终在收敛时没有分配给它的点取决于初始中心位置以及数据分布。一般来说,如果 kmeans 以一个簇质心为空而结束,这意味着如果您尝试强制将一个点分配给空簇,则可能会导致质量较差的簇,这是您不想做的事情。

      此时您可以尝试几件事。

      1. 首先,您可以多次运行算法,每次使用不同的随机初始化中心,然后选择具有最高聚类质量(通过 SSE 等衡量)的结果。
      2. 您可以尝试的第二件事是更智能的初始化 Kmeans++。
      3. 一个不太好的选择可能是将您的算法修改为 确保在重新分配集群时,它保证每个 k (=4) 个簇至少分配了一个点(如果没有,则 不要重新分配)。
      4. 最后你可以尝试一些其他算法,例如 层次聚类,通过 可以根据需要选择尽可能多的集群。

      【讨论】:

        【解决方案3】:

        这正是 k-means 的工作方式。你有两个主要选择。要么忍受更少的集群或,只要集群数量低于请求的集群数量,就开始一个新的。要开始一个新的,可能会找到离其集群中心最远的点并将其更改为一个新的集群。但是,这样做存在问题。假设您有 20 个点并且用户要求 25 个集群。你就是满足不了一些人。

        【讨论】:

          猜你喜欢
          • 2015-10-12
          • 2018-04-18
          • 2021-10-08
          • 2021-08-29
          • 2014-09-17
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多