Merge branch 'devel' of https://github.com/SheffieldML/GPy into wgps_improvements

Merging new devel
This commit is contained in:
beckdaniel 2016-03-02 17:26:04 +00:00
commit 76f3ff65a1
45 changed files with 729 additions and 378 deletions

View file

@ -25,18 +25,66 @@ def change_plotting_library(lib):
current_lib[0] = PlotlyPlots()
if lib == 'none':
current_lib[0] = None
inject_plotting()
#===========================================================================
except (ImportError, NameError):
config.set('plotting', 'library', 'none')
raise
import warnings
warnings.warn(ImportWarning("You spevified {} in your configuration, but is not available. Install newest version of {} for plotting".format(lib, lib)))
from ..util.config import config, NoOptionError
try:
lib = config.get('plotting', 'library')
change_plotting_library(lib)
except NoOptionError:
print("No plotting library was specified in config file. \n{}".format(error_suggestion))
def inject_plotting():
if current_lib[0] is not None:
# Inject the plots into classes here:
# Already converted to new style:
from . import gpy_plot
from ..core import GP
GP.plot_data = gpy_plot.data_plots.plot_data
GP.plot_data_error = gpy_plot.data_plots.plot_data_error
GP.plot_errorbars_trainset = gpy_plot.data_plots.plot_errorbars_trainset
GP.plot_mean = gpy_plot.gp_plots.plot_mean
GP.plot_confidence = gpy_plot.gp_plots.plot_confidence
GP.plot_density = gpy_plot.gp_plots.plot_density
GP.plot_samples = gpy_plot.gp_plots.plot_samples
GP.plot = gpy_plot.gp_plots.plot
GP.plot_f = gpy_plot.gp_plots.plot_f
GP.plot_magnification = gpy_plot.latent_plots.plot_magnification
from ..core import SparseGP
SparseGP.plot_inducing = gpy_plot.data_plots.plot_inducing
from ..models import GPLVM, BayesianGPLVM, bayesian_gplvm_minibatch, SSGPLVM, SSMRD
GPLVM.plot_latent = gpy_plot.latent_plots.plot_latent
GPLVM.plot_scatter = gpy_plot.latent_plots.plot_latent_scatter
GPLVM.plot_inducing = gpy_plot.latent_plots.plot_latent_inducing
GPLVM.plot_steepest_gradient_map = gpy_plot.latent_plots.plot_steepest_gradient_map
BayesianGPLVM.plot_latent = gpy_plot.latent_plots.plot_latent
BayesianGPLVM.plot_scatter = gpy_plot.latent_plots.plot_latent_scatter
BayesianGPLVM.plot_inducing = gpy_plot.latent_plots.plot_latent_inducing
BayesianGPLVM.plot_steepest_gradient_map = gpy_plot.latent_plots.plot_steepest_gradient_map
bayesian_gplvm_minibatch.BayesianGPLVMMiniBatch.plot_latent = gpy_plot.latent_plots.plot_latent
bayesian_gplvm_minibatch.BayesianGPLVMMiniBatch.plot_scatter = gpy_plot.latent_plots.plot_latent_scatter
bayesian_gplvm_minibatch.BayesianGPLVMMiniBatch.plot_inducing = gpy_plot.latent_plots.plot_latent_inducing
bayesian_gplvm_minibatch.BayesianGPLVMMiniBatch.plot_steepest_gradient_map = gpy_plot.latent_plots.plot_steepest_gradient_map
SSGPLVM.plot_latent = gpy_plot.latent_plots.plot_latent
SSGPLVM.plot_scatter = gpy_plot.latent_plots.plot_latent_scatter
SSGPLVM.plot_inducing = gpy_plot.latent_plots.plot_latent_inducing
SSGPLVM.plot_steepest_gradient_map = gpy_plot.latent_plots.plot_steepest_gradient_map
from ..kern import Kern
Kern.plot_covariance = gpy_plot.kernel_plots.plot_covariance
def deprecate_plot(self, *args, **kwargs):
import warnings
warnings.warn(DeprecationWarning('Kern.plot is being deprecated and will not be available in the 1.0 release. Use Kern.plot_covariance instead'))
return self.plot_covariance(*args, **kwargs)
Kern.plot = deprecate_plot
Kern.plot_ARD = gpy_plot.kernel_plots.plot_ARD
from ..inference.optimization import Optimizer
Optimizer.plot = gpy_plot.inference_plots.plot_optimizer
# Variational plot!
def plotting_library():
if current_lib[0] is None:
@ -53,54 +101,10 @@ def show(figure, **kwargs):
"""
return plotting_library().show_canvas(figure, **kwargs)
if config.get('plotting', 'library') is not 'none':
# Inject the plots into classes here:
# Already converted to new style:
from . import gpy_plot
from ..core import GP
GP.plot_data = gpy_plot.data_plots.plot_data
GP.plot_data_error = gpy_plot.data_plots.plot_data_error
GP.plot_errorbars_trainset = gpy_plot.data_plots.plot_errorbars_trainset
GP.plot_mean = gpy_plot.gp_plots.plot_mean
GP.plot_confidence = gpy_plot.gp_plots.plot_confidence
GP.plot_density = gpy_plot.gp_plots.plot_density
GP.plot_samples = gpy_plot.gp_plots.plot_samples
GP.plot = gpy_plot.gp_plots.plot
GP.plot_f = gpy_plot.gp_plots.plot_f
GP.plot_magnification = gpy_plot.latent_plots.plot_magnification
from ..core import SparseGP
SparseGP.plot_inducing = gpy_plot.data_plots.plot_inducing
from ..models import GPLVM, BayesianGPLVM, bayesian_gplvm_minibatch, SSGPLVM, SSMRD
GPLVM.plot_latent = gpy_plot.latent_plots.plot_latent
GPLVM.plot_scatter = gpy_plot.latent_plots.plot_latent_scatter
GPLVM.plot_inducing = gpy_plot.latent_plots.plot_latent_inducing
GPLVM.plot_steepest_gradient_map = gpy_plot.latent_plots.plot_steepest_gradient_map
BayesianGPLVM.plot_latent = gpy_plot.latent_plots.plot_latent
BayesianGPLVM.plot_scatter = gpy_plot.latent_plots.plot_latent_scatter
BayesianGPLVM.plot_inducing = gpy_plot.latent_plots.plot_latent_inducing
BayesianGPLVM.plot_steepest_gradient_map = gpy_plot.latent_plots.plot_steepest_gradient_map
bayesian_gplvm_minibatch.BayesianGPLVMMiniBatch.plot_latent = gpy_plot.latent_plots.plot_latent
bayesian_gplvm_minibatch.BayesianGPLVMMiniBatch.plot_scatter = gpy_plot.latent_plots.plot_latent_scatter
bayesian_gplvm_minibatch.BayesianGPLVMMiniBatch.plot_inducing = gpy_plot.latent_plots.plot_latent_inducing
bayesian_gplvm_minibatch.BayesianGPLVMMiniBatch.plot_steepest_gradient_map = gpy_plot.latent_plots.plot_steepest_gradient_map
SSGPLVM.plot_latent = gpy_plot.latent_plots.plot_latent
SSGPLVM.plot_scatter = gpy_plot.latent_plots.plot_latent_scatter
SSGPLVM.plot_inducing = gpy_plot.latent_plots.plot_latent_inducing
SSGPLVM.plot_steepest_gradient_map = gpy_plot.latent_plots.plot_steepest_gradient_map
from ..kern import Kern
Kern.plot_covariance = gpy_plot.kernel_plots.plot_covariance
def deprecate_plot(self, *args, **kwargs):
import warnings
warnings.warn(DeprecationWarning('Kern.plot is being deprecated and will not be available in the 1.0 release. Use Kern.plot_covariance instead'))
return self.plot_covariance(*args, **kwargs)
Kern.plot = deprecate_plot
Kern.plot_ARD = gpy_plot.kernel_plots.plot_ARD
from ..inference.optimization import Optimizer
Optimizer.plot = gpy_plot.inference_plots.plot_optimizer
# Variational plot!
from ..util.config import config, NoOptionError
try:
lib = config.get('plotting', 'library')
change_plotting_library(lib)
except NoOptionError:
print("No plotting library was specified in config file. \n{}".format(error_suggestion))

View file

@ -46,7 +46,7 @@ def plot_mean(self, plot_limits=None, fixed_inputs=None,
"""
Plot the mean of the GP.
You can deactivate the legend for this one plot by supplying None to label.
You can deactivate the legend for this one plot by supplying None to label.
Give the Y_metadata in the predict_kw if you need it.
@ -91,7 +91,7 @@ def _plot_mean(self, canvas, helper_data, helper_prediction,
if projection == '2d':
update_not_existing_kwargs(kwargs, pl().defaults.meanplot_2d) # @UndefinedVariable
plots = dict(gpmean=[pl().contour(canvas, x[:,0], y[0,:],
mu.reshape(resolution, resolution),
mu.reshape(resolution, resolution).T,
levels=levels, label=label, **kwargs)])
elif projection == '3d':
update_not_existing_kwargs(kwargs, pl().defaults.meanplot_3d) # @UndefinedVariable
@ -116,7 +116,7 @@ def plot_confidence(self, lower=2.5, upper=97.5, plot_limits=None, fixed_inputs=
E.g. the 95% confidence interval is $2.5, 97.5$.
Note: Only implemented for one dimension!
You can deactivate the legend for this one plot by supplying None to label.
You can deactivate the legend for this one plot by supplying None to label.
Give the Y_metadata in the predict_kw if you need it.
@ -170,7 +170,7 @@ def plot_samples(self, plot_limits=None, fixed_inputs=None,
"""
Plot the mean of the GP.
You can deactivate the legend for this one plot by supplying None to label.
You can deactivate the legend for this one plot by supplying None to label.
Give the Y_metadata in the predict_kw if you need it.
@ -231,7 +231,7 @@ def plot_density(self, plot_limits=None, fixed_inputs=None,
E.g. the 95% confidence interval is $2.5, 97.5$.
Note: Only implemented for one dimension!
You can deactivate the legend for this one plot by supplying None to label.
You can deactivate the legend for this one plot by supplying None to label.
Give the Y_metadata in the predict_kw if you need it.
@ -288,7 +288,7 @@ def plot(self, plot_limits=None, fixed_inputs=None,
"""
Convenience function for plotting the fit of a GP.
You can deactivate the legend for this one plot by supplying None to label.
You can deactivate the legend for this one plot by supplying None to label.
Give the Y_metadata in the predict_kw if you need it.
@ -319,9 +319,17 @@ def plot(self, plot_limits=None, fixed_inputs=None,
:param {2d|3d} projection: plot in 2d or 3d?
:param bool legend: convenience, whether to put a legend on the plot or not.
"""
canvas, _ = pl().new_canvas(projection=projection, **kwargs)
X = get_x_y_var(self)[0]
helper_data = helper_for_plot_data(self, X, plot_limits, visible_dims, fixed_inputs, resolution)
xmin, xmax = helper_data[5:7]
free_dims = helper_data[1]
if not 'xlim' in kwargs:
kwargs['xlim'] = (xmin[0], xmax[0])
if not 'ylim' in kwargs and len(free_dims) == 2:
kwargs['ylim'] = (xmin[1], xmax[1])
canvas, _ = pl().new_canvas(projection=projection, **kwargs)
helper_prediction = helper_predict_with_model(self, helper_data[2], plot_raw,
apply_link, np.linspace(2.5, 97.5, levels*2) if plot_density else (lower,upper),
get_which_data_ycols(self, which_data_ycols),
@ -330,9 +338,11 @@ def plot(self, plot_limits=None, fixed_inputs=None,
# It does not make sense to plot the data (which lives not in the latent function space) into latent function space.
plot_data = False
plots = {}
if hasattr(self, 'Z') and plot_inducing:
plots.update(_plot_inducing(self, canvas, visible_dims, projection, 'Inducing'))
if plot_data:
plots.update(_plot_data(self, canvas, which_data_rows, which_data_ycols, visible_dims, projection, "Data"))
plots.update(_plot_data_error(self, canvas, which_data_rows, which_data_ycols, visible_dims, projection, "Data Error"))
plots.update(_plot_data(self, canvas, which_data_rows, which_data_ycols, free_dims, projection, "Data"))
plots.update(_plot_data_error(self, canvas, which_data_rows, which_data_ycols, free_dims, projection, "Data Error"))
plots.update(_plot(self, canvas, plots, helper_data, helper_prediction, levels, plot_inducing, plot_density, projection))
if plot_raw and (samples_likelihood > 0):
helper_prediction = helper_predict_with_model(self, helper_data[2], False,
@ -340,8 +350,6 @@ def plot(self, plot_limits=None, fixed_inputs=None,
get_which_data_ycols(self, which_data_ycols),
predict_kw, samples_likelihood)
plots.update(_plot_samples(canvas, helper_data, helper_prediction, projection, "Lik Samples"))
if hasattr(self, 'Z') and plot_inducing:
plots.update(_plot_inducing(self, canvas, visible_dims, projection, 'Inducing'))
return pl().add_to_canvas(canvas, plots, legend=legend)
@ -362,7 +370,7 @@ def plot_f(self, plot_limits=None, fixed_inputs=None,
If you want fine graned control use the specific plotting functions supplied in the model.
You can deactivate the legend for this one plot by supplying None to label.
You can deactivate the legend for this one plot by supplying None to label.
Give the Y_metadata in the predict_kw if you need it.
@ -389,7 +397,7 @@ 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
"""
plot(self, plot_limits, fixed_inputs, resolution, True,
return plot(self, 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,

View file

@ -33,7 +33,7 @@ from .. import Tango
from .plot_util import update_not_existing_kwargs, helper_for_plot_data
from ...kern.src.kern import Kern, CombinationKernel
def plot_ARD(kernel, filtering=None, legend=False, **kwargs):
def plot_ARD(kernel, filtering=None, legend=False, canvas=None, **kwargs):
"""
If an ARD kernel is present, plot a bar representation using matplotlib
@ -62,7 +62,11 @@ def plot_ARD(kernel, filtering=None, legend=False, **kwargs):
bars = []
kwargs = update_not_existing_kwargs(kwargs, pl().defaults.ard)
canvas, kwargs = pl().new_canvas(xlim=(-.5, kernel._effective_input_dim-.5), xlabel='input dimension', ylabel='sensitivity', **kwargs)
if canvas is None:
canvas, kwargs = pl().new_canvas(xlim=(-.5, kernel._effective_input_dim-.5), xlabel='input dimension', ylabel='sensitivity', **kwargs)
for i in range(ard_params.shape[0]):
if parts[i].name in filtering:
c = Tango.nextMedium()
@ -96,7 +100,7 @@ def plot_covariance(kernel, x=None, label=None,
"""
X = np.ones((2, kernel._effective_input_dim)) * [[-3], [3]]
_, free_dims, Xgrid, xx, yy, _, _, resolution = helper_for_plot_data(kernel, X, plot_limits, visible_dims, None, resolution)
from numbers import Number
if x is None:
from ...kern.src.stationary import Stationary
@ -104,7 +108,7 @@ def plot_covariance(kernel, x=None, label=None,
elif isinstance(x, Number):
x = np.ones((1, kernel._effective_input_dim))*x
K = kernel.K(Xgrid, x)
if projection == '3d':
xlabel = 'X[:,0]'
ylabel = 'X[:,1]'

View file

@ -50,6 +50,17 @@ def _wait_for_updates(view, updates):
# No updateable view:
pass
def _new_canvas(self, projection, kwargs, which_indices):
input_1, input_2, input_3 = sig_dims = self.get_most_significant_input_dimensions(which_indices)
if input_3 is None:
zlabel = None
else:
zlabel = 'latent dimension %i' % input_3
canvas, kwargs = pl().new_canvas(projection=projection, xlabel='latent dimension %i' % input_1,
ylabel='latent dimension %i' % input_2,
zlabel=zlabel, **kwargs)
return canvas, projection, kwargs, sig_dims
def _plot_latent_scatter(canvas, X, visible_dims, labels, marker, num_samples, projection='2d', **kwargs):
from .. import Tango
@ -85,12 +96,8 @@ def plot_latent_scatter(self, labels=None,
:param str marker: markers to use - cycle if more labels then markers are given
:param kwargs: the kwargs for the scatter plots
"""
input_1, input_2, input_3 = sig_dims = self.get_most_significant_input_dimensions(which_indices)
canvas, projection, kwargs, sig_dims = _new_canvas(self, projection, kwargs, which_indices)
canvas, kwargs = pl().new_canvas(projection=projection,
xlabel='latent dimension %i' % input_1,
ylabel='latent dimension %i' % input_2,
zlabel='latent dimension %i' % input_3, **kwargs)
X, _, _ = get_x_y_var(self)
if labels is None:
labels = np.ones(self.num_data)
@ -101,8 +108,6 @@ def plot_latent_scatter(self, labels=None,
return pl().add_to_canvas(canvas, dict(scatter=scatters), legend=legend)
def plot_latent_inducing(self,
which_indices=None,
legend=False,
@ -122,17 +127,8 @@ def plot_latent_inducing(self,
:param str marker: markers to use - cycle if more labels then markers are given
:param kwargs: the kwargs for the scatter plots
"""
input_1, input_2, input_3 = sig_dims = self.get_most_significant_input_dimensions(which_indices)
if input_3 is None: zlabel=None
else: zlabel = 'latent dimension %i' % input_3
canvas, projection, kwargs, sig_dims = _new_canvas(self, projection, kwargs, which_indices)
if 'color' not in kwargs:
kwargs['color'] = 'white'
canvas, kwargs = pl().new_canvas(projection=projection,
xlabel='latent dimension %i' % input_1,
ylabel='latent dimension %i' % input_2,
zlabel=zlabel, **kwargs)
Z = self.Z.values
labels = np.array(['inducing'] * Z.shape[0])
scatters = _plot_latent_scatter(canvas, Z, sig_dims, labels, marker, num_samples, projection=projection, **kwargs)
@ -167,7 +163,8 @@ def plot_magnification(self, labels=None, which_indices=None,
updates=False,
mean=True, covariance=True,
kern=None, num_samples=1000,
scatter_kwargs=None, **imshow_kwargs):
scatter_kwargs=None, plot_scatter=True,
**imshow_kwargs):
"""
Plot the magnification factor of the GP on the inputs. This is the
density of the GP as a gray scale.
@ -192,17 +189,20 @@ def plot_magnification(self, labels=None, which_indices=None,
_, _, Xgrid, _, _, xmin, xmax, resolution = helper_for_plot_data(self, X, plot_limits, which_indices, None, resolution)
canvas, imshow_kwargs = pl().new_canvas(xlim=(xmin[0], xmax[0]), ylim=(xmin[1], xmax[1]),
xlabel='latent dimension %i' % input_1, ylabel='latent dimension %i' % input_2, **imshow_kwargs)
if (labels is not None):
legend = find_best_layout_for_subplots(len(np.unique(labels)))[1]
else:
labels = np.ones(self.num_data)
legend = False
scatters = _plot_latent_scatter(canvas, X, which_indices, labels, marker, num_samples, projection='2d', **scatter_kwargs or {})
view = _plot_magnification(self, canvas, which_indices, Xgrid, xmin, xmax, resolution, updates, mean, covariance, kern, **imshow_kwargs)
retval = pl().add_to_canvas(canvas, dict(scatter=scatters, imshow=view),
plots = {}
if legend and plot_scatter:
if (labels is not None):
legend = find_best_layout_for_subplots(len(np.unique(labels)))[1]
else:
labels = np.ones(self.num_data)
legend = False
if plot_scatter:
plots['scatters'] = _plot_latent_scatter(canvas, X, which_indices, labels, marker, num_samples, projection='2d', **scatter_kwargs or {})
plots['view'] = _plot_magnification(self, canvas, which_indices, Xgrid, xmin, xmax, resolution, updates, mean, covariance, kern, **imshow_kwargs)
retval = pl().add_to_canvas(canvas, plots,
legend=legend,
)
_wait_for_updates(view, updates)
_wait_for_updates(plots['view'], updates)
return retval
@ -231,7 +231,7 @@ def plot_latent(self, labels=None, which_indices=None,
plot_limits=None,
updates=False,
kern=None, marker='<>^vsd',
num_samples=1000,
num_samples=1000, projection='2d',
scatter_kwargs=None, **imshow_kwargs):
"""
Plot the latent space of the GP on the inputs. This is the
@ -251,16 +251,19 @@ def plot_latent(self, labels=None, which_indices=None,
:param imshow_kwargs: the kwargs for the imshow (magnification factor)
:param scatter_kwargs: the kwargs for the scatter plots
"""
if projection != '2d':
raise ValueError('Cannot plot latent in other then 2 dimensions, consider plot_scatter')
input_1, input_2 = which_indices = self.get_most_significant_input_dimensions(which_indices)[:2]
X = get_x_y_var(self)[0]
_, _, Xgrid, _, _, xmin, xmax, resolution = helper_for_plot_data(self, X, plot_limits, which_indices, None, resolution)
canvas, imshow_kwargs = pl().new_canvas(xlim=(xmin[0], xmax[0]), ylim=(xmin[1], xmax[1]),
xlabel='latent dimension %i' % input_1, ylabel='latent dimension %i' % input_2, **imshow_kwargs)
if (labels is not None):
legend = find_best_layout_for_subplots(len(np.unique(labels)))[1]
else:
labels = np.ones(self.num_data)
legend = False
if legend:
if (labels is not None):
legend = find_best_layout_for_subplots(len(np.unique(labels)))[1]
else:
labels = np.ones(self.num_data)
legend = False
scatters = _plot_latent_scatter(canvas, X, which_indices, labels, marker, num_samples, projection='2d', **scatter_kwargs or {})
view = _plot_latent(self, canvas, which_indices, Xgrid, xmin, xmax, resolution, updates, kern, **imshow_kwargs)
retval = pl().add_to_canvas(canvas, dict(scatter=scatters, imshow=view), legend=legend)

View file

@ -203,7 +203,7 @@ def subsample_X(X, labels, num_samples=1000):
num_samples and the returned subsampled X.
"""
if X.shape[0] > num_samples:
print("Warning: subsampling X, as it has more samples then 1000. X.shape={!s}".format(X.shape))
print("Warning: subsampling X, as it has more samples then {}. X.shape={!s}".format(int(num_samples), X.shape))
if labels is not None:
subsample = []
for _, _, _, _, index, _ in scatter_label_generator(labels, X, (0, None, None)):
@ -289,7 +289,10 @@ def get_x_y_var(model):
X = model.X.mean.values
X_variance = model.X.variance.values
else:
X = model.X.values
try:
X = model.X.values
except AttributeError:
X = model.X
X_variance = None
try:
Y = model.Y.values
@ -352,7 +355,7 @@ def x_frame1D(X,plot_limits=None,resolution=None):
xmin,xmax = X.min(0),X.max(0)
xmin, xmax = xmin-0.25*(xmax-xmin), xmax+0.25*(xmax-xmin)
elif len(plot_limits) == 2:
xmin, xmax = plot_limits
xmin, xmax = map(np.atleast_1d, plot_limits)
else:
raise ValueError("Bad limits for plotting")

View file

@ -18,4 +18,4 @@
from .util import align_subplot_array, align_subplots, fewerXticks, removeRightTicks, removeUpperTicks
from . import controllers
from . import controllers, base_plots

View file

@ -0,0 +1,265 @@
# #Copyright (c) 2012, GPy authors (see AUTHORS.txt).
# Licensed under the BSD 3-clause license (see LICENSE.txt)
from matplotlib import pyplot as plt
import numpy as np
def ax_default(fignum, ax):
if ax is None:
fig = plt.figure(fignum)
ax = fig.add_subplot(111)
else:
fig = ax.figure
return fig, ax
def meanplot(x, mu, color='#3300FF', ax=None, fignum=None, linewidth=2,**kw):
_, axes = ax_default(fignum, ax)
return axes.plot(x,mu,color=color,linewidth=linewidth,**kw)
def gpplot(x, mu, lower, upper, edgecol='#3300FF', fillcol='#33CCFF', ax=None, fignum=None, **kwargs):
_, axes = ax_default(fignum, ax)
mu = mu.flatten()
x = x.flatten()
lower = lower.flatten()
upper = upper.flatten()
plots = []
#here's the mean
plots.append(meanplot(x, mu, edgecol, axes))
#here's the box
kwargs['linewidth']=0.5
if not 'alpha' in kwargs.keys():
kwargs['alpha'] = 0.3
plots.append(axes.fill(np.hstack((x,x[::-1])),np.hstack((upper,lower[::-1])),color=fillcol,**kwargs))
#this is the edge:
plots.append(meanplot(x, upper,color=edgecol, linewidth=0.2, ax=axes))
plots.append(meanplot(x, lower,color=edgecol, linewidth=0.2, ax=axes))
return plots
def gradient_fill(x, percentiles, ax=None, fignum=None, **kwargs):
_, ax = ax_default(fignum, ax)
plots = []
#here's the box
if 'linewidth' not in kwargs:
kwargs['linewidth'] = 0.5
if not 'alpha' in kwargs.keys():
kwargs['alpha'] = 1./(len(percentiles))
# pop where from kwargs
where = kwargs.pop('where') if 'where' in kwargs else None
# pop interpolate, which we actually do not do here!
if 'interpolate' in kwargs: kwargs.pop('interpolate')
def pairwise(inlist):
l = len(inlist)
for i in range(int(np.ceil(l/2.))):
yield inlist[:][i], inlist[:][(l-1)-i]
polycol = []
for y1, y2 in pairwise(percentiles):
import matplotlib.mlab as mlab
# Handle united data, such as dates
ax._process_unit_info(xdata=x, ydata=y1)
ax._process_unit_info(ydata=y2)
# Convert the arrays so we can work with them
from numpy import ma
x = ma.masked_invalid(ax.convert_xunits(x))
y1 = ma.masked_invalid(ax.convert_yunits(y1))
y2 = ma.masked_invalid(ax.convert_yunits(y2))
if y1.ndim == 0:
y1 = np.ones_like(x) * y1
if y2.ndim == 0:
y2 = np.ones_like(x) * y2
if where is None:
where = np.ones(len(x), np.bool)
else:
where = np.asarray(where, np.bool)
if not (x.shape == y1.shape == y2.shape == where.shape):
raise ValueError("Argument dimensions are incompatible")
mask = reduce(ma.mask_or, [ma.getmask(a) for a in (x, y1, y2)])
if mask is not ma.nomask:
where &= ~mask
polys = []
for ind0, ind1 in mlab.contiguous_regions(where):
xslice = x[ind0:ind1]
y1slice = y1[ind0:ind1]
y2slice = y2[ind0:ind1]
if not len(xslice):
continue
N = len(xslice)
X = np.zeros((2 * N + 2, 2), np.float)
# the purpose of the next two lines is for when y2 is a
# scalar like 0 and we want the fill to go all the way
# down to 0 even if none of the y1 sample points do
start = xslice[0], y2slice[0]
end = xslice[-1], y2slice[-1]
X[0] = start
X[N + 1] = end
X[1:N + 1, 0] = xslice
X[1:N + 1, 1] = y1slice
X[N + 2:, 0] = xslice[::-1]
X[N + 2:, 1] = y2slice[::-1]
polys.append(X)
polycol.extend(polys)
from matplotlib.collections import PolyCollection
plots.append(PolyCollection(polycol, **kwargs))
ax.add_collection(plots[-1], autolim=True)
ax.autoscale_view()
return plots
def gperrors(x, mu, lower, upper, edgecol=None, ax=None, fignum=None, **kwargs):
_, axes = ax_default(fignum, ax)
mu = mu.flatten()
x = x.flatten()
lower = lower.flatten()
upper = upper.flatten()
plots = []
if edgecol is None:
edgecol='#3300FF'
if not 'alpha' in kwargs.keys():
kwargs['alpha'] = 1.
if not 'lw' in kwargs.keys():
kwargs['lw'] = 1.
plots.append(axes.errorbar(x,mu,yerr=np.vstack([mu-lower,upper-mu]),color=edgecol,**kwargs))
plots[-1][0].remove()
return plots
def removeRightTicks(ax=None):
ax = ax or plt.gca()
for i, line in enumerate(ax.get_yticklines()):
if i%2 == 1: # odd indices
line.set_visible(False)
def removeUpperTicks(ax=None):
ax = ax or plt.gca()
for i, line in enumerate(ax.get_xticklines()):
if i%2 == 1: # odd indices
line.set_visible(False)
def fewerXticks(ax=None,divideby=2):
ax = ax or plt.gca()
ax.set_xticks(ax.get_xticks()[::divideby])
def align_subplots(N,M,xlim=None, ylim=None):
"""make all of the subplots have the same limits, turn off unnecessary ticks"""
#find sensible xlim,ylim
if xlim is None:
xlim = [np.inf,-np.inf]
for i in range(N*M):
plt.subplot(N,M,i+1)
xlim[0] = min(xlim[0],plt.xlim()[0])
xlim[1] = max(xlim[1],plt.xlim()[1])
if ylim is None:
ylim = [np.inf,-np.inf]
for i in range(N*M):
plt.subplot(N,M,i+1)
ylim[0] = min(ylim[0],plt.ylim()[0])
ylim[1] = max(ylim[1],plt.ylim()[1])
for i in range(N*M):
plt.subplot(N,M,i+1)
plt.xlim(xlim)
plt.ylim(ylim)
if (i)%M:
plt.yticks([])
else:
removeRightTicks()
if i<(M*(N-1)):
plt.xticks([])
else:
removeUpperTicks()
def align_subplot_array(axes,xlim=None, ylim=None):
"""
Make all of the axes in the array hae the same limits, turn off unnecessary ticks
use plt.subplots() to get an array of axes
"""
#find sensible xlim,ylim
if xlim is None:
xlim = [np.inf,-np.inf]
for ax in axes.flatten():
xlim[0] = min(xlim[0],ax.get_xlim()[0])
xlim[1] = max(xlim[1],ax.get_xlim()[1])
if ylim is None:
ylim = [np.inf,-np.inf]
for ax in axes.flatten():
ylim[0] = min(ylim[0],ax.get_ylim()[0])
ylim[1] = max(ylim[1],ax.get_ylim()[1])
N,M = axes.shape
for i,ax in enumerate(axes.flatten()):
ax.set_xlim(xlim)
ax.set_ylim(ylim)
if (i)%M:
ax.set_yticks([])
else:
removeRightTicks(ax)
if i<(M*(N-1)):
ax.set_xticks([])
else:
removeUpperTicks(ax)
def x_frame1D(X,plot_limits=None,resolution=None):
"""
Internal helper function for making plots, returns a set of input values to plot as well as lower and upper limits
"""
assert X.shape[1] ==1, "x_frame1D is defined for one-dimensional inputs"
if plot_limits is None:
from ...core.parameterization.variational import VariationalPosterior
if isinstance(X, VariationalPosterior):
xmin,xmax = X.mean.min(0),X.mean.max(0)
else:
xmin,xmax = X.min(0),X.max(0)
xmin, xmax = xmin-0.2*(xmax-xmin), xmax+0.2*(xmax-xmin)
elif len(plot_limits)==2:
xmin, xmax = plot_limits
else:
raise ValueError("Bad limits for plotting")
Xnew = np.linspace(xmin,xmax,resolution or 200)[:,None]
return Xnew, xmin, xmax
def x_frame2D(X,plot_limits=None,resolution=None):
"""
Internal helper function for making plots, returns a set of input values to plot as well as lower and upper limits
"""
assert X.shape[1] ==2, "x_frame2D is defined for two-dimensional inputs"
if plot_limits is None:
xmin,xmax = X.min(0),X.max(0)
xmin, xmax = xmin-0.2*(xmax-xmin), xmax+0.2*(xmax-xmin)
elif len(plot_limits)==2:
xmin, xmax = plot_limits
else:
raise ValueError("Bad limits for plotting")
resolution = resolution or 50
xx,yy = np.mgrid[xmin[0]:xmax[0]:1j*resolution,xmin[1]:xmax[1]:1j*resolution]
Xnew = np.vstack((xx.flatten(),yy.flatten())).T
return Xnew, xx, yy, xmin, xmax

View file

@ -1,21 +1,21 @@
#===============================================================================
# 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.matplot_dep.plot_definitions 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
@ -41,14 +41,15 @@ class MatplotlibPlots(AbstractPlottingLibrary):
def __init__(self):
super(MatplotlibPlots, self).__init__()
self._defaults = defaults.__dict__
def figure(self, rows=1, cols=1, **kwargs):
fig = plt.figure(**kwargs)
def figure(self, rows=1, cols=1, gridspec_kwargs={}, tight_layout=True, **kwargs):
fig = plt.figure(tight_layout=tight_layout, **kwargs)
fig.rows = rows
fig.cols = cols
fig.gridspec = plt.GridSpec(rows, cols, **gridspec_kwargs)
return fig
def new_canvas(self, figure=None, col=1, row=1, projection='2d', xlabel=None, ylabel=None, zlabel=None, title=None, xlim=None, ylim=None, zlim=None, **kwargs):
def new_canvas(self, figure=None, row=1, col=1, projection='2d', xlabel=None, ylabel=None, zlabel=None, title=None, xlim=None, ylim=None, zlim=None, **kwargs):
if projection == '3d':
from mpl_toolkits.mplot3d import Axes3D
elif projection == '2d':
@ -56,7 +57,9 @@ class MatplotlibPlots(AbstractPlottingLibrary):
if 'ax' in kwargs:
ax = kwargs.pop('ax')
else:
if 'num' in kwargs and 'figsize' in kwargs:
if figure is not None:
fig = figure
elif 'num' in kwargs and 'figsize' in kwargs:
fig = self.figure(num=kwargs.pop('num'), figsize=kwargs.pop('figsize'))
elif 'num' in kwargs:
fig = self.figure(num=kwargs.pop('num'))
@ -64,10 +67,10 @@ class MatplotlibPlots(AbstractPlottingLibrary):
fig = self.figure(figsize=kwargs.pop('figsize'))
else:
fig = self.figure()
#if hasattr(fig, 'rows') and hasattr(fig, 'cols'):
ax = fig.add_subplot(fig.rows, fig.cols, (col,row), projection=projection)
ax = fig.add_subplot(fig.gridspec[row-1, col-1], projection=projection)
if xlim is not None: ax.set_xlim(xlim)
if ylim is not None: ax.set_ylim(ylim)
if xlabel is not None: ax.set_xlabel(xlabel)
@ -77,9 +80,9 @@ class MatplotlibPlots(AbstractPlottingLibrary):
if zlim is not None: ax.set_zlim(zlim)
if zlabel is not None: ax.set_zlabel(zlabel)
return ax, kwargs
def add_to_canvas(self, ax, plots, legend=False, title=None, **kwargs):
ax.autoscale_view()
#ax.autoscale_view()
fontdict=dict(family='sans-serif', weight='light', size=9)
if legend is True:
ax.legend(*ax.get_legend_handles_labels())
@ -88,18 +91,16 @@ class MatplotlibPlots(AbstractPlottingLibrary):
legend_ontop(ax, ncol=legend, fontdict=fontdict)
if title is not None: ax.figure.suptitle(title)
return ax
def show_canvas(self, ax, tight_layout=False, **kwargs):
if tight_layout:
ax.figure.tight_layout()
def show_canvas(self, ax):
ax.figure.canvas.draw()
return ax.figure
def scatter(self, ax, X, Y, Z=None, color=Tango.colorsHex['mediumBlue'], label=None, marker='o', **kwargs):
if Z is not None:
return ax.scatter(X, Y, c=color, zs=Z, label=label, marker=marker, **kwargs)
return ax.scatter(X, Y, c=color, label=label, marker=marker, **kwargs)
def plot(self, ax, X, Y, Z=None, color=None, label=None, **kwargs):
if Z is not None:
return ax.plot(X, Y, color=color, zs=Z, label=label, **kwargs)
@ -122,23 +123,23 @@ class MatplotlibPlots(AbstractPlottingLibrary):
if 'align' not in kwargs:
kwargs['align'] = 'center'
return ax.bar(left=x, height=height, width=width,
bottom=bottom, label=label, color=color,
bottom=bottom, label=label, color=color,
**kwargs)
def xerrorbar(self, ax, X, Y, error, color=Tango.colorsHex['mediumBlue'], label=None, **kwargs):
if not('linestyle' in kwargs or 'ls' in kwargs):
kwargs['ls'] = 'none'
#if Z is not None:
# return ax.errorbar(X, Y, Z, xerr=error, ecolor=color, label=label, **kwargs)
return ax.errorbar(X, Y, xerr=error, ecolor=color, label=label, **kwargs)
def yerrorbar(self, ax, X, Y, error, color=Tango.colorsHex['mediumBlue'], label=None, **kwargs):
if not('linestyle' in kwargs or 'ls' in kwargs):
kwargs['ls'] = 'none'
#if Z is not None:
# return ax.errorbar(X, Y, Z, yerr=error, ecolor=color, label=label, **kwargs)
return ax.errorbar(X, Y, yerr=error, ecolor=color, label=label, **kwargs)
def imshow(self, ax, X, extent=None, label=None, vmin=None, vmax=None, **imshow_kwargs):
if 'origin' not in imshow_kwargs:
imshow_kwargs['origin'] = 'lower'
@ -178,7 +179,7 @@ class MatplotlibPlots(AbstractPlottingLibrary):
if 'origin' not in imshow_kwargs:
imshow_kwargs['origin'] = 'lower'
return ImAnnotateController(ax, plot_function, extent, resolution=resolution, imshow_kwargs=imshow_kwargs or {}, **annotation_kwargs)
def contour(self, ax, X, Y, C, levels=20, label=None, **kwargs):
return ax.contour(X, Y, C, levels=np.linspace(C.min(), C.max(), levels), label=label, **kwargs)
@ -191,13 +192,13 @@ class MatplotlibPlots(AbstractPlottingLibrary):
def fill_gradient(self, canvas, X, percentiles, color=Tango.colorsHex['mediumBlue'], label=None, **kwargs):
ax = canvas
plots = []
if 'edgecolors' not in kwargs:
kwargs['edgecolors'] = 'none'
if 'facecolors' in kwargs:
color = kwargs.pop('facecolors')
if 'array' in kwargs:
array = kwargs.pop('array')
else:
@ -231,8 +232,8 @@ class MatplotlibPlots(AbstractPlottingLibrary):
# pass
a, b = tee(iterable)
next(b, None)
return zip(a, b)
return zip(a, b)
polycol = []
for y1, y2 in pairwise(percentiles):
import matplotlib.mlab as mlab
@ -244,51 +245,51 @@ class MatplotlibPlots(AbstractPlottingLibrary):
x = ma.masked_invalid(ax.convert_xunits(X))
y1 = ma.masked_invalid(ax.convert_yunits(y1))
y2 = ma.masked_invalid(ax.convert_yunits(y2))
if y1.ndim == 0:
y1 = np.ones_like(x) * y1
if y2.ndim == 0:
y2 = np.ones_like(x) * y2
if where is None:
where = np.ones(len(x), np.bool)
else:
where = np.asarray(where, np.bool)
if not (x.shape == y1.shape == y2.shape == where.shape):
raise ValueError("Argument dimensions are incompatible")
from functools import reduce
mask = reduce(ma.mask_or, [ma.getmask(a) for a in (x, y1, y2)])
if mask is not ma.nomask:
where &= ~mask
polys = []
for ind0, ind1 in mlab.contiguous_regions(where):
xslice = x[ind0:ind1]
y1slice = y1[ind0:ind1]
y2slice = y2[ind0:ind1]
if not len(xslice):
continue
N = len(xslice)
p = np.zeros((2 * N + 2, 2), np.float)
# the purpose of the next two lines is for when y2 is a
# scalar like 0 and we want the fill to go all the way
# down to 0 even if none of the y1 sample points do
start = xslice[0], y2slice[0]
end = xslice[-1], y2slice[-1]
p[0] = start
p[N + 1] = end
p[1:N + 1, 0] = xslice
p[1:N + 1, 1] = y1slice
p[N + 2:, 0] = xslice[::-1]
p[N + 2:, 1] = y2slice[::-1]
polys.append(p)
polycol.extend(polys)
from matplotlib.collections import PolyCollection

View file

@ -13,16 +13,16 @@ class SSGPLVM_plot(object):
self.model = model
self.imgsize= imgsize
assert model.Y.shape[1] == imgsize[0]*imgsize[1]
def plot_inducing(self):
fig1 = pylab.figure()
mean = self.model.posterior.mean
arr = mean.reshape(*(mean.shape[0],self.imgsize[1],self.imgsize[0]))
plot_2D_images(fig1, arr)
fig1.gca().set_title('The mean of inducing points')
fig2 = pylab.figure()
covar = self.model.posterior.covariance
plot_2D_images(fig2, covar)
fig2.gca().set_title('The variance of inducing points')

View file

@ -72,5 +72,5 @@ ard = dict(linewidth=1.2, barmode='stack')
latent = dict(colorscale='Greys', reversescale=True, zsmooth='best')
gradient = dict(colorscale='RdBu', opacity=.7)
magnification = dict(colorscale='Greys', zsmooth='best', reversescale=True)
latent_scatter = dict(marker_kwargs=dict(size='15', opacity=.7))
latent_scatter = dict(marker_kwargs=dict(size='5', opacity=.7))
# annotation = dict(fontdict=dict(family='sans-serif', weight='light', fontsize=9), zorder=.3, alpha=.7)

View file

@ -130,14 +130,15 @@ class PlotlyPlots(AbstractPlottingLibrary):
except:
#not matplotlib marker
pass
marker_kwargs = marker_kwargs or {}
marker_kwargs.setdefault('symbol', marker)
if Z is not None:
return Scatter3d(x=X, y=Y, z=Z, mode='markers',
showlegend=label is not None,
marker=Marker(color=color, colorscale=cmap, **marker_kwargs or {}),
return Scatter3d(x=X, y=Y, z=Z, mode='markers',
showlegend=label is not None,
marker=Marker(color=color, colorscale=cmap, **marker_kwargs),
name=label, **kwargs)
return Scatter(x=X, y=Y, mode='markers', showlegend=label is not None,
marker=Marker(color=color, colorscale=cmap, **marker_kwargs or {}),
return Scatter(x=X, y=Y, mode='markers', showlegend=label is not None,
marker=Marker(color=color, colorscale=cmap, **marker_kwargs or {}),
name=label, **kwargs)
def plot(self, ax, X, Y, Z=None, color=None, label=None, line_kwargs=None, **kwargs):
@ -169,10 +170,10 @@ class PlotlyPlots(AbstractPlottingLibrary):
elif X.shape[1] == 2:
marker_kwargs.setdefault('symbol', 'diamond')
opacity = kwargs.pop('opacity', .8)
return Scatter3d(x=X[:, 0], y=X[:, 1], z=np.zeros(X.shape[0]),
return Scatter3d(x=X[:, 0], y=X[:, 1], z=np.zeros(X.shape[0]),
mode='markers',
projection=dict(z=dict(show=True, opacity=opacity)),
marker=Marker(color=color, **marker_kwargs or {}),
projection=dict(z=dict(show=True, opacity=opacity)),
marker=Marker(color=color, **marker_kwargs or {}),
opacity=0,
name=label,
showlegend=label is not None, **kwargs)
@ -284,11 +285,11 @@ class PlotlyPlots(AbstractPlottingLibrary):
if color.startswith('#'):
colarray = Tango.hex2rgb(color)
opacity = .9
else:
else:
colarray = map(float(color.strip(')').split('(')[1]))
if len(colarray) == 4:
colarray, opacity = colarray[:3] ,colarray[3]
alpha = opacity*(1.-np.abs(np.linspace(-1,1,len(percentiles)-1)))
def pairwise(iterable):
@ -302,11 +303,11 @@ class PlotlyPlots(AbstractPlottingLibrary):
for i, y1, a in zip(range(len(percentiles)), percentiles, alpha):
fcolor = 'rgba({}, {}, {}, {alpha})'.format(*colarray, alpha=a)
if i == len(percentiles)/2:
polycol.append(Scatter(x=X, y=y1, fillcolor=fcolor, showlegend=True,
name=label, line=Line(width=0, smoothing=0), mode='none', fill='tonextx',
polycol.append(Scatter(x=X, y=y1, fillcolor=fcolor, showlegend=True,
name=label, line=Line(width=0, smoothing=0), mode='none', fill='tonextx',
legendgroup='density', hoverinfo='none', **kwargs))
else:
polycol.append(Scatter(x=X, y=y1, fillcolor=fcolor, showlegend=False,
name=None, line=Line(width=1, smoothing=0, color=fcolor), mode='none', fill='tonextx',
polycol.append(Scatter(x=X, y=y1, fillcolor=fcolor, showlegend=False,
name=None, line=Line(width=1, smoothing=0, color=fcolor), mode='none', fill='tonextx',
legendgroup='density', hoverinfo='none', **kwargs))
return polycol