Author - Mohit Rathore mrmohitrathoremr@gmail.com - markroxor.in
Licensed under The MIT License - https://opensource.org/licenses/MIT

In [1]:
import numpy as np

from sklearn import datasets
from sklearn.utils import shuffle

from fromscratchtoml.neighbors import KNeighborsClassifier
from fromscratchtoml.toolbox import binary_visualize

%matplotlib inline

K Nearest neighbor Algorithm

In [2]:
iris = datasets.load_iris()

X = iris.data[:, :2]
Y = iris.target[:]
X, Y = shuffle(X, Y, random_state=10)

Xtrain = X[:120]
Ytrain = Y[:120]
Xtest = X[120:]
Ytest = Y[120:]
In [3]:
knn = KNeighborsClassifier()
knn.fit(Xtrain, Ytrain)
Out[3]:
KNeighborsClassifier({'n_neighbors': 5})
In [4]:
knn.predict(Xtest)
Out[4]:
array([2, 1, 1, 0, 1, 0, 1, 1, 2, 1, 0, 1, 2, 2, 1, 2, 1, 0, 2, 0, 0, 1,
       0, 1, 2, 1, 1, 0, 2, 0])

The iris data

In [5]:
binary_visualize(X, Y, coarse=50, color_seed=1980)
In [10]:
binary_visualize(np.array(X), clf=knn, draw_contour=True, coarse=50, color_seed=1980)
In [ ]: