参考这个链接,(链接),我尝试使用 tf.contrib.factorization.KMeansClustering 进行聚类。以下简单的代码运行正常:
import numpy as np
import tensorflow as tf
# ---- 创建数据样本 -----
k = 5
n = 100
variables = 5
points = np.random.uniform(0, 1000, [n, variables])
# ---- 聚类 -----
input_fn=lambda: tf.train.limit_epochs(tf.convert_to_tensor(points, dtype=tf.float32), num_epochs=1)
kmeans=tf.contrib.factorization.KMeansClustering(num_clusters=6)
kmeans.train(input_fn=input_fn)
centers = kmeans.cluster_centers()
# ---- 输出结果 -----
cluster_indices = list(kmeans.predict_cluster_index(input_fn))
for i, point in enumerate(points):
cluster_index = cluster_indices[i]
print ('point:', point, 'is in cluster', cluster_index, 'centered at', centers[cluster_index])
我的问题是,为什么这个 “input_fn” 代码能起作用?如果我将代码改成这样,它会陷入无限循环。为什么?
input_fn=lambda:tf.convert_to_tensor(points, dtype=tf.float32)
根据文档 (这里),train() 函数期望 input_fn 参数是一个 ‘tf.data.Dataset’ 对象,就像 Tensor(X)。那么,为什么我必须使用 lambda: tf.train.limit_epochs() 做这些复杂的事情呢?
有谁熟悉 TensorFlow 估计器的基础知识可以帮助解释吗?非常感谢!
回答:
我的问题是,为什么这个 “input_fn” 代码能起作用?如果我将代码改成这样,它会陷入无限循环。为什么?
文档中说明 input_fn
会被反复调用,直到它返回一个 tf.errors.OutOfRangeError
。使用 tf.train.limit_epochs
来装饰你的张量可以确保最终会引发这个错误,从而向 KMeans 发出停止训练的信号。