我编写了一个简单的脚本,旨在对一个简单的测试数据集进行层次聚类。
我发现函数fclusterdata可以将我的数据聚集到两个集群中。它需要两个强制调用参数:数据集和阈值。问题是,我找不到可以产生预期的两个集群的阈值。
如果有人能告诉我我做错了什么,我会很高兴。如果有人能指出更适合我的集群的其他方法,我也会很高兴(我明确希望避免事先指定集群的数量。)
这是我的代码:
import time
import scipy.cluster.hierarchy as hcluster
import numpy.random as random
import numpy
import pylab
pylab.ion()
data = random.randn(2,200)
data[:100,:100] += 10
for i in range(5,15):
thresh = i/10.
clusters = hcluster.fclusterdata(numpy.transpose(data), thresh)
pylab.scatter(*data[:,:], c=clusters)
pylab.axis("equal")
title = "threshold: %f, number of clusters: %d" % (thresh, len(set(clusters)))
print title
pylab.title(title)
pylab.draw()
time.sleep(0.5)
pylab.clf()
这是输出:
threshold: 0.500000, number of clusters: 129
threshold: 0.600000, number of clusters: 129
threshold: 0.700000, number of clusters: 129
threshold: 0.800000, number of clusters: 75
threshold: 0.900000, number of clusters: 75
threshold: 1.000000, number of clusters: 73
threshold: 1.100000, number of clusters: 58
threshold: 1.200000, number of clusters: 1
threshold: 1.300000, number of clusters: 1
threshold: 1.400000, number of clusters: 1