Python 使用回迁列表运行tensorflow不起作用
我在玩Tensorflow,实现了一个k均值聚类算法。一切都很好,但是如果我想在Python 使用回迁列表运行tensorflow不起作用,python,tensorflow,Python,Tensorflow,我在玩Tensorflow,实现了一个k均值聚类算法。一切都很好,但是如果我想在列表中使用两次回迁来运行会话,我总是会得到一个错误,列表不能转换为张量或操作 代码明确地说,我可以使用列表调用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
列表
中使用两次回迁来运行会话,我总是会得到一个错误,列表
不能转换为张量
或操作
代码明确地说,我可以使用列表调用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.)
TypeError:Fetch参数[,,
,
,
]的
[,
,
,
]有
无效类型,必须是字符串或张量。(不能
将列表转换为张量或运算。)
tf.dynamic_partition
返回一个值,因此集群本身就是一个列表
clusters = tf.dynamic_partition(tf_data, mins, k)
当您将该列表输入到sess.run中的另一个列表中时,我认为这就是您的问题所在。你可以试试:
sess.run(clusters + [new_means, converged], ...
tf.dynamic_partition
返回一个值,因此clusters
本身就是一个列表
clusters = tf.dynamic_partition(tf_data, mins, k)
当您将该列表输入到sess.run中的另一个列表中时,我认为这就是您的问题所在。你可以试试:
sess.run(clusters + [new_means, converged], ...