Skip to main content
 首页 » 编程设计

python之在 TensorFlow KMean 类中解压的值太多

2024年08月16日27sky-heaven

我目前正在使用 tensorflow.contrib.factorization 模块中的 KMeans 类。我的输入是(假设所有变量都已定义):

kmeans = KMeans(inputs=X, num_clusters=k, distance_metric='cosine', use_mini_batch=True) 

我正在关注 https://www.tensorflow.org/api_docs/python/tf/contrib/factorization/KMeans 上的文档解压值,如:

(all_scores, cluster_idx, scores, cluster_centers_initialized, init_op, train_op) = kmeans.training_graph() 

我得到错误:

----> (all_scores, cluster_idx, scores, cluster_centers_initialized, init_op, train_op) = kmeans.training_graph()     
ValueError: too many values to unpack 

我强烈猜测上述链接中的文档未更新,因为kmeans.training_graph() 的输出是:

((<tf.Tensor 'sub_14:0' shape=(?, ?) dtype=float32>,), 
 (<tf.Tensor 'Squeeze_7:0' shape=<unknown> dtype=int64>,), 
 (<tf.Tensor 'Squeeze_6:0' shape=<unknown> dtype=float32>,), 
 <tf.Variable 'initialized_3:0' shape=() dtype=bool_ref>, 
 <tf.Variable 'clusters_3:0' shape=<unknown> dtype=float32_ref>, 
 tf.Tensor 'cond_3/Merge:0' shape=() dtype=bool>, 
 <tf.Operation 'group_deps_3' type=NoOp>) 

请通过阅读文档让我知道我不知道的额外返回值是多少。

请您参考如下方法:

更新:来自history of the file clustering_ops.py (master branch) ,附加值 (cluster_centers_vars) 似乎在 following commit from 6.Oct 中被删除了,即它推出后不久。

这意味着您的初始代码应该可以与更新版本的 TF 完美配合,即

(all_scores, cluster_idx, scores, cluster_centers_initialized, init_op, train_op) = kmeans.training_graph() 

现在应该又好了。

但是,结果是您无法通过 kmeans.training_graph() 函数获取聚类中心。

如果要获取聚类中心,有两种解决方案。

第一个解决方案很简单,即使用文件 kmeans.py 中定义的 KMeansClustering 估计器.更具体地说,您可以使用方法 KMeansClustering.cluster_centers()。

第二种解决方案是一种变通方法。如果您不使用 KMeansClustering 估计器,而只使用文件 clustering_ops.py 中定义的 KMeans 图构造函数, 那么你仍然可以通过读取全局 TF 变量 'clusters:0' 来获取聚类中心:

tf_vble_cluster_centers = tf.global_variables('clusters:0')[0] # get the global TF variable 'clusters:0' 
cluster_centers = sess.run(tf_vble_cluster_centers) # evaluate its contents 
print(cluster_centers.shape) # nr. rows = nr. of clusters, nr. columns = nr. dimensions 
print(cluster_centers[0]) # print cluster centers for the first cluster