我看到在tensorflow contrib庫中有一個Kmeans聚類的實現。但是,我無法做簡單的估算2D點聚類中心的操作。Kmeans聚類如何在tensorflow中工作?
代碼:
## 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? –