Creation
Browse files
app.py
ADDED
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
import gradio as gr
|
3 |
+
import matplotlib.pyplot as plt
|
4 |
+
|
5 |
+
# Define functions and classes
|
6 |
+
def true_fun(x):
|
7 |
+
return x ** 2 - np.cos(np.pi * x)
|
8 |
+
|
9 |
+
def euclid_dist(x, xk):
|
10 |
+
return np.sqrt((x.reshape(-1, 1) - xk.reshape(1, -1)) ** 2)
|
11 |
+
|
12 |
+
def rbf(radius, eps):
|
13 |
+
return np.exp(-(eps * radius) ** 2)
|
14 |
+
|
15 |
+
class RBFInt:
|
16 |
+
def __init__(self, eps):
|
17 |
+
self.eps = eps
|
18 |
+
|
19 |
+
def fit(self, x, y):
|
20 |
+
self.xk_ = x
|
21 |
+
transf = rbf(euclid_dist(x, x), self.eps)
|
22 |
+
self.w_ = np.linalg.solve(transf, y)
|
23 |
+
|
24 |
+
def __call__(self, xn):
|
25 |
+
transf = rbf(euclid_dist(xn, self.xk_), self.eps)
|
26 |
+
return transf.dot(self.w_)
|
27 |
+
|
28 |
+
def rbf_interpolation(eps, num_points):
|
29 |
+
# Generate random points
|
30 |
+
np.random.seed(42)
|
31 |
+
xk = np.linspace(0, 1, num_points)
|
32 |
+
yk = true_fun(xk) + np.random.randn(num_points) * 0.1
|
33 |
+
|
34 |
+
# Fit the RBF model
|
35 |
+
rbf_model = RBFInt(eps)
|
36 |
+
rbf_model.fit(xk, yk)
|
37 |
+
|
38 |
+
# Interpolate over a range of x values
|
39 |
+
x = np.linspace(0, 1, 100)
|
40 |
+
y_true = true_fun(x)
|
41 |
+
y_interp = rbf_model(x)
|
42 |
+
|
43 |
+
# Plot the results
|
44 |
+
fig, ax = plt.subplots()
|
45 |
+
ax.plot(x, y_true, label="True function")
|
46 |
+
ax.plot(x, y_interp, label="RBF Interpolation")
|
47 |
+
ax.scatter(xk, yk, color="red", label="Data points")
|
48 |
+
ax.legend()
|
49 |
+
plt.close(fig) # Close the figure to avoid display issues in some environments
|
50 |
+
return fig
|
51 |
+
|
52 |
+
# Gradio UI
|
53 |
+
iface = gr.Interface(
|
54 |
+
fn=rbf_interpolation,
|
55 |
+
inputs=[
|
56 |
+
gr.Slider(0.1, 10.0, step=0.1, label="Epsilon (eps)"),
|
57 |
+
gr.Slider(1, 20, step=1, label="Number of points")
|
58 |
+
],
|
59 |
+
outputs=gr.Plot(label="RBF Interpolation"),
|
60 |
+
live=True
|
61 |
+
)
|
62 |
+
|
63 |
+
iface.launch()
|