Python 不可哈希类型:'numpy.ndarray'

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41436542/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 00:57:36  来源:igfitidea点击:

Python unhashable type: 'numpy.ndarray'

pythonnumpy

提问by Cantarella

I worked on making functions for K Nearest Neighbors. I have tested each function separately and they all work well. However whenever I put them together and run KNN_method, it shows unhashable type: 'numpy.ndarray'. Here is my code:

我致力于为 K 最近的邻居制作函数。我分别测试了每个功能,它们都运行良好。但是,每当我将它们放在一起并运行时KNN_method,它就会显示unhashable type: 'numpy.ndarray'。这是我的代码:

def distance(p,point):
    import numpy as np
    value = np.sqrt(sum(np.power((p-point),2)))
    return(value)

def find_neighbors(p,list_of_points, k = 3):
    import numpy as np
    distances = np.zeros(list_of_points.shape[0])
    for i in range(list_of_points.shape[0]):
        distances[i]= distance(p,list_of_points[i])
    ind = np.argsort(distances)
    return(ind[0:k])

def majority_votes(votes):
    import random
    vote_result = {}
    for key in votes:
        if key in vote_result:
            vote_result[key] += 1
        else:
            vote_result[key] = 1
    final_list = []
    for (number, vote) in vote_result.items():
        if vote == max(vote_result.values()):
            final_list.append(number)
    Winner = random.choice(final_list)
    return(Winner)


def KNN_method(p , list_of_points , outcomes , k = 3):
    ind = find_neighbors(p , list_of_points , k) 
    Final = majority_votes(outcomes[ind])
    return(Final)

回答by DaveQ

Convert to tuple first.

首先转换为元组。

hash(tuple(np.array([1,2,3,4])))