2010-11-29 01:44:37 +08:00
|
|
|
"""
|
2011-09-12 01:45:34 +08:00
|
|
|
============================
|
|
|
|
|
Nearest Neighbors regression
|
|
|
|
|
============================
|
2010-11-29 01:44:37 +08:00
|
|
|
|
|
|
|
|
Demonstrate the resolution of a regression problem
|
|
|
|
|
using a k-Nearest Neighbor and the interpolation of the
|
2011-02-15 19:47:10 +08:00
|
|
|
target using both barycenter and constant weights.
|
2010-11-29 01:44:37 +08:00
|
|
|
|
|
|
|
|
"""
|
|
|
|
|
|
2011-02-15 19:47:10 +08:00
|
|
|
# Author: Alexandre Gramfort <alexandre.gramfort@inria.fr>
|
|
|
|
|
# Fabian Pedregosa <fabian.pedregosa@inria.fr>
|
|
|
|
|
#
|
2013-04-30 14:23:46 +08:00
|
|
|
# License: BSD 3 clause (C) INRIA
|
2011-02-15 19:47:10 +08:00
|
|
|
|
|
|
|
|
|
2022-02-09 22:09:14 +08:00
|
|
|
# %%
|
2010-11-29 01:44:37 +08:00
|
|
|
# Generate sample data
|
2022-02-09 22:09:14 +08:00
|
|
|
# --------------------
|
2010-11-29 01:44:37 +08:00
|
|
|
import numpy as np
|
2014-05-15 04:31:03 +08:00
|
|
|
import matplotlib.pyplot as plt
|
2011-09-02 17:00:02 +08:00
|
|
|
from sklearn import neighbors
|
2010-11-29 01:44:37 +08:00
|
|
|
|
|
|
|
|
np.random.seed(0)
|
2011-12-24 02:24:36 +08:00
|
|
|
X = np.sort(5 * np.random.rand(40, 1), axis=0)
|
2011-02-01 14:02:49 +08:00
|
|
|
T = np.linspace(0, 5, 500)[:, np.newaxis]
|
2010-11-29 01:44:37 +08:00
|
|
|
y = np.sin(X).ravel()
|
|
|
|
|
|
|
|
|
|
# Add noise to targets
|
2011-12-24 02:24:36 +08:00
|
|
|
y[::5] += 1 * (0.5 - np.random.rand(8))
|
2010-11-29 01:44:37 +08:00
|
|
|
|
2022-02-09 22:09:14 +08:00
|
|
|
# %%
|
2010-11-29 01:44:37 +08:00
|
|
|
# Fit regression model
|
2022-02-09 22:09:14 +08:00
|
|
|
# --------------------
|
2011-09-12 07:17:57 +08:00
|
|
|
n_neighbors = 5
|
|
|
|
|
|
2011-12-24 02:24:36 +08:00
|
|
|
for i, weights in enumerate(["uniform", "distance"]):
|
2011-09-12 07:17:57 +08:00
|
|
|
knn = neighbors.KNeighborsRegressor(n_neighbors, weights=weights)
|
|
|
|
|
y_ = knn.fit(X, y).predict(T)
|
|
|
|
|
|
2014-05-15 04:31:03 +08:00
|
|
|
plt.subplot(2, 1, i + 1)
|
2019-06-14 23:38:18 +08:00
|
|
|
plt.scatter(X, y, color="darkorange", label="data")
|
|
|
|
|
plt.plot(T, y_, color="navy", label="prediction")
|
2014-05-15 04:31:03 +08:00
|
|
|
plt.axis("tight")
|
|
|
|
|
plt.legend()
|
|
|
|
|
plt.title("KNeighborsRegressor (k = %i, weights = '%s')" % (n_neighbors, weights))
|
2010-11-29 01:44:37 +08:00
|
|
|
|
2017-11-17 16:13:15 +08:00
|
|
|
plt.tight_layout()
|
2014-05-15 04:31:03 +08:00
|
|
|
plt.show()
|