Last active
September 9, 2016 16:41
-
-
Save sicktastic/65b936bb167d66a4b3f3e0a257c54264 to your computer and use it in GitHub Desktop.
kNN(k Nearest Neighbors) Algorithm example from http://goo.gl/cg0ELd
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
print(__doc__) | |
# Author: Alexandre Gramfort <[email protected]> | |
# Fabian Pedregosa <[email protected]> | |
# | |
# License: BSD 3 clause (C) INRIA | |
############################################################################### | |
# Generate sample data | |
import numpy as np | |
import matplotlib.pyplot as plt | |
from sklearn import neighbors | |
np.random.seed(0) | |
X = np.sort(5 * np.random.rand(40, 1), axis=0) | |
T = np.linspace(0, 5, 500)[:, np.newaxis] | |
y = np.sin(X).ravel() | |
# Add noise to targets | |
y[::5] += 1 * (0.5 - np.random.rand(8)) | |
############################################################################### | |
# Fit regression model | |
n_neighbors = 5 | |
for i, weights in enumerate(['uniform', 'distance']): | |
knn = neighbors.KNeighborsRegressor(n_neighbors, weights=weights) | |
y_ = knn.fit(X, y).predict(T) | |
plt.subplot(2, 1, i + 1) | |
plt.scatter(X, y, c='k', label='data') | |
plt.plot(T, y_, c='g', label='prediction') | |
plt.axis('tight') | |
plt.legend() | |
plt.title("KNeighborsRegressor (k = %i, weights = '%s')" % (n_neighbors, | |
weights)) | |
plt.show() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment