使用 “tf.contrib.factorization.KMeansClustering”

参考这个链接,(链接),我尝试使用 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 发出停止训练的信号。

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注