Last active
July 5, 2022 20:59
-
-
Save rikrd/05f5ca0c31adb9203823 to your computer and use it in GitHub Desktop.
GPy Kernel Cheatsheet:: All the kernels in GPy (example realizations, covariance matrix, kernel equation)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
%pylab inline | |
import numpy as np | |
import pylab as plt | |
import GPy | |
import re | |
def get_equation(kern): | |
match = re.search(r'(math::)(\r\n|\r|\n)*(?P<equation>.*)(\r\n|\r|\n)*', kern.__doc__) | |
return '' if match is None else match.group('equation').strip() | |
for kernel_name in dir(GPy.kern): | |
Kernel = getattr(GPy.kern, kernel_name) | |
if Kernel.__class__ == GPy.kern.Exponential.__class__ == GPy.kern._src.kernel_slice_operations.KernCallsViaSlicerMeta: | |
# Try plotting sample paths here | |
try: | |
k = Kernel(input_dim=1) | |
X = np.linspace(0.,1.,500) # define X to be 500 points evenly spaced over [0,1] | |
X = X[:,None] # reshape X to make it n*p --- we try to use 'design matrices' in GPy | |
mu = np.zeros((500))# vector of the means --- we could use a mean function here, but here it is just zero. | |
C = k.K(X,X) # compute the covariance matrix associated with inputs X | |
# Generate 20 separate samples paths from a Gaussian with mean mu and covariance C | |
Z = np.random.multivariate_normal(mu,C,20) | |
kernel_equation = get_equation(k) | |
#print kernel_equation | |
from IPython.display import Math, display | |
display(Math(kernel_equation)) | |
fig = plt.figure() # open a new plotting window | |
plt.subplot(121) | |
for i in range(3): | |
plt.plot(X[:],Z[i,:]) | |
plt.title('{} samples'.format(kernel_name)) | |
plt.subplot(122) | |
plt.imshow(C, interpolation='nearest') | |
plt.title('{} covariance'.format(kernel_name)) | |
except: | |
continue |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi rikrd,
very useful program- I had to make some changes to run in a jupyter notebook on my machine:
#%pylab inline
import numpy as np
%matplotlib inline
# https://stackoverflow.com/questions/19410042/how-to-make-ipython-notebook-matplotlib-plot-inline
#import pylab as plt
import GPy
import re
from IPython.display import Math, display #This will display the equation of the kernel in picture form
if Kernel.class == GPy.kern.Exponential.class == GPy.kern.src.kernel_slice_operations.KernCallsViaSlicerMeta:
(removed the ._src and replaced it with .src)
add in:
```
print "\n **",kernel_name
display(Math(kernel_equation))
plt.show()