|
| 1 | +import numpy as np |
| 2 | +from bokeh.plotting import figure, show, output_notebook |
| 3 | +from bokeh.layouts import gridplot |
| 4 | +from bokeh.io import push_notebook |
| 5 | + |
| 6 | +def local_regression(x0, X, Y, tau): |
| 7 | + x0 = np.r_[1, x0] # Add one to avoid the loss in information |
| 8 | + X = np.c_[np.ones(len(X)), X] |
| 9 | + xw = X.T * radial_kernel(x0, X, tau) |
| 10 | + beta = np.linalg.pinv(xw @ X) @ xw @ Y |
| 11 | + return x0 @ beta |
| 12 | + |
| 13 | +def radial_kernel(x0, X, tau): |
| 14 | + return np.exp(np.sum((X - x0) ** 2, axis=1) / (-2 * tau * tau)) |
| 15 | + |
| 16 | +n = 1000 |
| 17 | +X = np.linspace(-3, 3, num=n) |
| 18 | +print("The Data Set ( 10 Samples) X :\n",X[1:10]) |
| 19 | +Y = np.log(np.abs(X ** 2 - 1) + .5) |
| 20 | +print("The Fitting Curve Data Set (10 Samples) Y :\n",Y[1:10]) |
| 21 | +X += np.random.normal(scale=.1, size=n) |
| 22 | +print("Normalised (10 Samples) X :\n",X[1:10]) |
| 23 | + |
| 24 | +domain = np.linspace(-3, 3, num=300) |
| 25 | +print(" Xo Domain Space(10 Samples) :\n",domain[1:10]) |
| 26 | +def plot_lwr(tau): |
| 27 | + prediction = [local_regression(x0, X, Y, tau) for x0 in domain] |
| 28 | + plot = figure(plot_width=400, plot_height=400) |
| 29 | + plot.title.text='tau=%g' % tau |
| 30 | + plot.scatter(X, Y, alpha=.3) |
| 31 | + plot.line(domain, prediction, line_width=2, color='red') |
| 32 | + return plot |
| 33 | + |
| 34 | +show(gridplot([ |
| 35 | + [plot_lwr(10.), plot_lwr(1.)], |
| 36 | + [plot_lwr(0.1), plot_lwr(0.01)]])) |
0 commit comments