我看到tensorflow的contrib库中有Kmeans聚类的实现。然而,我无法简单地估计2D点的簇中心。
代码:
我收到了以下错误信息:
代码:
## Generate synthetic data
N,D = 1000, 2 # number of points and dimenstinality
means = np.array([[0.5, 0.0],
[0, 0],
[-0.5, -0.5],
[-0.8, 0.3]])
covs = np.array([np.diag([0.01, 0.01]),
np.diag([0.01, 0.01]),
np.diag([0.01, 0.01]),
np.diag([0.01, 0.01])])
n_clusters = means.shape[0]
points = []
for i in range(n_clusters):
x = np.random.multivariate_normal(means[i], covs[i], N )
points.append(x)
points = np.concatenate(points)
## construct model
kmeans = tf.contrib.learn.KMeansClustering(num_clusters = n_clusters)
kmeans.fit(points.astype(np.float32))
我收到了以下错误信息:
InvalidArgumentError (see above for traceback): Shape [-1,2] has negative dimensions
[[Node: input = Placeholder[dtype=DT_FLOAT, shape=[?,2], _device="/job:localhost/replica:0/task:0/cpu:0"]()]]
我猜自己做错了一些事情,但从文件中没找出来。
编辑:
我使用input_fn
解决了这个问题,但是速度非常慢(我不得不将每个集群中的点数减少到10才能看到结果)。 为什么会这样,我该如何使它更快?
def input_fn():
return tf.constant(points, dtype=tf.float32), None
## construct model
kmeans = tf.contrib.learn.KMeansClustering(num_clusters = n_clusters, relative_tolerance=0.0001)
kmeans.fit(input_fn=input_fn)
centers = kmeans.clusters()
print(centers)
已解决:
看来需要设置相对容忍度。我只改了一行代码,现在它可以正常工作了。
kmeans = tf.contrib.learn.KMeansClustering(num_clusters = n_clusters, relative_tolerance=0.0001)