Discussion about this post

User's avatar
Orith Loeb's avatar

Thank you!

Expand full comment
Orith Loeb's avatar

Hii,

Please see below:

# DDC-37: KNN classification

import numpy as np

from sklearn.neighbors import KNeighborsClassifier

import matplotlib.pyplot as plt

# ---creating the random numbers groups---

Group0 = np.random.uniform(-2.5, 1.5, size = (10,2))

Group1 = np.random.uniform(-2.5, 1.5, size = (10,2))

# ---combine into one dataframe---

X = np.vstack ((Group0, Group1))

# ---Label---

y = np.array ([0]*len(Group0)+ [1]* len(Group1))

# --- create the knn model---

knn = KNeighborsClassifier (n_neighbors=3)

# ---fit the model---

knn.fit (X, y)

# ---predict for p (0,0)---

new_point = np.array ([[0,0]])

new_prediction = knn.predict(new_point)

print ( "Prediction for new point:", new_prediction)

# ---Plot---

X_0 = X [y==0]

X_1 = X [y==1]

plt.scatter (X_0[:,0], X_0[:, 1] , color = "blue", s = 70, marker = "^" , label = "Group 0")

plt.scatter (X_1[:,0], X_1[:, 1] , color = "red", s = 70, marker="o", label = "Group 1")

plt.scatter (new_point[0,0], new_point[0,1], color = "Green", marker="X", s=100, label= "new point")

plt.xlabel ("Feature 1")

plt.ylabel ("Feature 2")

plt.legend()

plt.show()

Expand full comment
1 more comment...

No posts