2016-07-22 33 views
0

我正在玩Tensorflow並實現了k均值聚類算法。一切運作良好,但如果我想通過list中的幾次提取來運行會話,我總是會收到錯誤,表明list無法轉換爲TensorOperation運行一個帶有提取列表的tensorflow不起作用

documentation明確地說,我可以用列表呼叫Session.run()。我做錯了什麼?

這裏是源代碼:

import tensorflow as tf 
import numpy as np 

def tf_k_means(k, data, eps_=0.1): 
    eps = tf.constant(eps_) 

    cluster_means = tf.placeholder(tf.float32, [None, 2]) 
    tf_data = tf.placeholder(tf.float32, [None, 2], name='data') 

    model = tf.initialize_all_variables() 

    expanded_data = tf.expand_dims(tf_data, 0) 
    expanded_means = tf.expand_dims(cluster_means, 1) 
    distances = tf.reduce_sum(tf.square(tf.sub(expanded_means, expanded_data)), 2) 
    mins = tf.to_int32(tf.argmin(distances, 0)) 

    clusters = tf.dynamic_partition(tf_data, mins, k) 
    old_cluster_means = tf.identity(cluster_means) 
    new_means = tf.concat(0, [tf.expand_dims(tf.reduce_mean(cluster, 0), 0) for cluster in clusters]) 

    clusters_moved = tf.reduce_sum(tf.square(tf.sub(old_cluster_means, new_means)), 1) 
    converged = tf.reduce_all(tf.less(clusters_moved, eps)) 

    cms = data[np.random.randint(data.shape[0],size=k), :] 

    with tf.Session() as sess: 
     sess.run(model) 
     conv = False 
     while not conv: 
      ##################################### 
      # THE FOLLOWING LINE DOES NOT WORK: # 
      ##################################### 
      (cs, cms, conv) = sess.run([clusters, new_means, converged], 
             feed_dict={tf_data: data, cluster_means: cms})  

    return cs, cms 

以下是錯誤消息:

TypeError: Fetch argument [<tf.Tensor 'DynamicPartition_25:0' shape=(?, 2) dtype=float32>, 
<tf.Tensor 'DynamicPartition_25:1' shape=(?, 2) dtype=float32>, 
<tf.Tensor 'DynamicPartition_25:2' shape=(?, 2) dtype=float32>, 
<tf.Tensor 'DynamicPartition_25:3' shape=(?, 2) dtype=float32>] of 
[<tf.Tensor 'DynamicPartition_25:0' shape=(?, 2) dtype=float32>, 
<tf.Tensor 'DynamicPartition_25:1' shape=(?, 2) dtype=float32>, 
<tf.Tensor 'DynamicPartition_25:2' shape=(?, 2) dtype=float32>, 
<tf.Tensor 'DynamicPartition_25:3' shape=(?, 2) dtype=float32>] has 
invalid type <class 'list'>, must be a string or Tensor. (Can not 
convert a list into a Tensor or Operation.) 

回答

2
tf.dynamic_partition

返回一個list of Tensors,所以clusters是自身的列表。

clusters = tf.dynamic_partition(tf_data, mins, k) 

當您將該列表反饋到另一個列表中的sess.run時,我認爲這是您的問題所在。你可以嘗試:

sess.run(clusters + [new_means, converged], ... 
相關問題