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
6
7
def plot_kneighbors_regularization():
8
rnd = np.random.RandomState(42)
9
x = np.linspace(-3, 3, 100)
10
y_no_noise = np.sin(4 * x) + x
11
y = y_no_noise + rnd.normal(size=len(x))
12
X = x[:, np.newaxis]
13
fig, axes = plt.subplots(1, 3, figsize=(15, 5))
14
15
x_test = np.linspace(-3, 3, 1000)
16
17
for n_neighbors, ax in zip([2, 5, 20], axes.ravel()):
18
kneighbor_regression = KNeighborsRegressor(n_neighbors=n_neighbors)
19
kneighbor_regression.fit(X, y)
20
ax.plot(x, y_no_noise, label="true function")
21
ax.plot(x, y, "o", label="data")
22
ax.plot(x_test, kneighbor_regression.predict(x_test[:, np.newaxis]),
23
label="prediction")
24
ax.legend()
25
ax.set_title("n_neighbors = %d" % n_neighbors)
26
27
28
if __name__ == "__main__":
29
plot_kneighbors_regularization()
30
plt.show()
31
32