Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download

📚 The CoCalc Library - books, templates and other resources

132928 views
License: OTHER
1
import numpy as np
2
import matplotlib.pyplot as plt
3
4
from sklearn.neighbors import KNeighborsRegressor
5
from sklearn.metrics import euclidean_distances
6
7
from .datasets import make_wave
8
from .plot_helpers import cm3
9
10
11
def plot_knn_regression(n_neighbors=1):
12
X, y = make_wave(n_samples=40)
13
X_test = np.array([[-1.5], [0.9], [1.5]])
14
15
dist = euclidean_distances(X, X_test)
16
closest = np.argsort(dist, axis=0)
17
18
plt.figure(figsize=(10, 6))
19
20
reg = KNeighborsRegressor(n_neighbors=n_neighbors).fit(X, y)
21
y_pred = reg.predict(X_test)
22
23
for x, y_, neighbors in zip(X_test, y_pred, closest.T):
24
for neighbor in neighbors[:n_neighbors]:
25
plt.arrow(x[0], y_, X[neighbor, 0] - x[0], y[neighbor] - y_,
26
head_width=0, fc='k', ec='k')
27
28
train, = plt.plot(X, y, 'o', c=cm3(0))
29
test, = plt.plot(X_test, -3 * np.ones(len(X_test)), '*', c=cm3(2),
30
markersize=20)
31
pred, = plt.plot(X_test, y_pred, '*', c=cm3(0), markersize=20)
32
plt.vlines(X_test, -3.1, 3.1, linestyle="--")
33
plt.legend([train, test, pred],
34
["training data/target", "test data", "test prediction"],
35
ncol=3, loc=(.1, 1.025))
36
plt.ylim(-3.1, 3.1)
37
plt.xlabel("Feature")
38
plt.ylabel("Target")
39
40