【问题标题】:How does Kmeans clustering work in tensorflow?Kmeans 聚类在 tensorflow 中是如何工作的?
【发布时间】:2017-08-09 22:48:38
【问题描述】:

我看到在 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)

【问题讨论】:

  • 你运行的是什么版本的TF?

标签: python tensorflow


【解决方案1】:

您的原始代码使用 Tensorflow 1.2 返回以下错误:

    WARNING:tensorflow:From <stdin>:1: calling BaseEstimator.fit (from         
    tensorflow.contrib.learn.python.learn.estimators.estimator) with x 
    is deprecated and will be removed after 2016-12-01.
    Instructions for updating:
    Estimator is decoupled from Scikit Learn interface by moving into
    separate class SKCompat. Arguments x, y and batch_size are only
    available in the SKCompat class, Estimator will only accept input_fn.

根据您的编辑,您似乎发现input_fn 是唯一可接受的输入。如果您真的想使用 TF,我会升级到 r1.2 并将 Estimator 包装在 SKCompat 类中,如错误消息所示。否则,我只会使用 SKLearn 包。也可以在TF中手动实现自己的聚类算法,如this blog所示。

【讨论】:

  • 谢谢。我想到了。不过有一个问题——如果我的观点在 tf 变量中怎么办?它会起作用还是我需要做一些不同的事情? (比如在输入到 kmeans 聚类之前对其进行评估)
  • 没有包装器的 Estimator 不将 TF 张量作为输入,因此不包括占位符和变量。因此,在输入之前对其进行评估应该可以工作!
猜你喜欢
  • 2012-08-09
  • 2019-11-12
  • 2018-12-13
  • 2018-05-15
  • 2016-02-02
  • 2013-03-23
  • 2013-11-18
  • 1970-01-01
  • 2018-05-15
相关资源
最近更新 更多