import matplotlib.pyplot as plt
import numpy as np
import seaborn
seaborn.set(style='whitegrid',rc={'figure.figsize':(9,5)})
(a) Fit the data with a polynomial with 5, 10, and 15 terms, using a pseudo-inverse of the Vandermonde matrix.
x_data = np.arange(-10,11)
y_data = np.zeros(len(x_data))
for i in range(len(x_data)):
if x_data[i]>0: y_data[i]=1
VSolvePlot(x_data,y_data,5)
VSolvePlot(x_data,y_data,10)
VSolvePlot(x_data,y_data,15)
def VSolvePlot(x_,y_,n_):
n_plot = 10000
x_plot = np.linspace(-10,10,n_plot)
y_plot = np.zeros(n_plot)
A = np.empty([len(x_),n_])
for i in range(len(x_)):
for j in range(n_):
A[i][j] = x_[i]**j
A_pseudo = np.linalg.pinv(A, rcond=1e-15,)
v_terms = np.dot(A_pseudo,y_)
for i in range(n_plot):
y_plot[i] = sum(v_terms[j]*(x_plot[i]**j) for j in range(n_))
print(n_,"terms")
fig,ax = plt.subplots()
plt.ylim(-0.2,1.2)
plt.plot(x_plot,y_plot,'black',lw=1)
ax = plt.scatter(x_,y_,40,'blue')
plt.show()
(b)
RBFSolve(x_data,y_data,5)
RBFSolve(x_data,y_data,10)
RBFSolve(x_data,y_data,15)
def RBFFunc(x, a, c):
n_ = len(a)
y = sum(a[j]*abs(x-c[j])**3 for j in range(n_))
return y
def RBFSolve(x_,y_,n_):
c = np.linspace(-10,10,n_,endpoint=False)
n_plot = 10000
x_plot = np.linspace(-10,10,n_plot)
y_plot = np.zeros(n_plot)
A = np.empty([len(x_),n_])
for i in range(len(x_)):
for j in range(n_):
A[i][j] = abs(x_[i]-c[j])**3
A_pseudo = np.linalg.pinv(A, rcond=1e-17,)
v_coef = np.dot(A_pseudo,y_)
for i in range(n_plot):
y_plot[i] = RBFFunc(x_plot[i], v_coef, c)
print(n_,"terms")
fig,ax = plt.subplots()
plt.ylim(-0.2,1.2)
plt.plot(x_plot,y_plot,'black',lw=1)
ax = plt.scatter(x_,y_,40,'blue')
plt.show()
return v_coef, c
(c)
x_outofsamp = np.arange(-10.5,10.5)
RBFError(x_outofsamp,5)
RBFError(x_outofsamp,10)
RBFError(x_outofsamp,15)
def RBFError(x_,n_):
v_coef, c = RBFSolve(x_data,y_data,n_)
y_fit = np.empty(len(x_))
for i in range(len(x_)):
y_fit[i] = RBFFunc(x_[i], v_coef, c)
y_exact = BaseFunc(x_)
error = np.sqrt(sum((y_fit[i]-y_exact[i])**2 for i in range(len(x_)))/len(x_))
print("error =", error)
def BaseFunc(x_):
y_ = np.zeros(len(x_))
for i in range(len(x_)):
if x_[i]>0: y_[i]=1
return y_