K-nearest Neighbors Classifier subpackage (battelle.knn)
|
Instance of a k-Nearest Neighbors Classifier. |
Predict the class label for the provided point |
|
Fit the k-nearest neighbors classifier from the training dataset. |
This module allows the user to create and train k-nearest neighbor classifiers.
Here is a simple example of binary classification:
import numpy as np
import matplotlib.pyplot as plt
from battelle.knn import KNearestNeighborsClassifier
neigh = KNearestNeighborsClassifier()
x = np.random.random(size=(300,2)) - 0.5
x = [list(xi) for xi in x]
y = np.array([np.sign(np.prod(k)) for k in x])
neigh.train(x,y)
# Plot training data
plt.subplot(1,2,1)
for i, xi in enumerate(x):
if y[i] == 1:
plt.plot(xi[0], xi[1], 'xr')
else:
plt.plot(xi[0], xi[1], 'xb')
plt.title("Testing data")
# Plot neural net result
plt.subplot(1,2,2)
xrange = np.linspace(-0.5, 0.5, 20)
yrange = np.linspace(-0.5, 0.5, 20)
for x in xrange:
for y in yrange:
if neigh.predict([x, y]) > 0:
plt.plot(x, y, 'xr')
else:
plt.plot(x, y, 'xb')
plt.title("k-NN result")
plt.show()
This code creates the following graph: