# 8. Nearest Neighbors

## 8.1. Ball tree

[1]:

import numpy as np
from sklearn.neighbors import BallTree

X = np.array([
[-2, -2],
[-1, -1],
[0, 0],
[1, 1],
[2, 2]])

q = np.array([
[0, 0],
[-1.5, -1.5]
])

tree = BallTree(X)
distance, indices = tree.query(q, k=2)

print('distances')
print(distance)
print('-')
print('indices')
print(indices)

distances
[[0.         1.41421356]
[0.70710678 0.70710678]]
-
indices
[[2 1]
[1 0]]


## 8.2. KD tree

[2]:

from sklearn.neighbors import KDTree

X = np.array([
[-2, -2],
[-1, -1],
[0, 0],
[1, 1],
[2, 2]])

q = np.array([
[0, 0],
[-1.5, -1.5]
])

tree = KDTree(X)
distance, indices = tree.query(q, k=2)

print('distances')
print(distance)
print('-')
print('indices')
print(indices)

distances
[[0.         1.41421356]
[0.70710678 0.70710678]]
-
indices
[[2 1]
[1 0]]


## 8.3. Nearest centroid

[3]:

from sklearn.neighbors import NearestCentroid

X = np.array([
[-2, -2],
[-1, -1],
[1, 1],
[2, 2]])

y = np.array([0, 0, 1, 1])

q = np.array([
[1.5, 1.5],
[-1.5, -1.5]
])

nc = NearestCentroid()
nc.fit(X, y)

nc.predict(q)

[3]:

array([1, 0])


## 8.4. Nearest neighbor

[4]:

from sklearn.neighbors import NearestNeighbors

X = np.array([
[-2, -2],
[-1, -1],
[0, 0],
[1, 1],
[2, 2]])

q = np.array([
[0, 0],
[-1.5, -1.5]
])

nn = NearestNeighbors(n_neighbors=2)
nn.fit(X)
distance, indices = nn.kneighbors(q)

print('distances')
print(distance)
print('-')
print('indices')
print(indices)

distances
[[0.         1.41421356]
[0.70710678 0.70710678]]
-
indices
[[2 1]
[0 1]]