4

I am using the GPy library in Python 2.7 to perform Gaussian Process regressions. I started by following the tutorial notebooks provided in the GitHub page.

Sample code :

import numpy as np
import matplotlib.pyplot as plt

f = lambda x : np.sin(x**2)

kernel = GPy.kern.RBF(input_dim=1, variance=1., lengthscale=1.)

X=np.random.rand(2,1)
Y=f(X)

m = GPy.models.GPRegression(X,Y,kernel)
m.optimize_restarts(num_restarts = 10,verbose=False)

fig=m.plot()
plt.show()

The weird thing I witnessed is that there is no plot function implemented in the GPRegression class (ok, it's just a small sub-class of GP.), nor in its super-class (GP), nor in its super-super-class (Model)... all located in GPy.core.

The plot function that is executed when I call m.plot() is in GPy.plotting.gpy_plot (which does not contain any class, but still uses the "self" keyword as function argument - but maybe it's just a "bad" name for a function argument ?).

I cannot see how a GPy.core.GP object can access this plot function (at first sight, there is no link whatsoever between the two python files - Ctrl+F "plot" in GPy/core/gp.py gives nothing for example).

When I call

vars(GPy.models.gp_regression.GP).keys()

, the plot function is indeed there, although not directly implemented in GPy.core.GP.

Same thing for : (Minimal reproducible example)

import GPy.core.gp
import GPy.likelihoods
import GPy.kern
import matplotlib.pyplot as plt

GPy.core.gp.GP.__dict__.keys()

Any idea of how GP calls the plot function in gpy_plot, and why it is coded this way ?

gehbiszumeis
  • 3,525
  • 4
  • 24
  • 41
saleml
  • 105
  • 7

1 Answers1

2

The plotting library gets "injected" in GPy/GPy/plotting/__init__.py's inject_plotting(). Here the line for plot():

    from ..core import GP
    ...
    GP.plot = gpy_plot.gp_plots.plot

I assume the reason for this design was that it allows easily changing the plotting library on-the-fly via change_plotting_library().

Ulrich Stern
  • 10,761
  • 5
  • 55
  • 76
  • Thanks for your answer. Just to get things clear : 1. In this \__init__ file, the GP.plot function is created, meaning that all instances of the GP class _will (as soon as this line of code is executed)_ have this plot object method. Am I right ? 2. When does this code get executed ? Once I initialize a GP object, say **m**, how come the \__init__.py file of another folder gets executed ? Thank you – saleml Jul 18 '16 at 08:26
  • The assignment to `GP.plot` modifies the [_class object_](https://docs.python.org/2/tutorial/classes.html#class-objects), so instances can access `plot()`. (This works even if the class object is modified _after_ the instance is created.) The \_\_init__.py gets executed on `import`. E.g., `import GPy.core.gp` executes GPy/\_\_init__.py and GPy/core/\_\_init__.py. And the former has `from . import plotting`. – Ulrich Stern Jul 18 '16 at 18:12