Ask a Question
Ask Question Login
Corporate Training
  1. Community
  2. Python
  3. Question
Python

Python unhashable type: 'numpy.ndarray'

Asked by Rutuja Mishra Apr 6, 2021 1.2K views 1 answer
Share

About this question

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:

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)

Your answer

1 Answer

More Python discussions

Learn & Explore

Free tutorials and interview questions from industry experts — learn the skill, then get ready to prove it.

Latest Python Blogs

Guides, tips and career advice on Python from JanBask experts.