In [1]:
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
from GPs.Kernel import Kernel, SqExp, RQ, ExpSine, WhiteNoise
from GPs.GP import GPR
%matplotlib inline
In [2]:
x = np.random.RandomState(0).uniform(-5, 5, 20)
#x = np.random.uniform(-5, 5, 20)
y = x*np.sin(x)
#y += np.random.normal(0,0.5,y.size)
y += np.random.RandomState(34).normal(0,0.5,y.size)
In [3]:
x_star = np.linspace(-5,5,500)
In [4]:
#Define the basic kernels
k1 = SqExp(0.45,2)
k2 = RQ(0.5,2,3)
k3 = ExpSine(0.1,2,30)
k4 = WhiteNoise(0.01)
#Define the combined kernel
k1 = k1+k4
In [5]:
#Instantiate the GP predictor object with the desired kernel
gp = GPR(k1)
#Train the model
gp.train(x,y)
In [6]:
#Predict a new set of test data given the independent variable observations
y_mean1,y_var1 = gp.predict(x_star,False)
#Convert the variance to the standard deviation
y_err1 = np.sqrt(y_var1)
In [7]:
plt.scatter(x,y,s=30)
plt.plot(x_star,x_star*np.sin(x_star),'r:')
plt.plot(x_star,y_mean1,'k-')
plt.fill_between(x_star,y_mean1+y_err1,y_mean1-y_err1,alpha=0.5)
Out[7]:
In [8]:
gp.optimize('SLSQP')
Out[8]:
array([ 1.47895967, 3.99711988, 0.16295754])
array([ 1.80397587, 4.86011667, 0.18058626])
In [9]:
#Predict a new set of test data given the independent variable observations
y_mean2,y_var2 = gp.predict(x_star,False)
#Convert the variance to the standard deviation
y_err2 = np.sqrt(y_var2)
In [10]:
plt.scatter(x,y,s=30)
plt.plot(x_star,x_star*np.sin(x_star),'r:')
plt.plot(x_star,y_mean2,'k-')
plt.fill_between(x_star,y_mean2+y_err2,y_mean2-y_err2,alpha=0.5)
Out[10]: