Tensorflow:无法将函数转换为Tensor或Operation

时间:2018-01-18 21:07:31

标签: python tensorflow machine-learning

我已阅读过之前的字符串。我的数据是以送到占位符的数组的形式。在进给之前尝试将数据转换为张量会产生不同的(反向)错误消息。在这种情况下,其他解决方案似乎也不起作用。这是最小的代码。

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})

1 个答案:

答案 0 :(得分:1)

正确,您无法仅评估lump,因为它是函数(返回张量),而不是 tensor op < / em>的。你可能想做这样的事情:

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显然没有完成并且存在维度问题,但它是评估会话中某些内容的正确方法。