[testing] more restructuring, almost ready to ship, added some tests for testing with travis

This commit is contained in:
mzwiessele 2015-10-04 16:10:35 +01:00
parent 831e032ade
commit fa8f73326e
65 changed files with 628 additions and 1046 deletions

View file

@ -1,109 +0,0 @@
# Copyright (c) 2012, GPy authors (see AUTHORS.txt).
# Licensed under the BSD 3-clause license (see LICENSE.txt)
import sys
colorsHex = {\
"Aluminium6":"#2e3436",\
"Aluminium5":"#555753",\
"Aluminium4":"#888a85",\
"Aluminium3":"#babdb6",\
"Aluminium2":"#d3d7cf",\
"Aluminium1":"#eeeeec",\
"lightPurple":"#ad7fa8",\
"mediumPurple":"#75507b",\
"darkPurple":"#5c3566",\
"lightBlue":"#729fcf",\
"mediumBlue":"#3465a4",\
"darkBlue": "#204a87",\
"lightGreen":"#8ae234",\
"mediumGreen":"#73d216",\
"darkGreen":"#4e9a06",\
"lightChocolate":"#e9b96e",\
"mediumChocolate":"#c17d11",\
"darkChocolate":"#8f5902",\
"lightRed":"#ef2929",\
"mediumRed":"#cc0000",\
"darkRed":"#a40000",\
"lightOrange":"#fcaf3e",\
"mediumOrange":"#f57900",\
"darkOrange":"#ce5c00",\
"lightButter":"#fce94f",\
"mediumButter":"#edd400",\
"darkButter":"#c4a000"}
darkList = [colorsHex['darkBlue'],colorsHex['darkRed'],colorsHex['darkGreen'], colorsHex['darkOrange'], colorsHex['darkButter'], colorsHex['darkPurple'], colorsHex['darkChocolate'], colorsHex['Aluminium6']]
mediumList = [colorsHex['mediumBlue'], colorsHex['mediumRed'],colorsHex['mediumGreen'], colorsHex['mediumOrange'], colorsHex['mediumButter'], colorsHex['mediumPurple'], colorsHex['mediumChocolate'], colorsHex['Aluminium5']]
lightList = [colorsHex['lightBlue'], colorsHex['lightRed'],colorsHex['lightGreen'], colorsHex['lightOrange'], colorsHex['lightButter'], colorsHex['lightPurple'], colorsHex['lightChocolate'], colorsHex['Aluminium4']]
def currentDark():
return darkList[-1]
def currentMedium():
return mediumList[-1]
def currentLight():
return lightList[-1]
def nextDark():
darkList.append(darkList.pop(0))
return darkList[-1]
def nextMedium():
mediumList.append(mediumList.pop(0))
return mediumList[-1]
def nextLight():
lightList.append(lightList.pop(0))
return lightList[-1]
def reset():
while not darkList[0]==colorsHex['darkBlue']:
darkList.append(darkList.pop(0))
while not mediumList[0]==colorsHex['mediumBlue']:
mediumList.append(mediumList.pop(0))
while not lightList[0]==colorsHex['lightBlue']:
lightList.append(lightList.pop(0))
def hex2rgb(hexcolor):
hexcolor = [hexcolor[1+2*i:1+2*(i+1)] for i in range(3)]
r,g,b = [int(n,16) for n in hexcolor]
return (r,g,b)
colorsRGB = dict([(k,hex2rgb(i)) for k,i in colorsHex.items()])
cdict_RB = {'red' :((0.,colorsRGB['mediumRed'][0]/256.,colorsRGB['mediumRed'][0]/256.),
(.5,colorsRGB['mediumPurple'][0]/256.,colorsRGB['mediumPurple'][0]/256.),
(1.,colorsRGB['mediumBlue'][0]/256.,colorsRGB['mediumBlue'][0]/256.)),
'green':((0.,colorsRGB['mediumRed'][1]/256.,colorsRGB['mediumRed'][1]/256.),
(.5,colorsRGB['mediumPurple'][1]/256.,colorsRGB['mediumPurple'][1]/256.),
(1.,colorsRGB['mediumBlue'][1]/256.,colorsRGB['mediumBlue'][1]/256.)),
'blue':((0.,colorsRGB['mediumRed'][2]/256.,colorsRGB['mediumRed'][2]/256.),
(.5,colorsRGB['mediumPurple'][2]/256.,colorsRGB['mediumPurple'][2]/256.),
(1.,colorsRGB['mediumBlue'][2]/256.,colorsRGB['mediumBlue'][2]/256.))}
cdict_BGR = {'red' :((0.,colorsRGB['mediumBlue'][0]/256.,colorsRGB['mediumBlue'][0]/256.),
(.5,colorsRGB['mediumGreen'][0]/256.,colorsRGB['mediumGreen'][0]/256.),
(1.,colorsRGB['mediumRed'][0]/256.,colorsRGB['mediumRed'][0]/256.)),
'green':((0.,colorsRGB['mediumBlue'][1]/256.,colorsRGB['mediumBlue'][1]/256.),
(.5,colorsRGB['mediumGreen'][1]/256.,colorsRGB['mediumGreen'][1]/256.),
(1.,colorsRGB['mediumRed'][1]/256.,colorsRGB['mediumRed'][1]/256.)),
'blue':((0.,colorsRGB['mediumBlue'][2]/256.,colorsRGB['mediumBlue'][2]/256.),
(.5,colorsRGB['mediumGreen'][2]/256.,colorsRGB['mediumGreen'][2]/256.),
(1.,colorsRGB['mediumRed'][2]/256.,colorsRGB['mediumRed'][2]/256.))}
cdict_Alu = {'red' :((0./5,colorsRGB['Aluminium1'][0]/256.,colorsRGB['Aluminium1'][0]/256.),
(1./5,colorsRGB['Aluminium2'][0]/256.,colorsRGB['Aluminium2'][0]/256.),
(2./5,colorsRGB['Aluminium3'][0]/256.,colorsRGB['Aluminium3'][0]/256.),
(3./5,colorsRGB['Aluminium4'][0]/256.,colorsRGB['Aluminium4'][0]/256.),
(4./5,colorsRGB['Aluminium5'][0]/256.,colorsRGB['Aluminium5'][0]/256.),
(5./5,colorsRGB['Aluminium6'][0]/256.,colorsRGB['Aluminium6'][0]/256.)),
'green' :((0./5,colorsRGB['Aluminium1'][1]/256.,colorsRGB['Aluminium1'][1]/256.),
(1./5,colorsRGB['Aluminium2'][1]/256.,colorsRGB['Aluminium2'][1]/256.),
(2./5,colorsRGB['Aluminium3'][1]/256.,colorsRGB['Aluminium3'][1]/256.),
(3./5,colorsRGB['Aluminium4'][1]/256.,colorsRGB['Aluminium4'][1]/256.),
(4./5,colorsRGB['Aluminium5'][1]/256.,colorsRGB['Aluminium5'][1]/256.),
(5./5,colorsRGB['Aluminium6'][1]/256.,colorsRGB['Aluminium6'][1]/256.)),
'blue' :((0./5,colorsRGB['Aluminium1'][2]/256.,colorsRGB['Aluminium1'][2]/256.),
(1./5,colorsRGB['Aluminium2'][2]/256.,colorsRGB['Aluminium2'][2]/256.),
(2./5,colorsRGB['Aluminium3'][2]/256.,colorsRGB['Aluminium3'][2]/256.),
(3./5,colorsRGB['Aluminium4'][2]/256.,colorsRGB['Aluminium4'][2]/256.),
(4./5,colorsRGB['Aluminium5'][2]/256.,colorsRGB['Aluminium5'][2]/256.),
(5./5,colorsRGB['Aluminium6'][2]/256.,colorsRGB['Aluminium6'][2]/256.))}

View file

@ -32,48 +32,9 @@ from . import pl
from .plot_util import get_x_y_var, get_free_dims, get_which_data_ycols,\
get_which_data_rows, update_not_existing_kwargs, helper_predict_with_model
def _plot_data(self, canvas, which_data_rows='all',
which_data_ycols='all', visible_dims=None,
error_kwargs=None, **plot_kwargs):
if error_kwargs is None:
error_kwargs = {}
ycols = get_which_data_ycols(self, which_data_ycols)
rows = get_which_data_rows(self, which_data_rows)
X, X_variance, Y = get_x_y_var(self)
free_dims = get_free_dims(self, visible_dims, None)
plots = {}
plots['dataplot'] = []
if X_variance is not None: plots['xerrorplot'] = []
#one dimensional plotting
if len(free_dims) == 1:
for d in ycols:
update_not_existing_kwargs(plot_kwargs, pl.defaults.data_1d) # @UndefinedVariable
plots['dataplot'].append(pl.scatter(canvas, X[rows, free_dims], Y[rows, d], **plot_kwargs))
if X_variance is not None:
update_not_existing_kwargs(error_kwargs, pl.defaults.xerrorbar)
plots['xerrorplot'].append(pl.xerrorbar(canvas, X[rows, free_dims].flatten(), Y[rows, d].flatten(),
2 * np.sqrt(X_variance[rows, free_dims].flatten()),
**error_kwargs))
#2D plotting
elif len(free_dims) == 2:
for d in ycols:
update_not_existing_kwargs(plot_kwargs, pl.defaults.data_2d) # @UndefinedVariable
plots['dataplot'].append(pl.scatter(canvas, X[rows, free_dims[0]], X[rows, free_dims[1]],
c=Y[rows, d], vmin=Y.min(), vmax=Y.max(), **plot_kwargs))
elif len(free_dims) == 0:
pass #Nothing to plot!
else:
raise NotImplementedError("Cannot plot in more then two dimensions")
return plots
def plot_data(self, which_data_rows='all',
which_data_ycols='all', visible_dims=None,
error_kwargs=None, **plot_kwargs):
projection='2d', label=None, **plot_kwargs):
"""
Plot the training data
- For higher dimensions than two, use fixed_inputs to plot the data points with some of the inputs fixed.
@ -87,28 +48,128 @@ def plot_data(self, which_data_rows='all',
:type which_data_ycols: 'all' or a list of integers
:param visible_dims: an array specifying the input dimensions to plot (maximum two)
:type visible_dims: a numpy array
:param dict error_kwargs: kwargs for the error plot for the plotting library you are using
:param {'2d','3d'} projection: whether to plot in 2d or 3d. This only applies when plotting two dimensional inputs!
:param str label: the label for the plot
:param kwargs plot_kwargs: kwargs for the data plot for the plotting library you are using
:returns list: of plots created.
"""
canvas, kwargs = pl.get_new_canvas(plot_kwargs)
plots = _plot_data(self, canvas, which_data_rows, which_data_ycols, visible_dims, error_kwargs, **kwargs)
return pl.show_canvas(canvas, plots, xlabel='x', ylabel='y', legend='dataplot')
canvas, plot_kwargs = pl.get_new_canvas(projection=projection, **plot_kwargs)
plots = _plot_data(self, canvas, which_data_rows, which_data_ycols, visible_dims, projection, label, **plot_kwargs)
return pl.show_canvas(canvas, plots)
def _plot_data(self, canvas, which_data_rows='all',
which_data_ycols='all', visible_dims=None,
projection='2d', label=None, **plot_kwargs):
ycols = get_which_data_ycols(self, which_data_ycols)
rows = get_which_data_rows(self, which_data_rows)
def plot_inducing(self, visible_dims=None, **plot_kwargs):
X, _, Y = get_x_y_var(self)
free_dims = get_free_dims(self, visible_dims, None)
plots = {}
plots['dataplot'] = []
#one dimensional plotting
if len(free_dims) == 1:
for d in ycols:
update_not_existing_kwargs(plot_kwargs, pl.defaults.data_1d) # @UndefinedVariable
plots['dataplot'].append(pl.scatter(canvas, X[rows, free_dims], Y[rows, d], label=label, **plot_kwargs))
#2D plotting
elif len(free_dims) == 2:
if projection=='2d':
for d in ycols:
update_not_existing_kwargs(plot_kwargs, pl.defaults.data_2d) # @UndefinedVariable
plots['dataplot'].append(pl.scatter(canvas, X[rows, free_dims[0]], X[rows, free_dims[1]],
color=Y[rows, d], vmin=Y.min(), vmax=Y.max(), label=label, **plot_kwargs))
else:
for d in ycols:
update_not_existing_kwargs(plot_kwargs, pl.defaults.data_2d) # @UndefinedVariable
plots['dataplot'].append(pl.scatter(canvas, X[rows, free_dims[0]], X[rows, free_dims[1]],
Z=Y[rows, d], vmin=Y.min(), color=Y[rows, d], vmax=Y.max(), label=label, **plot_kwargs))
elif len(free_dims) == 0:
pass #Nothing to plot!
else:
raise NotImplementedError("Cannot plot in more then two dimensions")
return plots
def plot_data_error(self, which_data_rows='all',
which_data_ycols='all', visible_dims=None,
projection='2d', label=None, **error_kwargs):
"""
Plot the training data input error.
For higher dimensions than two, use fixed_inputs to plot the data points with some of the inputs fixed.
Can plot only part of the data
using which_data_rows and which_data_ycols.
:param which_data_rows: which of the training data to plot (default all)
:type which_data_rows: 'all' or a slice object to slice self.X, self.Y
:param which_data_ycols: when the data has several columns (independant outputs), only plot these
:type which_data_ycols: 'all' or a list of integers
:param visible_dims: an array specifying the input dimensions to plot (maximum two)
:type visible_dims: a numpy array
:param {'2d','3d'} projection: whether to plot in 2d or 3d. This only applies when plotting two dimensional inputs!
:param dict error_kwargs: kwargs for the error plot for the plotting library you are using
:param str label: the label for the plot
:param kwargs plot_kwargs: kwargs for the data plot for the plotting library you are using
:returns list: of plots created.
"""
canvas, error_kwargs = pl.get_new_canvas(projection=='3d', **error_kwargs)
plots = _plot_data_error(self, canvas, which_data_rows, which_data_ycols, visible_dims, projection, label, **error_kwargs)
return pl.show_canvas(canvas, plots)
def _plot_data_error(self, canvas, which_data_rows='all',
which_data_ycols='all', visible_dims=None,
projection='2d', **error_kwargs):
ycols = get_which_data_ycols(self, which_data_ycols)
rows = get_which_data_rows(self, which_data_rows)
X, X_variance, Y = get_x_y_var(self)
free_dims = get_free_dims(self, visible_dims, None)
plots = {}
if X_variance is not None:
plots['xerrorplot'] = []
#one dimensional plotting
if len(free_dims) == 1:
for d in ycols:
update_not_existing_kwargs(error_kwargs, pl.defaults.xerrorbar)
plots['xerrorplot'].append(pl.xerrorbar(canvas, X[rows, free_dims].flatten(), Y[rows, d].flatten(),
2 * np.sqrt(X_variance[rows, free_dims].flatten()),
**error_kwargs))
#2D plotting
elif len(free_dims) == 2:
update_not_existing_kwargs(error_kwargs, pl.defaults.xerrorbar) # @UndefinedVariable
for d in ycols:
plots['xerrorplot'].append(pl.xerrorbar(canvas, X[rows, free_dims[0]].flatten(), Y[rows, d].flatten(),
2 * np.sqrt(X_variance[rows, free_dims[0]].flatten()),
**error_kwargs))
plots['yerrorplot'].append(pl.xerrorbar(canvas, X[rows, free_dims[1]].flatten(), Y[rows, d].flatten(),
2 * np.sqrt(X_variance[rows, free_dims[1]].flatten()),
**error_kwargs))
elif len(free_dims) == 0:
pass #Nothing to plot!
else:
raise NotImplementedError("Cannot plot in more then two dimensions")
return plots
def plot_inducing(self, visible_dims=None, projection='2d', label=None, **plot_kwargs):
"""
Plot the inducing inputs of a sparse gp model
:param array-like visible_dims: an array specifying the input dimensions to plot (maximum two)
:param kwargs plot_kwargs: keyword arguments for the plotting library
"""
canvas, kwargs = pl.get_new_canvas(plot_kwargs)
plots = _plot_inducing(self, canvas, visible_dims, **kwargs)
canvas, kwargs = pl.get_new_canvas(projection=projection, **plot_kwargs)
plots = _plot_inducing(self, canvas, visible_dims, projection, label, **kwargs)
return pl.show_canvas(canvas, plots)
def _plot_inducing(self, canvas, visible_dims, **plot_kwargs):
def _plot_inducing(self, canvas, visible_dims, projection, label, **plot_kwargs):
free_dims = get_free_dims(self, visible_dims, None)
Z = self.Z[:, free_dims]
@ -119,6 +180,9 @@ def _plot_inducing(self, canvas, visible_dims, **plot_kwargs):
update_not_existing_kwargs(plot_kwargs, pl.defaults.inducing_1d) # @UndefinedVariable
plots['inducing'] = pl.plot_axis_lines(canvas, Z[:, free_dims], **plot_kwargs)
#2D plotting
elif len(free_dims) == 2 and projection == '3d':
update_not_existing_kwargs(plot_kwargs, pl.defaults.inducing_3d) # @UndefinedVariable
plots['inducing'] = pl.plot_axis_lines(canvas, Z[:, free_dims], **plot_kwargs)
elif len(free_dims) == 2:
update_not_existing_kwargs(plot_kwargs, pl.defaults.inducing_2d) # @UndefinedVariable
plots['inducing'] = pl.scatter(canvas, Z[:, free_dims[0]], Z[:, free_dims[1]],
@ -131,7 +195,7 @@ def _plot_inducing(self, canvas, visible_dims, **plot_kwargs):
def plot_errorbars_trainset(self, which_data_rows='all',
which_data_ycols='all', fixed_inputs=None,
plot_raw=False, apply_link=False,
plot_raw=False, apply_link=False, label=None, projection='2d',
predict_kw=None, **plot_kwargs):
"""
Plot the errorbars of the GP likelihood on the training data.
@ -150,16 +214,16 @@ def plot_errorbars_trainset(self, which_data_rows='all',
:param dict predict_kwargs: kwargs for the prediction used to predict the right quantiles.
:param kwargs plot_kwargs: kwargs for the data plot for the plotting library you are using
"""
canvas, kwargs = pl.get_new_canvas(plot_kwargs)
canvas, kwargs = pl.get_new_canvas(projection=projection, **plot_kwargs)
plots = _plot_errorbars_trainset(self, canvas, which_data_rows, which_data_ycols,
fixed_inputs, plot_raw, apply_link, predict_kw, **kwargs)
fixed_inputs, plot_raw, apply_link, label, projection, predict_kw, **kwargs)
return pl.show_canvas(canvas, plots)
def _plot_errorbars_trainset(self, canvas,
which_data_rows='all', which_data_ycols='all',
fixed_inputs=None,
plot_raw=False, apply_link=False,
predict_kw=None, **plot_kwargs):
label=None, projection='2d', predict_kw=None, **plot_kwargs):
ycols = get_which_data_ycols(self, which_data_ycols)
rows = get_which_data_rows(self, which_data_rows)
@ -176,9 +240,9 @@ def _plot_errorbars_trainset(self, canvas,
plots = []
if len(free_dims)<2:
if len(free_dims)<=2:
update_not_existing_kwargs(plot_kwargs, pl.defaults.yerrorbar)
if len(free_dims)==1:
update_not_existing_kwargs(plot_kwargs, pl.defaults.yerrorbar)
if predict_kw is None:
predict_kw = {}
if 'Y_metadata' not in predict_kw:
@ -189,8 +253,14 @@ def _plot_errorbars_trainset(self, canvas,
for d in ycols:
plots.append(pl.yerrorbar(canvas, X[rows,free_dims[0]], Y[rows,d],
np.vstack([Y[rows,d]-percs[0][rows,d], percs[1][rows,d]-Y[rows,d]]),
label=label,
**plot_kwargs))
else:
elif len(free_dims) == 2:
plots.append(pl.yerrorbar(canvas, X[rows,free_dims[0]], X[rows,free_dims[1]],
np.vstack([Y[rows,d]-percs[0][rows,d], percs[1][rows,d]-Y[rows,d]]),
Y[rows,d],
label=label,
**plot_kwargs))
pass #Nothing to plot!
else:
raise NotImplementedError("Cannot plot in more then one dimension.")

View file

@ -33,13 +33,14 @@ import numpy as np
from . import pl
from .plot_util import helper_for_plot_data, update_not_existing_kwargs, \
helper_predict_with_model, get_which_data_ycols
from .data_plots import _plot_data, _plot_inducing
from .data_plots import _plot_data, _plot_inducing, _plot_data_error
def plot_mean(self, plot_limits=None, fixed_inputs=None,
resolution=None, plot_raw=False,
apply_link=False, visible_dims=None,
which_data_ycols='all',
levels=20,
levels=20, projection='2d',
label=None,
predict_kw=None,
**kwargs):
"""
@ -56,22 +57,25 @@ def plot_mean(self, plot_limits=None, fixed_inputs=None,
:param bool plot_raw: plot the latent function (usually denoted f) only?
:param bool apply_link: whether to apply the link function of the GP to the raw prediction.
:param array-like which_data_ycols: which columns of y to plot (array-like or list of ints)
:param dict predict_kw: the keyword arguments for the prediction. If you want to plot a specific kernel give dict(kern=<specific kernel>) in here
:param int levels: for 2D plotting, the number of contour levels to use is
:param {'2d','3d'} projection: whether to plot in 2d or 3d. This only applies when plotting two dimensional inputs!
:param str label: the label for the plot.
:param dict predict_kw: the keyword arguments for the prediction. If you want to plot a specific kernel give dict(kern=<specific kernel>) in here
"""
canvas, kwargs = pl.get_new_canvas(kwargs)
canvas, kwargs = pl.get_new_canvas(projection=projection, **kwargs)
plots = _plot_mean(self, canvas, plot_limits, fixed_inputs,
resolution, plot_raw,
apply_link, visible_dims, which_data_ycols, levels,
predict_kw, **kwargs)
apply_link, visible_dims, which_data_ycols,
levels, projection, label, predict_kw, **kwargs)
return pl.show_canvas(canvas, plots)
def _plot_mean(self, canvas, plot_limits=None, fixed_inputs=None,
resolution=None, plot_raw=False,
apply_link=False, visible_dims=None,
which_data_ycols=None,
levels=20,
predict_kw=None, **kwargs):
which_data_ycols='all',
levels=20, projection='2d', label=None,
predict_kw=None,
**kwargs):
_, _, _, _, free_dims, Xgrid, x, y, _, _, resolution = helper_for_plot_data(self, plot_limits, visible_dims, fixed_inputs, resolution)
if len(free_dims)<=2:
@ -82,17 +86,25 @@ def _plot_mean(self, canvas, plot_limits=None, fixed_inputs=None,
if len(free_dims)==1:
# 1D plotting:
update_not_existing_kwargs(kwargs, pl.defaults.meanplot_1d) # @UndefinedVariable
return dict(gpmean=[pl.plot(canvas, Xgrid[:, free_dims], mu, **kwargs)])
plots = dict(gpmean=[pl.plot(canvas, Xgrid[:, free_dims], mu, label=label, **kwargs)])
else:
update_not_existing_kwargs(kwargs, pl.defaults.meanplot_2d) # @UndefinedVariable
return dict(gpmean=[pl.contour(canvas, x, y,
mu.reshape(resolution, resolution),
levels=levels, **kwargs)])
if projection == '2d':
update_not_existing_kwargs(kwargs, pl.defaults.meanplot_2d) # @UndefinedVariable
plots = dict(gpmean=[pl.contour(canvas, x, y,
mu.reshape(resolution, resolution),
levels=levels, label=label, **kwargs)])
elif projection == '3d':
update_not_existing_kwargs(kwargs, pl.defaults.meanplot_3d) # @UndefinedVariable
plots = dict(gpmean=[pl.surface(canvas, x, y,
mu.reshape(resolution, resolution),
label=label,
**kwargs)])
elif len(free_dims)==0:
pass # Nothing to plot!
else:
raise RuntimeError('Cannot plot mean in more then 2 input dimensions')
return plots
def plot_confidence(self, lower=2.5, upper=97.5, plot_limits=None, fixed_inputs=None,
resolution=None, plot_raw=False,
apply_link=False, visible_dims=None,
@ -119,7 +131,7 @@ def plot_confidence(self, lower=2.5, upper=97.5, plot_limits=None, fixed_inputs=
:param array-like which_data_ycols: which columns of the output y (!) to plot (array-like or list of ints)
:param dict predict_kw: the keyword arguments for the prediction. If you want to plot a specific kernel give dict(kern=<specific kernel>) in here
"""
canvas, kwargs = pl.get_new_canvas(kwargs)
canvas, kwargs = pl.get_new_canvas(**kwargs)
plots = _plot_confidence(self, canvas, lower, upper, plot_limits,
fixed_inputs, resolution, plot_raw,
apply_link, visible_dims, which_data_ycols,
@ -158,7 +170,7 @@ def plot_samples(self, plot_limits=None, fixed_inputs=None,
resolution=None, plot_raw=True,
apply_link=False, visible_dims=None,
which_data_ycols='all',
samples=3, predict_kw=None,
samples=3, projection='2d', predict_kw=None,
**kwargs):
"""
Plot the mean of the GP.
@ -178,29 +190,37 @@ def plot_samples(self, plot_limits=None, fixed_inputs=None,
:param dict predict_kw: the keyword arguments for the prediction. If you want to plot a specific kernel give dict(kern=<specific kernel>) in here
:param int levels: for 2D plotting, the number of contour levels to use is
"""
canvas, kwargs = pl.get_new_canvas(kwargs)
canvas, kwargs = pl.get_new_canvas(projection=projection, **kwargs)
plots = _plot_samples(self, canvas, plot_limits, fixed_inputs,
resolution, plot_raw,
apply_link, visible_dims, which_data_ycols, samples,
apply_link, visible_dims, which_data_ycols, samples, projection,
predict_kw, **kwargs)
return pl.show_canvas(canvas, plots)
def _plot_samples(self, canvas, plot_limits=None, fixed_inputs=None,
resolution=None, plot_raw=False,
resolution=None, plot_raw=True,
apply_link=False, visible_dims=None,
which_data_ycols=None,
samples=3,
samples=3, projection='2d',
label=None,
predict_kw=None, **kwargs):
_, _, _, _, free_dims, Xgrid, _, _, _, _, resolution = helper_for_plot_data(self, plot_limits, visible_dims, fixed_inputs, resolution)
_, _, _, _, free_dims, Xgrid, x, y, _, _, resolution = helper_for_plot_data(self, plot_limits, visible_dims, fixed_inputs, resolution)
if len(free_dims)<2:
if len(free_dims)<=2:
if len(free_dims)==1:
# 1D plotting:
_, _, samples = helper_predict_with_model(self, Xgrid, plot_raw, apply_link,
None, get_which_data_ycols(self, which_data_ycols), predict_kw, samples)
update_not_existing_kwargs(kwargs, pl.defaults.samples_1d) # @UndefinedVariable
return dict(gpmean=[pl.plot(canvas, Xgrid[:, free_dims], samples, **kwargs)])
elif len(free_dims)==2 and projection=='3d':
_, _, samples = helper_predict_with_model(self, Xgrid, plot_raw, apply_link,
None, get_which_data_ycols(self, which_data_ycols), predict_kw, samples)
update_not_existing_kwargs(kwargs, pl.defaults.samples_3d) # @UndefinedVariable
for s in range(samples.shape[-1]):
return dict(gpmean=[pl.surface(canvas, x,
y, samples[:, s].reshape(resolution, resolution),
**kwargs)])
else:
pass # Nothing to plot!
else:
@ -233,7 +253,7 @@ def plot_density(self, plot_limits=None, fixed_inputs=None,
:param int levels: the number of levels in the density (number bigger then 1, where 35 is smooth and 1 is the same as plot_confidence). You can go higher then 50 if the result is not smooth enough for you.
:param dict predict_kw: the keyword arguments for the prediction. If you want to plot a specific kernel give dict(kern=<specific kernel>) in here
"""
canvas, kwargs = pl.get_new_canvas(kwargs)
canvas, kwargs = pl.get_new_canvas(**kwargs)
plots = _plot_density(self, canvas, plot_limits,
fixed_inputs, resolution, plot_raw,
apply_link, visible_dims, which_data_ycols,
@ -276,13 +296,14 @@ def plot(self, plot_limits=None, fixed_inputs=None,
visible_dims=None,
levels=20, samples=0, samples_likelihood=0, lower=2.5, upper=97.5,
plot_data=True, plot_inducing=True, plot_density=False,
predict_kw=None, error_kwargs=None,
**kwargs):
predict_kw=None, projection='2d', **kwargs):
"""
Convinience function for plotting the fit of a GP.
Give the Y_metadata in the predict_kw if you need it.
If you want fine graned control use the specific plotting functions supplied in the model.
:param plot_limits: The limits of the plot. If 1D [xmin,xmax], if 2D [[xmin,ymin],[xmax,ymax]]. Defaluts to data limits
:type plot_limits: np.array
:param fixed_inputs: a list of tuple [(i,v), (i,v)...], specifying that input dimension i should be set to value v.
@ -304,14 +325,12 @@ def plot(self, plot_limits=None, fixed_inputs=None,
:param bool plot_inducing: plot inducing inputs?
:param bool plot_density: plot density instead of the confidence interval?
:param dict predict_kw: the keyword arguments for the prediction. If you want to plot a specific kernel give dict(kern=<specific kernel>) in here
:param dict error_kwargs: kwargs for the error plot for the plotting library you are using
:param kwargs plot_kwargs: kwargs for the data plot for the plotting library you are using
"""
canvas, kwargs = pl.get_new_canvas(kwargs)
canvas, _ = pl.get_new_canvas(projection=projection, **kwargs)
plots = _plot(self, canvas, plot_limits, fixed_inputs, resolution, plot_raw,
apply_link, which_data_ycols, which_data_rows, visible_dims,
levels, samples, samples_likelihood, lower, upper, plot_data,
plot_inducing, plot_density, predict_kw, error_kwargs)
plot_inducing, plot_density, projection, predict_kw)
return pl.show_canvas(canvas, plots)
@ -322,13 +341,15 @@ def plot_f(self, plot_limits=None, fixed_inputs=None,
visible_dims=None,
levels=20, samples=0, lower=2.5, upper=97.5,
plot_density=False,
plot_data=True, plot_inducing=True,
predict_kw=None, error_kwargs=None,
plot_data=True, plot_inducing=True,
projection='2d',
predict_kw=None,
**kwargs):
"""
Convinience function for plotting the fit of a GP.
This is the same as plot, except it plots the latent function fit of the GP!
If you want fine graned control use the specific plotting functions supplied in the model.
Give the Y_metadata in the predict_kw if you need it.
@ -354,12 +375,12 @@ def plot_f(self, plot_limits=None, fixed_inputs=None,
:param dict error_kwargs: kwargs for the error plot for the plotting library you are using
:param kwargs plot_kwargs: kwargs for the data plot for the plotting library you are using
"""
canvas, kwargs = pl.get_new_canvas(kwargs)
canvas, _ = pl.get_new_canvas(projection=='3d', **kwargs)
plots = _plot(self, canvas, plot_limits, fixed_inputs, resolution,
True, apply_link, which_data_ycols, which_data_rows,
visible_dims, levels, samples, 0, lower, upper,
plot_data, plot_inducing, plot_density,
predict_kw, error_kwargs)
plot_data, plot_inducing, plot_density, projection,
predict_kw)
return pl.show_canvas(canvas, plots)
@ -370,19 +391,27 @@ def _plot(self, canvas, plot_limits=None, fixed_inputs=None,
which_data_ycols='all', which_data_rows='all',
visible_dims=None,
levels=20, samples=0, samples_likelihood=0, lower=2.5, upper=97.5,
plot_data=True, plot_inducing=True, plot_density=False,
predict_kw=None, error_kwargs=None,
**kwargs):
plot_data=True, plot_inducing=True, plot_density=False, projection='2d',
predict_kw=None):
plots = {}
if plot_raw and not apply_link:
# It does not make sense to plot the data (which lives not in the latent function space) into latent function space.
plot_data = False
if plot_data:
plots.update(_plot_data(self, canvas, which_data_rows, which_data_ycols, visible_dims, error_kwargs))
plots.update(_plot_mean(self, canvas, plot_limits, fixed_inputs, resolution, plot_raw, apply_link, visible_dims, which_data_ycols, levels, predict_kw))
if not plot_density:
plots.update(_plot_confidence(self, canvas, lower, upper, plot_limits, fixed_inputs, resolution, plot_raw, apply_link, visible_dims, which_data_ycols, predict_kw))
else:
plots.update(_plot_density(self, canvas, plot_limits, fixed_inputs, resolution, plot_raw, apply_link, visible_dims, which_data_ycols, levels, predict_kw))
plots.update(_plot_data(self, canvas, which_data_rows, which_data_ycols, visible_dims,
projection, label=None))
plots.update(_plot_data_error(self, canvas, which_data_rows, which_data_ycols, visible_dims,
projection, label=None))
plots.update(_plot_mean(self, canvas, plot_limits, fixed_inputs, resolution, plot_raw, apply_link, visible_dims, which_data_ycols, levels, projection, label=None,
predict_kw=None))
if projection=='2d':
if not plot_density:
plots.update(_plot_confidence(self, canvas, lower, upper, plot_limits, fixed_inputs, resolution, plot_raw, apply_link, visible_dims, which_data_ycols, predict_kw))
else:
plots.update(_plot_density(self, canvas, plot_limits, fixed_inputs, resolution, plot_raw, apply_link, visible_dims, which_data_ycols, levels, predict_kw))
if samples > 0:
plots.update(_plot_samples(self, canvas, plot_limits, fixed_inputs, resolution, True, apply_link, visible_dims, which_data_ycols, samples, predict_kw))
@ -390,6 +419,6 @@ def _plot(self, canvas, plot_limits=None, fixed_inputs=None,
plots.update(_plot_samples(self, canvas, plot_limits, fixed_inputs, resolution, False, apply_link, visible_dims, which_data_ycols, samples, predict_kw))
if hasattr(self, 'Z') and plot_inducing:
plots.update(_plot_inducing(self, canvas, visible_dims))
plots.update(_plot_inducing(self, canvas, visible_dims, projection, None))
return plots

View file

@ -0,0 +1,82 @@
#===============================================================================
# Copyright (c) 2015, Max Zwiessele
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# * Neither the name of GPy.plotting.gpy_plot.kernel_plots nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#===============================================================================
import numpy as np
from . import pl
from .. import Tango
def plot_ARD(kernel, filtering=None, **kwargs):
"""
If an ARD kernel is present, plot a bar representation using matplotlib
:param fignum: figure number of the plot
:param filtering: list of names, which to use for plotting ARD parameters.
Only kernels which match names in the list of names in filtering
will be used for plotting.
:type filtering: list of names to use for ARD plot
"""
canvas, kwargs = pl.get_new_canvas(kwargs)
Tango.reset()
bars = []
ard_params = np.atleast_2d(kernel.input_sensitivity(summarize=False))
bottom = 0
last_bottom = bottom
x = np.arange(kernel.input_dim)
if filtering is None:
filtering = kernel.parameter_names(recursive=False)
for i in range(ard_params.shape[0]):
if kernel.parameters[i].name in filtering:
c = Tango.nextMedium()
bars.append(pl.barplot(canvas, x, ard_params[i,:], color=c, label=kernel.parameters[i].name, bottom=bottom))
last_bottom = ard_params[i,:]
bottom += last_bottom
else:
print("filtering out {}".format(kernel.parameters[i].name))
plt.show_canvas()
ax.set_xlim(-.5, kernel.input_dim - .5)
add_bar_labels(fig, ax, [bars[-1]], bottom=bottom-last_bottom)
if legend:
if title is '':
mode = 'expand'
if len(bars) > 1:
mode = 'expand'
ax.legend(bbox_to_anchor=(0., 1.02, 1., 1.02), loc=3,
ncol=len(bars), mode=mode, borderaxespad=0.)
fig.tight_layout(rect=(0, 0, 1, .9))
else:
ax.legend()
return dict(barplots=bars)

View file

@ -0,0 +1,107 @@
#===============================================================================
# Copyright (c) 2015, Max Zwiessele
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# * Neither the name of GPy.plotting.gpy_plot.latent_plots nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#===============================================================================
import numpy as np
from . import pl
from .plot_util import get_x_y_var, get_free_dims, get_which_data_ycols,\
get_which_data_rows, update_not_existing_kwargs, helper_predict_with_model,\
helper_for_plot_data
def plot_prediction_fit(self, plot_limits=None,
which_data_rows='all', which_data_ycols='all',
fixed_inputs=None, resolution=None,
plot_raw=False, apply_link=False, visible_dims=None,
predict_kw=None, scatter_kwargs=None, **plot_kwargs):
"""
Plot the fit of the (Bayesian)GPLVM latent space prediction to the outputs.
This scatters two output dimensions against each other and a line
from the prediction in two dimensions between them.
Give the Y_metadata in the predict_kw if you need it.
:param which_data_rows: which of the training data to plot (default all)
:type which_data_rows: 'all' or a slice object to slice self.X, self.Y
:param array-like which_data_ycols: which columns of y to plot (array-like or list of ints)
:param fixed_inputs: a list of tuple [(i,v), (i,v)...], specifying that input dimension i should be set to value v.
:type fixed_inputs: a list of tuples
:param int resolution: The resolution of the prediction [defaults are 1D:200, 2D:50]
:param bool plot_raw: plot the latent function (usually denoted f) only?
:param bool apply_link: whether to apply the link function of the GP to the raw prediction.
:param array-like visible_dims: which columns of the input X (!) to plot (array-like or list of ints)
:param dict predict_kw: the keyword arguments for the prediction. If you want to plot a specific kernel give dict(kern=<specific kernel>) in here
:param dict sactter_kwargs: kwargs for the scatter plot, specific for the plotting library you are using
:param kwargs plot_kwargs: kwargs for the data plot for the plotting library you are using
"""
canvas, kwargs = pl.get_new_canvas(plot_kwargs)
plots = _plot_prediction_fit(self, canvas, plot_limits, which_data_rows, which_data_ycols,
fixed_inputs, resolution, plot_raw,
apply_link, visible_dims,
predict_kw, scatter_kwargs, **kwargs)
return pl.show_canvas(canvas, plots)
def _plot_prediction_fit(self, canvas, plot_limits=None,
which_data_rows='all', which_data_ycols='all',
fixed_inputs=None, resolution=None,
plot_raw=False, apply_link=False, visible_dims=False,
predict_kw=None, scatter_kwargs=None, **plot_kwargs):
ycols = get_which_data_ycols(self, which_data_ycols)
rows = get_which_data_rows(self, which_data_rows)
if visible_dims is None:
visible_dims = self.get_most_significant_input_dimensions()[:1]
X, _, Y, _, free_dims, Xgrid, _, _, _, _, resolution = helper_for_plot_data(self, plot_limits, visible_dims, fixed_inputs, resolution)
plots = {}
if len(free_dims)<2:
if len(free_dims)==1:
if scatter_kwargs is None:
scatter_kwargs = {}
update_not_existing_kwargs(scatter_kwargs, pl.defaults.data_y_1d) # @UndefinedVariable
plots['output'] = pl.scatter(canvas, Y[rows, ycols[0]], Y[rows, ycols[1]],
c=X[rows, free_dims[0]],
**scatter_kwargs)
if predict_kw is None:
predict_kw = {}
mu, _, _ = helper_predict_with_model(self, Xgrid, plot_raw,
apply_link, None,
ycols, predict_kw)
update_not_existing_kwargs(plot_kwargs, pl.defaults.data_y_1d_plot) # @UndefinedVariable
plots['output_fit'] = pl.plot(canvas, mu[:, 0], mu[:, 1], **plot_kwargs)
else:
pass #Nothing to plot!
else:
raise NotImplementedError("Cannot plot in more then one dimension.")
return plots