我已经阅读了前面的字符串。我的数据以数组的形式馈入占位符。在馈送之前尝试将数据转换为张量会产生不同的(反向)错误消息。类似地,其他解决方案在这种情况下似乎不起作用。这是最少的代码。
from __future__ import print_function
import numpy as np
import tensorflow as tf
from tensorflow.contrib.factorization import KMeans
X = tf.placeholder(tf.float32, shape=[None, 10], name="X")
data = np.random.randn(2,10)
def lump(X):
# Build KMeans graph
kmeans = KMeans(inputs=X, num_clusters=k, distance_metric='cosine',
use_mini_batch=True)
(all_scores, cluster_idx, scores, cluster_centers_initialized, cluster_centers_var, init_op,
train_op) = kmeans.training_graph()
cluster_idx = cluster_idx[0] # fix for cluster_idx being a tuple
avg_distance = tf.reduce_mean(scores)
return cluster_idx, scores
# Initialize the variables (i.e. assign their default value)
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
idx, d = sess.run(lump,feed_dict={X: data})
最佳答案
正确,您不能只评估lump
,因为它是一个函数(返回张量),而不是张量或op。您可能打算这样做:
cluster_idx, scores = lump(X)
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
idx, d = sess.run([cluster_idx, scores], feed_dict={X: data})
请注意,在
lump()
之前先调用tf.global_variables_initializer()
,因为它在图形中定义了新变量,因此必须对其进行初始化。代码仍然失败,因为
lump
显然没有完成并且存在尺寸方面的问题,但这是评估会话中某些内容的正确方法。