K-Nearest Neighbours: Effect of K

K-Nearest Neighbours: Effect of K#

Twitter Handle LinkedIn Profile GitHub Profile Tag

import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets, neighbors
from matplotlib.colors import ListedColormap



def knn_comparison(data, n_neighbors = 15):
    '''
    This function finds k-NN and plots the data.
    '''
    X = data[:, :2]
    y = data[:,2] 
    
    
    # grid cell size
    h = .02
    cmap_light = ListedColormap(['#FFAAAA',  '#AAAAFF'])
    cmap_bold = ListedColormap(['#FF0000', '#0000FF'])


    # the core classifier: k-NN
    clf = neighbors.KNeighborsClassifier(n_neighbors)
    clf.fit(X, y)

    x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
    y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
    
    # we create a mesh grid (x_min,y_min) to (x_max y_max) with 0.02 grid spaces
    xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))
    
    # we predict the value (either 0 or 1) of each element in the grid
    Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])
    
    # xx.ravel() will give a flatten array

    # np.c_ : Translates slice objects to concatenation along the second axis.
    # > np.c_[np.array([1,2,3]), np.array([4,5,6])]
    # > array([[1, 4],
    #          [2, 5],
    #          [3, 6]])   (source: np.c_ documentation)
    
    
    
    
    # convert the out back to the xx shape (we need it to plot the decission boundry)
    Z = Z.reshape(xx.shape)
    
    
    # pcolormesh will plot the (xx,yy) grid with colors according to the values of Z
    # it looks like decision boundry
    plt.figure()
    plt.pcolormesh(xx, yy, Z, cmap=cmap_light)
   
    # scatter plot of with given points
    plt.scatter(X[:, 0], X[:, 1], c=y, cmap=cmap_bold)
    
    #defining scale on both axises
    plt.xlim(xx.min(), xx.max())
    plt.ylim(yy.min(), yy.max())
   
    # set the title
    plt.title('K value = '+str(n_neighbors))
    

    plt.show()

Meshgrid explanation#

title please check this link stackoverflow meshgrid explanation

data = np.genfromtxt('data/6.overlap.csv', delimiter=',')
knn_comparison(data, 1)
knn_comparison(data, 5)
knn_comparison(data,15)
knn_comparison(data, 30)
knn_comparison(data, 50)
---------------------------------------------------------------------------
FileNotFoundError                         Traceback (most recent call last)
Cell In[3], line 1
----> 1 data = np.genfromtxt('data/6.overlap.csv', delimiter=',')
      2 knn_comparison(data, 1)
      3 knn_comparison(data, 5)
      4 knn_comparison(data,15)

File ~/work/omniverse/omniverse/.venv/lib/python3.14/site-packages/numpy/lib/_npyio_impl.py:1982, in genfromtxt(fname, dtype, comments, delimiter, skip_header, skip_footer, converters, missing_values, filling_values, usecols, names, excludelist, deletechars, replace_space, autostrip, case_sensitive, defaultfmt, unpack, usemask, loose, invalid_raise, max_rows, encoding, ndmin, like)
   1980     fname = os.fspath(fname)
   1981 if isinstance(fname, str):
-> 1982     fid = np.lib._datasource.open(fname, 'rt', encoding=encoding)
   1983     fid_ctx = contextlib.closing(fid)
   1984 else:

File ~/work/omniverse/omniverse/.venv/lib/python3.14/site-packages/numpy/lib/_datasource.py:192, in open(path, mode, destpath, encoding, newline)
    155 """
    156 Open `path` with `mode` and return the file object.
    157 
   (...)    188 
    189 """
    191 ds = DataSource(destpath)
--> 192 return ds.open(path, mode, encoding=encoding, newline=newline)

File ~/work/omniverse/omniverse/.venv/lib/python3.14/site-packages/numpy/lib/_datasource.py:529, in DataSource.open(self, path, mode, encoding, newline)
    526     return _file_openers[ext](found, mode=mode,
    527                               encoding=encoding, newline=newline)
    528 else:
--> 529     raise FileNotFoundError(f"{path} not found.")

FileNotFoundError: data/6.overlap.csv not found.
data = np.genfromtxt('data/1.ushape.csv', delimiter=',')
knn_comparison(data, 1)
knn_comparison(data, 5)
knn_comparison(data,15)
knn_comparison(data,30)
../../_images/ba5e00fba933be47f980c349a2f9cfc8871eee55638dafc29289590800e1bd58.png ../../_images/8f91c423e0af430aa42b038edd7dd8590bc0b142104f3de1f1c1bdb8c1ad6a4c.png ../../_images/06a8f5cb521ff6235f039150f6b94d5edf150b745edc3bcea6f29e3579d8dd14.png ../../_images/3dfd92d3816bd7924f8c7091afff205f10e0ae7589d895197996a7ace75c5758.png
data = np.genfromtxt('data/2.concerticcir1.csv', delimiter=',')
knn_comparison(data, 1)
knn_comparison(data, 5)
knn_comparison(data,15)
knn_comparison(data,30)
../../_images/b0789892c73c01c4e6edcfecc0d703a64f607a74937e1f2edf3d60ac28b3bba4.png ../../_images/500f724beba44e18b186d1b6fc5b974fd88505c1bd19c4754eda5315f40590f3.png ../../_images/bf711178f5232ba32cb857d3d077bb9ce18fb07e946b835c731ddba726cf96a5.png ../../_images/0ce672902e231c02ff043344ac9fb50278136f6e5ea3250672b3c09a95e5499b.png
data = np.genfromtxt('data/3.concertriccir2.csv', delimiter=',')
knn_comparison(data, 1)
knn_comparison(data, 5)
knn_comparison(data, 15)
../../_images/0f42b0308f0a0796ec26dd1ab180aaeab4918ee3e6f88e2638c29ffb278bea15.png ../../_images/a673bf22dd44e602a2a7431b1531f67e3599713dad4ce2f0e0ffc9865bb84f6a.png ../../_images/8cdbebca07c77b9e476f7462a5ca88b51a0ee2405c006dbc74e3a45ddf651640.png
data = np.genfromtxt('data/4.linearsep.csv', delimiter=',')
knn_comparison(data, 1)
knn_comparison(data, 5)
knn_comparison(data)
../../_images/302c470309aa4444064d12a1b78a9af1f0063bc6ee13d345994e49b60b8b0017.png ../../_images/85d77c168574a03c9f95fcfc7cbec804ab56a3fd9cb4b300b3ce927ca38dce54.png ../../_images/ed4e2d9087635a52a0161589734c54f5d1b170df52803c6c9b3d1a30ce619dae.png
data = np.genfromtxt('data/5.outlier.csv', delimiter=',')
knn_comparison(data,1)
knn_comparison(data,5)
knn_comparison(data)
../../_images/5c795923253209b808f6f0faed79d76bd71816c59d2ca7ce5e88981080881c05.png ../../_images/1a2e4b8f5a314d1c49d49124ed99a554b629757e28b01d921f96ff43f75f3585.png ../../_images/7f5bba0c03718b358abc40e2dcae0a8400ae568d839ba5bc3dc6fd8c7403ccb1.png
data = np.genfromtxt('data/7.xor.csv', delimiter=',')
knn_comparison(data, 1)
knn_comparison(data, 5)
knn_comparison(data)
../../_images/9affcb16397290ee9422b79c96faa881fa518d78bc52c5a94e7fd78b50320f44.png ../../_images/dce4e0f8381b23f60a8821d4cd38ba180e9cefe936ac251f83a9be0cdfdcc610.png ../../_images/7b164dee634d04c22c8e53e849b1b2bffc7461220461f3f4f7ae94b30527d029.png
data = np.genfromtxt('data/8.twospirals.csv', delimiter=',')
knn_comparison(data, 1)
knn_comparison(data, 5)
knn_comparison(data)
../../_images/213011b798d642ff5130d53fccd6fdde149948dbb5c41ede00d26715a8b2c2e6.png ../../_images/d94f3f76f5693e335ae5f3028687e9b2a6257a9fc0091a72fcaa506dc933badb.png ../../_images/4e5f307f14449790b89ca71462c8568e2a627facbd0b8d755d08991f3f39f368.png
data = np.genfromtxt('data/9.random.csv', delimiter=',')
knn_comparison(data, 1)
knn_comparison(data, 5)
knn_comparison(data)
../../_images/ff6df72cf80557c47f96d138bf99aa73b2bbeb24e7d3d76aeed7aeb40c584f07.png ../../_images/5d0c306f062152cd91d14b67ff3e2da375781aeb4ed38674f47262702752f3bf.png ../../_images/a6415e18166eff4d2297a71d055ee3eedc65b2d2ef915e13e0b9c67050ae865f.png