File size: 2,110 Bytes
c7961a7 dd0867a c7961a7 899658d c7961a7 baedbad c7961a7 942aa99 c7961a7 2cdc579 57cb2f9 c7961a7 942aa99 c7961a7 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
import numpy as np
import matplotlib.pyplot as plt
from sklearn import neighbors
import gradio as gr
def train_and_plot(weights, n_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))
knn = neighbors.KNeighborsRegressor(n_neighbors, weights=weights)
fit = knn.fit(X, y)
y_ = knn.predict(T)
score = knn.score(T, y_)
plt.figure()
plt.scatter(X, y, color="darkorange", label="data")
plt.plot(T, y_, color="navy", label="prediction")
plt.axis("tight")
plt.legend()
plt.title("KNeighborsRegressor (k = %i, weights = '%s')" % (n_neighbors, weights))
plt.tight_layout()
return plt, score
with gr.Blocks() as demo:
link = "https://scikit-learn.org/stable/auto_examples/neighbors/plot_regression.html#sphx-glr-auto-examples-neighbors-plot-regression-py"
gr.Markdown("## Nearest Neighbors Regression")
gr.Markdown(f"This demo is based on this [scikit-learn example]({link}).")
gr.HTML("<hr>")
gr.Markdown("In this demo, we learn a noise-infused sine function using k-Nearest Neighbor and observe how the function learned varies as we change the following hyperparameters:")
gr.Markdown("""1. Weight function
2. Number of neighbors""")
with gr.Row():
weights = gr.Radio(['uniform', "distance"], label="Weights", info="Choose the weight function")
n_neighbors = gr.Slider(label="Neighbors", info="Choose the number of neighbors", minimum =1, maximum=15, step=1)
with gr.Row():
with gr.Column(scale=2):
plot = gr.Plot(label="KNeighborsRegressor Plot")
with gr.Column(scale=1):
num = gr.Textbox(label="Test Accuracy")
weights.change(train_and_plot, inputs=[weights, n_neighbors], outputs=[plot, num])
n_neighbors.change(train_and_plot, inputs=[weights, n_neighbors], outputs=[plot, num])
if __name__ == "__main__":
demo.launch() |