数据
为了方便, 我们使用 MNIST 数据集.
核心 API
(all_scores, cluster_idx, scores, cluster_centers_initialized, init_op, train_op) = kmeans.training_graph() |
这个 API 用来生成一个 kmeans 算法的计算图.
API 返回一个元组:
- all_scores: 返回一个维度为 (num_input, num_clusters) 的矩阵, 值是每个 input vector 和 cluster center 的距离.
- cluster_idx: 一个 vector, 包含了 cluster 的 id. TODO inp ?
- scores: 对应与每个 cluster 的距离.
- cluster_centers_initialized: 标记是否被初始化.
- init_op: 初始化 clusters 的 op.
- train_op: 训练用的的 op.
开始
首先加载 MNIST 数据:
|
然后是构建训练的计算图 :
# 输入 |
运行后, 可以查看训练的输出:
Step 1, Avg Distance: 0.341471 |
可视化
为了直观的看结果的分布, 我们可以用散点图来显示, 先使用 PCA 再根据对应 label 画散点图.
# counts, shape: (25, 10) |
plot:
from sklearn.decomposition import PCA |
将训练后的结果 plot 之后, 还是分类比较明显的 (虽然准确度不高...):
其他
1.4 的 API 已经有返回 cluster 中心了, 请看这里
cluster_centers_var
: a Variable holding the cluster centers.
参考
https://github.com/aymericdamien/TensorFlow-Examples/blob/master/examples/2_BasicModels/kmeans.py
http://scikit-learn.org/stable/auto_examples/cluster/plot_kmeans_digits.html