Guest User

Untitled

a guest
Jul 19th, 2018
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.62 KB | None | 0 0
  1. import numpy as np
  2. from math import sqrt
  3. import warnings
  4. import pandas as pd
  5. import random
  6. from collections import Counter
  7.  
  8. def k_nearest_neighbors(data,predict,k=3):
  9. if(len(data)>=k):
  10. warnings.warn('K is set to a value less than total voting groups')
  11. distances=[]
  12. for group in data:
  13. for features in data[group]:
  14. euclidean_distance=np.linalg.norm(np.array(features)-np.array(predict))
  15. distances.append([euclidean_distance,group])
  16.  
  17. votes=[i[1] for i in sorted(distances)[:k]]
  18.  
  19.  
  20. vote_result=Counter(votes).most_common(1)[0][0] #now two zeroes meaning is clear
  21. return vote_result
  22.  
  23.  
  24. df=pd.read_csv("breast-cancer-wisconsin.data.txt")
  25. df.replace('?',-99999,inplace=True)
  26. df.drop(['id'],1,inplace=True)
  27.  
  28. full_data=df.astype(float).values.tolist()
  29.  
  30. random.shuffle(full_data)
  31.  
  32.  
  33. test_size=0.2
  34. train_set={2:[],4:[]} #dictionary of classes
  35. test_set={2:[],4:[]}
  36. train_data=full_data[:-int(test_size*len(full_data))]
  37. test_data=full_data[-int(test_size*len(full_data)):]
  38.  
  39. #populating our dictionaries
  40. for i in train_data:
  41. train_set[i[-1]].append(i[:-1])
  42.  
  43. for i in test_data:
  44. train_set[i[-1]].append(i[:-1])
  45.  
  46.  
  47. correct=0
  48. total=0
  49.  
  50. print('$')
  51.  
  52. for group in test_set:
  53. for datax in test_set[group]:
  54. print('$') #this is not printing,loop not running
  55. vote=k_nearest_neighbors(train_set,datx,k=5)
  56. if group==vote:
  57. correct+=1
  58. total+=1
  59.  
  60. print('accuracy:',correct/total)
  61.  
  62. Traceback (most recent call last):
  63. File "my_k_near_neigh.py", line 67, in <module>
  64. print(c/t)
  65. ZeroDivisionError: division by zero
Add Comment
Please, Sign In to add comment