In [65]:
%matplotlib inline
import numpy as np
from matplotlib import pyplot as plt

In [66]:
a = np.arange(9)
a


Out[66]:
array([0, 1, 2, 3, 4, 5, 6, 7, 8])

In [67]:
b = np.arange(3,21,2)
b


Out[67]:
array([ 3,  5,  7,  9, 11, 13, 15, 17, 19])

In [68]:
plt.gca().set_aspect('equal')
plt.scatter(a,b)


Out[68]:
<matplotlib.collections.PathCollection at 0x7fad185febd0>

In [69]:
pts = np.random.uniform(size=(2,200))

In [70]:
x = pts[0,:]
y = pts[1,:]

plt.scatter(x,y)


Out[70]:
<matplotlib.collections.PathCollection at 0x7fad18686290>

In [71]:
from sklearn.datasets import make_moons

# make classification problem
X, y = make_moons(n_samples=500, noise=0.3)

In [72]:
# represent the coordinates in several convenient ways
I = X[:,0]
J = X[:,1]

plt.gca().set_aspect('equal')
plt.scatter(I, J, c=y, cmap='cool')


Out[72]:
<matplotlib.collections.PathCollection at 0x7fad184fbfd0>

In [73]:
from sklearn.neighbors import KNeighborsClassifier

model = KNeighborsClassifier(n_neighbors=7,metric='euclidean')
model.fit(X,y)


Out[73]:
KNeighborsClassifier(algorithm='auto', leaf_size=30, metric='euclidean',
           metric_params=None, n_jobs=1, n_neighbors=7, p=2,
           weights='uniform')

In [74]:
resolution = 600

i = np.linspace(-3,3,resolution)

j, k = np.meshgrid(i,i)
pts = np.dstack((j,k)).reshape(-1,2)
pts


Out[74]:
array([[-3.        , -3.        ],
       [-2.98998331, -3.        ],
       [-2.97996661, -3.        ],
       ..., 
       [ 2.97996661,  3.        ],
       [ 2.98998331,  3.        ],
       [ 3.        ,  3.        ]])

In [75]:
y


Out[75]:
array([0, 0, 0, 1, 0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1,
       1, 1, 1, 0, 1, 0, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 1, 1,
       0, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 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, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 1, 0, 1, 1,
       1, 0, 1, 1, 1, 0, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 1, 0,
       1, 0, 1, 0, 0, 1, 0, 1, 1, 1, 0, 1, 1, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0,
       1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1,
       1, 1, 1, 0, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1])

In [76]:
py = model.predict(pts)
py.shape
py_img = py.reshape((resolution,resolution))

plt.scatter(I, J, c=y, cmap='cool')
plt.imshow(py_img,origin='lower',cmap='cool',extent=[-3,3,-3,3])


Out[76]:
<matplotlib.image.AxesImage at 0x7fad187d0290>

In [76]: