我曾爲K最近鄰居製作函數。我已經分別測試了每個功能,並且它們都工作正常。然而,無論何時我將它們放在一起並運行KNN_method
,它都會顯示unhashable type: 'numpy.ndarray'
。 這裏是我的代碼:Python難以置信的類型:'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)
我希望這只是一個練習。 Scipy已經優化了KNN功能和數據結構。還可以查看來自PyCon US 2016和SciPy 2016的Leland McInnes的hdbscan講座。https://www.youtube.com/watch?v=AgPQ76RIi6A https://github.com/lmcinnes/hdbscan – IceArdor
像列表一樣,數組不能用作字典鍵。他們是可變的對象。字符串和元組是不可變的,並且作爲鍵。你真的需要使用一個數組作爲關鍵嗎? – hpaulj
如果您提供了可以複製問題的示例輸入,並指定哪一行引發異常,這將有所幫助。 – jez