From c3319ba5b6f0c70019310d2e4224fd6e8c1ef7a7 Mon Sep 17 00:00:00 2001 From: G-Dinusha Date: Sat, 19 Oct 2024 10:39:05 +0530 Subject: [PATCH] Update kNearestNeighbour.py --- ML Algorithms/kNearestNeighbour.py | 77 +++++++++++++++++------------- 1 file changed, 44 insertions(+), 33 deletions(-) diff --git a/ML Algorithms/kNearestNeighbour.py b/ML Algorithms/kNearestNeighbour.py index d2d778d05..5ac348baa 100644 --- a/ML Algorithms/kNearestNeighbour.py +++ b/ML Algorithms/kNearestNeighbour.py @@ -1,41 +1,52 @@ import matplotlib.pyplot as plt import numpy as np -import math -f=[[10,5],[40,7],[3,2],[5,3]] -l=['good','good','bad','bad'] -x=[] -y=[] -s=len(set(l)) #shows all categories present +import math + +# Input data points +f = [[10, 5], [40, 7], [3, 2], [5, 3]] +l = ['good', 'good', 'bad', 'bad'] + +# Initialize numpy arrays +x = np.array([point[0] for point in f]) +y = np.array([point[1] for point in f]) + +print(x, " ", y) + +# Plot data points based on labels for i in range(len(f)): - f1=f[i][0] - x=np.append(x,f1) - f2=f[i][1] - y=np.append(y,f2) -print(x," ",y) -for i in range(len(f)): - if (l[i]== 'good'): - plt.plot(x[i],y[i],'r*') + if l[i] == 'good': + plt.plot(x[i], y[i], 'r*', label='Good Habits' if i == 0 else "") else: - plt.plot(x[i],y[i],"y^") -p = int(input("Enter saving%")) -q = int(input("Enter no. of good habit")) -k=int(input("Enter k")) -plt.plot(p,q,'b*') -disx=[] -disy=[] -dis=[] -if (k>len(f)): - k=len(f) -for i in range(len(x)): - dis=np.append(dis,math.sqrt(((p-x[i])**2)+((q-y[i])**2))) + plt.plot(x[i], y[i], 'y^', label='Bad Habits' if i == 0 else "") + +# User inputs +p = int(input("Enter saving%: ")) +q = int(input("Enter no. of good habits: ")) +k = int(input("Enter k: ")) + +# Plot user input point +plt.plot(p, q, 'b*', label='User Input') + +# Calculate distances +dis = np.array([math.sqrt(((p - x[i]) ** 2) + ((q - y[i]) ** 2)) for i in range(len(x))]) print(dis) + +# Sort distances and get the k smallest dis.sort() -min1=[] -for i in range(k): - min1=np.append(min1,dis[i]) +min1 = dis[:k] # Get the k smallest distances print(min1) -sum1=0 -for i in range(len(min1)): - sum1=sum1+min1[i] -print(sum1/len(min1)) #avgmin = sum1/len(min1) + +# Calculate average of the smallest distances +if len(min1) > 0: + avg_min = sum(min1) / len(min1) + print("Average of the k smallest distances:", avg_min) +else: + print("No distances to calculate average.") + +# Add legends and labels +plt.title('Habits Visualization') +plt.xlabel('Saving Percentage') +plt.ylabel('Number of Good Habits') +plt.legend() +plt.grid(True) plt.show()