PYTHON 19
AI - Lab - 1 Guest on 5th March 2022 06:30:29 AM
  1. KNN = k-nearest neighbor
  2. To calculate according to the data present
  3. An example
  4.  
  5.  
  6. constant is k, which is fixed
  7. value of k is 3 in this case
  8.  
  9. Name Age Gender Sport      Distance
  10. Ajay 32   0     Football   9
  11. Mark 40   0     Neither    17
  12. Sara 16   1     Cricket    7
  13. Zaira 34  1     Cricket    66
  14. Sachin 55 0     Neither    32
  15. Rahul 40  0     Cricket    17
  16. Pooja 20  1     Neither    77
  17. smith 15  0     Cricket    8
  18. Laxmi 55  1     Football   8
  19. Michael 15 0    Football   8
  20.  
  21. Shayan 23 0
  22.  
  23. Calculating the Euclean Distance of each
  24. d = sqrt((x1-x2)^2(y1-y2)^2)
  25.  
  26. Calculate distance for Ajay:
  27. d = sqrt((23-32)^2(0-0)^2)
  28. =9
  29.  
  30. Find the closest values:
  31. 7,8,8
  32. Check age factor if values are same
  33.  
  34. Cricket would be estimated.
  35.  
  36.  
  37. if more data is added, then it'll be 3d distance. Another variable will be added.
  38. d = sqrt((x1-x2)^2(y1-y2)^2(z1-z2)^2)
  39.  
  40.  
  41.  
  42.  
  43. # coding: utf-8
  44.  
  45. # In[14]:
  46.  
  47. #KNN Algorithm Implementation
  48.  
  49.  
  50. # In[15]:
  51.  
  52. import numpy as np
  53. import matplotlib.pyplot as pit
  54. import pandas as pd
  55.  
  56.  
  57.  
  58. # In[16]:
  59.  
  60. url = "https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data"
  61. names = {'sepal-length', 'sepal-width', 'petal-length', 'petal-width', 'Class'}
  62. dataset = pd.read_csv(url, names=names)
  63.  
  64.  
  65. # In[17]:
  66.  
  67. dataset.head()
  68.  
  69.  
  70. # In[19]:
  71.  
  72. X = dataset.iloc(:, :-1).values
  73. y = dataset.iloc(:, 4).values
  74.  
  75.  
  76. # In[ ]:
  77.  
  78. from sklearn.model_selection import test_train_split
  79. X_train, X_test, y_train, y_test = test_train_split(X,y, test_size=0.20)
  80.  
  81.  
  82. # In[ ]:
  83.  
  84. from sklearn.preprocessing import StandardScalar
  85. scalar = StandardScalar()
  86. scaler.fit(X_train)
  87. X_train = scaler.transform(X_train)
  88. X_test = scaler.transform(X_test)
  89.  
  90.  
  91. # In[ ]:
  92.  
  93. y=pred = classifier.predict(X_test)
  94.  
  95.  
  96. # In[ ]:
  97.  
  98. from sklearn.metrics import classification_report, confusion_matrix
  99. print(classification_report(y_test, y_pred))
  100. print(confusion_matrix(y_test, y_pred))

Coding Base is for source code and general debugging text.

Login or Register to edit, delete and keep track of your pastes and more.

Raw Paste

Login or Register to edit or fork this paste. It's free.