在Weka中以编程方式获取Xmeans clusterer输出

时间:2012-09-16 23:33:19

标签: cluster-analysis weka xmeans

在Weka中使用Kmeans时,可以在模型的结果输出上调用getAssignments()来获取每个给定实例的集群分配。这是一个(截断的)Jython示例:

>>>import weka.clusterers.SimpleKMeans as kmeans
>>>kmeans.buildClusterer(data)
>>>assignments = kmeans.getAssignments()
>>>assignments
>>>array('i',[14, 16, 0, 0, 0, 0, 16,...])

每个簇编号的索引对应于实例。因此,实例0在集群14中,实例1在集群16中,依此类推。

我的问题是:Xmeans有类似的东西吗?我已经浏览了整个API here并且没有看到类似的内容。

1 个答案:

答案 0 :(得分:7)

以下是Weka listserv对我的问题的回复:

 "Not as such. But all clusterers have a clusterInstance() method. You can 
 pass each training instance through the trained clustering model to 
 obtain the cluster index for each."

这是我对这个建议的Jython实现:

 >>> import java.io.FileReader as FileReader
 >>> import weka.core.Instances as Instances
 >>> import weka.clusterers.XMeans as xmeans
 >>> import java.io.BufferedReader as read
 >>> import java.io.FileReader
 >>> import java.io.File
 >>> read = read(FileReader("some arff file"))
 >>> data = Instances(read)
 >>> file = FileReader("some arff file")
 >>> data = Instances(file)
 >>> xmeans = xmeans()
 >>> xmeans.setMaxNumClusters(100)  
 >>> xmeans.setMinNumClusters(2) 
 >>> xmeans.buildClusterer(data)# here's our model 
 >>> enumerated_instances = data.enumerateInstances() #get the index of each instance 
 >>> for index, instance in enumerate(enumerated_instances):
         cluster_num = xmeans.clusterInstance(instance) #pass each instance through the model
         print "instance # ",index,"is in cluster ", cluster_num #pretty print results

 instance # 0 is in cluster  1
 instance # 1 is in cluster  1
 instance # 2 is in cluster  0
 instance # 3 is in cluster  0

我将所有这些作为参考,因为可以使用相同的方法来获取任何Weka聚类的结果的聚类分配。