【发布时间】:2018-07-06 18:36:33
【问题描述】:
我正在尝试使用 tensorflow 解决 KNN。在我得到 N 个向量的 K 个邻居之后,我有一个 N×K 张量。现在,对于 N 中的每个向量,我需要使用tf.unique_with_counts 来找到多数票。但是,我无法在张量中进行迭代,也无法使用多维张量运行 tf.unique_with_counts。它一直给我InvalidArgumentError (see above for traceback): unique expects a 1D vector.
示例:
def knnVote():
'''
KNN using majority vote
'''
#nearest indices
A = tf.constant([1, 1, 2, 4, 4, 4, 7, 8, 8])
print(A.shape)
nearest_k_y, idx, votes = tf.unique_with_counts(A)
print("y", nearest_k_y.eval())
print("idx", idx.eval())
print("votes", votes.eval())
majority = tf.argmax(votes)
predict_res = tf.gather(nearest_k_y, majority)
print("majority", majority.eval())
print("predict", predict_res.eval())
return predict_res
结果:
y [1 2 4 7 8]
idx [0 0 1 2 2 2 3 4 4]
votes [2 1 3 1 2]
majority 2
predict 4
但是如何通过D输入A把这个扩展到N,比如A = tf.constant([[1, 1, 2, 4, 4, 4, 7, 8, 8],
[2, 2, 3, 3, 3, 4, 4, 5, 6]])的情况
【问题讨论】:
标签: python tensorflow machine-learning artificial-intelligence nearest-neighbor