Assignment No 2 AI
Assignment No 2 AI
INTELLIGENCE
CS307/AI202
ASSIGNMENT-02
Task: Implementing K-Nearest Neighbors (KNN)
Q 1: Implement the KNN algorithm in python. This should include functions for
calculating Euclidean distance between data points, getting the K nearest neighbors
of a data point, and predicting the class of a data point based on the majority class of
its K nearest neighbors.
import numpy as np
sorted_indices = np.argsort(distances)
neighbors = data[sorted_indices[:k]]
labels_neighbors = labels[sorted_indices[:k]]
class_counts = Counter(labels_neighbors)
most_frequent_class, _ = class_counts.most_common(1)[0]
return most_frequent_class
# Example usage
data = np.array([[1, 2, 1], [1.5, 1.8, 1], [5, 8, 0], [8, 8, 0]])
k=2
Q 2: Apply your KNN implementation on the Iris dataset. The Iris dataset includes 50
samples from each of three species of Iris flowers with four features measured from
each sample: the lengths and the widths of the sepals and petals.
2
predictions.append(predicted_class)
return np.array(predictions)
# Calculate accuracy
from sklearn.metrics import accuracy_score
accuracy = accuracy_score(y_test, predicted_labels)
print("KNN Accuracy:", accuracy)
Q 3: Compare the results of your KNN implementation with the KNN implemen-
tation from sklearn.
3
4