当我将常规knn方法应用于算法时,遇到了此问题:
TypeError:不可哈希类型:'numpy.ndarray'
def classify(inx, dataset, labels, k):
dist = tf.sqrt(tf.reduce_sum(tf.square(inx - dataset), axis=1))
k_labels = [labels[index] for index in np.argsort(dist)[0 : k]]
lab = collections.Counter(k_labels).most_common(1)[0][0]
return lab
错误:
File "C:/Users/xjy/untitled0.py", line 166, in classify
lab = collections.Counter(k_labels).most_common(1)[0][0]
File "C:\Users\xjy\Anaconda3\envs\xjy\lib\collections\__init__.py", line 535, in __init__
self.update(*args, **kwds)
File "C:\Users\xjy\Anaconda3\envs\xjy\lib\collections\__init__.py", line 622, in update
_count_elements(self, iterable)
TypeError: unhashable type: 'numpy.ndarray'
答案 0 :(得分:0)
如果您的k_labels为[array([1., 0., 0., 0., 0., 0., 0., 0.], dtype=float32)]
,则
使用
lab = collections.Counter(k_labels[0]).most_common(1)[0][0]