【问题标题】:In R, how do I retrieve information from an XMeans output在 R 中,如何从 XMeans 输出中检索信息
【发布时间】:2018-09-06 04:28:05
【问题描述】:

我有一个数据框df,其中包含一组点的xy 坐标。摘录如下:

> tail(df)
            x        y
1495 0.627174 0.120215
1496 0.616036 0.123623
1497 0.620269 0.122713
1498 0.630231 0.110670
1499 0.611844 0.111593
1500 0.412236 0.933250

我正在尝试找出最合适的集群数量。最终的目标是用数以万计的这些数据帧来做到这一点,所以选择的方法必须是快速的并且不能是可视化的。根据这些要求,RWeka 包似乎是可行的方法。

我成功地加载了 RWeka 包(我必须先在我的计算机上安装 Java SE Runtime)以及 RWeka 的包 XMeans,然后运行它:

library("RWeka") # requires Java SE Runtime
WPM("refresh-cache") # Build Weka package metadata cache
WPM("install-package", "XMeans") # Install XMeans package if not previously installed

weka_ctrl <- Weka_control( # Create a Weka control object to specify our parameters
  I = 100, # max no iterations overall
  M = 100, # max no iterations in the kmeans loop
  L = 2,   # min no clusters
  H = 5,   # max no clusters
  D = "weka.core.EuclideanDistance", # distance metric
  C = 0.4, S = 1)
x_means <- XMeans(df, control = weka_ctrl) # run algorithm on data

这会产生我想要的结果:

XMeans
======
Requested iterations            : 100
Iterations performed            : 1
Splits prepared                 : 2
Splits performed                : 0
Cutoff factor                   : 0.4
Percentage of splits accepted 
by cutoff factor                : 0 %
------
Cutoff factor                   : 0.4
------

Cluster centers                 : 2 centers

Cluster 0
            0.4197712002617799 0.9346986806282739
Cluster 1
            0.616697959239131 0.11564350951086963

Distortion: 30.580934
BIC-Value : 2670.359509

我可以通过运行 x_means$class_ids 将数据框中的每个点分配给一个集群。

但是,我想有一种方法来检索集群中心的坐标。我可以在输出中看到它们并手动将它们写下来,但如果我要运行成千上万个,我需要能够有一段代码将它们保存到一个变量中。我似乎无法使用方括号对x_means 进行子集化,所以我不知道还能做什么。

非常感谢您的帮助!

【问题讨论】:

    标签: r weka k-means rweka xmeans


    【解决方案1】:

    中心似乎没有直接存储在返回的结构中。然而,由于结构确实告诉你每个点属于哪个簇,计算中心很容易。由于您不提供数据,我将使用内置的虹膜数据进行说明。

    正如您所观察到的,打印出结果会显示中心。我们可以用它来检查结果。

    x_means <- XMeans(iris[,1:4], control = weka_ctrl) 
    x_means
    ## Output truncated to just the interesting part.
    Cluster centers                 : 2 centers
    
    Cluster 0
                6.261999999999998 2.872000000000001 4.906000000000001 1.6760000000000006
    Cluster 1
                5.005999999999999 3.428000000000001 1.4620000000000002 0.2459999999999999
    

    所以这里是如何计算的

    colMeans(iris[x_means$class_ids==0,1:4])
    Sepal.Length  Sepal.Width Petal.Length  Petal.Width 
           6.262        2.872        4.906        1.676 
    colMeans(iris[x_means$class_ids==1,1:4])
    Sepal.Length  Sepal.Width Petal.Length  Petal.Width 
           5.006        3.428        1.462        0.246 
    

    结果一致。

    【讨论】:

    • 感谢您的帮助!我真的很感激。
    猜你喜欢
    • 2021-02-11
    • 2019-12-09
    • 1970-01-01
    • 1970-01-01
    • 2015-01-25
    • 1970-01-01
    • 2012-06-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多