我正在尝试使用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
但是如何将此扩展到NxD输入A,例如当A = tf.constant([[1, 1, 2, 4, 4, 4, 7, 8, 8],
[2, 2, 3, 3, 3, 4, 4, 5, 6]])
的情况呢?