dakshdixit183

Untitled

Sep 1st, 2023
116
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.71 KB | None | 0 0
  1. import pandas as pd
  2. import numpy as np
  3. import matplotlib.pyplot as plt
  4. from sklearn.model_selection import train_test_split
  5. from collections import Counter
  6. from sklearn.metrics import accuracy_score
  7.  
  8.  
  9.  
  10.  
  11.  
  12. dataset_path = 'data/diabetes.csv'
  13. df = pd.read_csv(dataset_path)
  14. # Show the first few rows of the dataset
  15. df.head()
  16.  
  17.  
  18.  
  19.  
  20.  
  21. X = df.drop('Outcome', axis=1).values
  22. y = df['Outcome'].values
  23. X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
  24. X_train.shape, X_test.shape, y_train.shape, y_test.shape
  25.  
  26.  
  27.  
  28. class KNN:
  29. def __init__(self, k=3):
  30. self.k = k
  31.  
  32. def fit(self, X, y):
  33. self.X_train = X
  34. self.y_train = y
  35.  
  36. def predict(self, X):
  37. y_pred = [self._predict(x) for x in X]
  38. return np.array(y_pred)
  39.  
  40. def _predict(self, x):
  41. # Compute distances between x and all examples in the training set
  42. distances = [np.linalg.norm(x - x_train) for x_train in self.X_train]
  43. # Sort by distance and return indices of the first k neighbors
  44. k_indices = np.argsort(distances)[:self.k]
  45. # Extract the labels of the k nearest neighbor training samples
  46. k_nearest_labels = [self.y_train[i] for i in k_indices]
  47. # Return the most common class label among k nearest neighbors
  48. most_common = Counter(k_nearest_labels).most_common(1)
  49. return most_common[0][0]
  50. # Initialize KNN classifier with k=3
  51. knn = KNN(k=3)
  52. # Fit the model with the training data
  53. knn.fit(X_train, y_train)
  54. # Make predictions on the test data
  55. y_pred = knn.predict(X_test)
  56. # Display some of the predictions
  57. y_pred[:10]
  58.  
  59.  
  60.  
  61.  
  62.  
  63. accuracy = accuracy_score(y_test, y_pred)
  64. accuracy
Advertisement
Add Comment
Please, Sign In to add comment