Program 4
Program 4
import numpy as np
import pandas as pd
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score, f1_score
from collections import Counter
class KNN:
def __init__(self, k=3, weighted=False):
self.k = k
self.weighted = weighted
if self.weighted:
weights = [1 / (distances[i] ** 2 + 1e-5) for i in k_indices]
# Adding small value to avoid division by zero
class_weights = {}
for label, weight in zip(k_nearest_labels, weights):
class_weights[label] = class_weights.get(label, 0) +
weight
return max(class_weights, key=class_weights.get)
else:
most_common = Counter(k_nearest_labels).most_common(1)
return most_common[0][0]
# Split data
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2,
random_state=42)