INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Make a scatter plot between X and Y on the canvas given. the kwargs are plotting library specific kwargs! :param canvas: the plotting librarys specific canvas to plot on. :param array-like X: the inputs to plot. :param array-like Y: the outputs to plot. :param a...
def scatter(self, canvas, X, Y, Z=None, color=None, vmin=None, vmax=None, label=None, **kwargs): """ Make a scatter plot between X and Y on the canvas given. the kwargs are plotting library specific kwargs! :param canvas: the plotting librarys specific canvas to plot on...
Plot vertical bar plot centered at x with height and width of bars. The y level is at bottom. the kwargs are plotting library specific kwargs! :param array-like x: the center points of the bars :param array-like height: the height of the bars :param array-like width: t...
def barplot(self, canvas, x, height, width=0.8, bottom=0, color=None, label=None, **kwargs): """ Plot vertical bar plot centered at x with height and width of bars. The y level is at bottom. the kwargs are plotting library specific kwargs! :param array-like x: the cent...
Make an errorbar along the xaxis for points at (X,Y) on the canvas. if error is two dimensional, the lower error is error[:,0] and the upper error is error[:,1] the kwargs are plotting library specific kwargs!
def xerrorbar(self, canvas, X, Y, error, color=None, label=None, **kwargs): """ Make an errorbar along the xaxis for points at (X,Y) on the canvas. if error is two dimensional, the lower error is error[:,0] and the upper error is error[:,1] the kwargs are plotting librar...
Show the image stored in X on the canvas. The origin of the image show is (0,0), such that X[0,0] gets plotted at [0,0] of the image! the kwargs are plotting library specific kwargs!
def imshow(self, canvas, X, extent=None, label=None, vmin=None, vmax=None, **kwargs): """ Show the image stored in X on the canvas. The origin of the image show is (0,0), such that X[0,0] gets plotted at [0,0] of the image! the kwargs are plotting library specific kwarg...
This function is optional! Create an imshow controller to stream the image returned by the plot_function. There is an imshow controller written for mmatplotlib, which updates the imshow on changes in axis. The origin of the image show is (0,0), such that X[0,0] gets p...
def imshow_interact(self, canvas, plot_function, extent=None, label=None, vmin=None, vmax=None, **kwargs): """ This function is optional! Create an imshow controller to stream the image returned by the plot_function. There is an imshow controller written for mmatplotlib, which...
Make a contour plot at (X, Y) with heights/colors stored in C on the canvas. if Z is not None: make 3d contour plot at (X, Y, Z) with heights/colors stored in C on the canvas. the kwargs are plotting library specific kwargs!
def contour(self, canvas, X, Y, C, Z=None, color=None, label=None, **kwargs): """ Make a contour plot at (X, Y) with heights/colors stored in C on the canvas. if Z is not None: make 3d contour plot at (X, Y, Z) with heights/colors stored in C on the canvas. the kwargs a...
Fill along the xaxis between lower and upper. the kwargs are plotting library specific kwargs!
def fill_between(self, canvas, X, lower, upper, color=None, label=None, **kwargs): """ Fill along the xaxis between lower and upper. the kwargs are plotting library specific kwargs! """ raise NotImplementedError("Implement all plot functions in AbstractPlottingLibrary in...
Randomize the model. Make this draw from the prior if one exists, else draw from given random generator :param rand_gen: np random number generator which takes args and kwargs :param flaot loc: loc parameter for random number generator :param float scale: scale parameter for random number generator ...
def randomize(self, rand_gen=None, *args, **kwargs): """ Randomize the model. Make this draw from the prior if one exists, else draw from given random generator :param rand_gen: np random number generator which takes args and kwargs :param flaot loc: loc parameter for random number generator :p...
Covariance between observed values. s and t are one domain of the integral (i.e. the integral between s and t) sprime and tprime are another domain of the integral (i.e. the integral between sprime and tprime) We're interested in how correlated these two integrals are. Note: We've not...
def k_xx(self,t,tprime,s,sprime,l): """Covariance between observed values. s and t are one domain of the integral (i.e. the integral between s and t) sprime and tprime are another domain of the integral (i.e. the integral between sprime and tprime) We're interested in how correlated th...
Calculates K_xx without the variance term
def calc_K_xx_wo_variance(self,X): """Calculates K_xx without the variance term""" K_xx = np.ones([X.shape[0],X.shape[0]]) #ones now as a product occurs over each dimension for i,x in enumerate(X): for j,x2 in enumerate(X): for il,l in enumerate(self.lengthscale): ...
I've used the fact that we call this method for K_ff when finding the covariance as a hack so I know if I should return K_ff or K_xx. In this case we're returning K_ff!! $K_{ff}^{post} = K_{ff} - K_{fx} K_{xx}^{-1} K_{xf}$
def Kdiag(self, X): """I've used the fact that we call this method for K_ff when finding the covariance as a hack so I know if I should return K_ff or K_xx. In this case we're returning K_ff!! $K_{ff}^{post} = K_{ff} - K_{fx} K_{xx}^{-1} K_{xf}$""" K_ff = np.ones(X.shape[0]) for ...
Overwrite checkgrad method to check whole block instead of looping through Shows diagnostics using matshow instead :param verbose: If True, print a "full" checking of each parameter :type verbose: bool :param step: The size of the step around which to linearise the objective :t...
def checkgrad(self, target_param=None, verbose=False, step=1e-6, tolerance=1e-3, block_indices=None, plot=False): """ Overwrite checkgrad method to check whole block instead of looping through Shows diagnostics using matshow instead :param verbose: If True, print a "full" checking of e...
Checkgrad a block matrix
def checkgrad_block(self, analytic_hess, numeric_hess, verbose=False, step=1e-6, tolerance=1e-3, block_indices=None, plot=False): """ Checkgrad a block matrix """ if analytic_hess.dtype is np.dtype('object'): #Make numeric hessian also into a block matrix real_siz...
Derivative of Kernel function wrt variance applied on inputs X and X2. In the stationary case there is an inner function depending on the distances from X to X2, called r. dKd_dVar(X, X2) = dKdVar_of_r((X-X2)**2)
def dKd_dVar(self, X, X2=None): """ Derivative of Kernel function wrt variance applied on inputs X and X2. In the stationary case there is an inner function depending on the distances from X to X2, called r. dKd_dVar(X, X2) = dKdVar_of_r((X-X2)**2) """ r = self._scaled_dist(X, X2) return self.dKdVar_of...
Derivate of Kernel function wrt lengthscale applied on inputs X and X2. In the stationary case there is an inner function depending on the distances from X to X2, called r. dKd_dLen(X, X2) = dKdLen_of_r((X-X2)**2)
def dKd_dLen(self, X, dimension, lengthscale, X2=None): """ Derivate of Kernel function wrt lengthscale applied on inputs X and X2. In the stationary case there is an inner function depending on the distances from X to X2, called r. dKd_dLen(X, X2) = dKdLen_of_r((X-X2)**2) """ r = self._scaled_dist(X, X2...
Compute derivative of kernel for dimension wrt lengthscale Computation of derivative changes when lengthscale corresponds to the dimension of the kernel whose derivate is being computed.
def dKdLen_of_r(self, r, dimCheck, lengthscale): """ Compute derivative of kernel for dimension wrt lengthscale Computation of derivative changes when lengthscale corresponds to the dimension of the kernel whose derivate is being computed. """ if (dimCheck == True): return (self.variance**(float(1)/self...
Instantiate an object of a derived class using the information in input_dict (built by the to_dict method of the derived class). More specifically, after reading the derived class from input_dict, it calls the method _build_from_input_dict of the derived class. Note: This method should n...
def from_dict(input_dict): """ Instantiate an object of a derived class using the information in input_dict (built by the to_dict method of the derived class). More specifically, after reading the derived class from input_dict, it calls the method _build_from_input_dict of the de...
Calculation of the log predictive density .. math: p(y_{*}|D) = p(y_{*}|f_{*})p(f_{*}|\mu_{*}\\sigma^{2}_{*}) :param y_test: test observations (y_{*}) :type y_test: (Nx1) array :param mu_star: predictive mean of gaussian p(f_{*}|mu_{*}, var_{*}) :type mu_star: (Nx1)...
def log_predictive_density(self, y_test, mu_star, var_star, Y_metadata=None): """ Calculation of the log predictive density .. math: p(y_{*}|D) = p(y_{*}|f_{*})p(f_{*}|\mu_{*}\\sigma^{2}_{*}) :param y_test: test observations (y_{*}) :type y_test: (Nx1) array ...
Calculation of the log predictive density via sampling .. math: log p(y_{*}|D) = log 1/num_samples prod^{S}_{s=1} p(y_{*}|f_{*s}) f_{*s} ~ p(f_{*}|\mu_{*}\\sigma^{2}_{*}) :param y_test: test observations (y_{*}) :type y_test: (Nx1) array :param mu_star: predicti...
def log_predictive_density_sampling(self, y_test, mu_star, var_star, Y_metadata=None, num_samples=1000): """ Calculation of the log predictive density via sampling .. math: log p(y_{*}|D) = log 1/num_samples prod^{S}_{s=1} p(y_{*}|f_{*s}) f_{*s} ~ p(f_{*}|\mu_{*}\\sigma^...
Calculation of moments using quadrature :param obs: observed output :param tau: cavity distribution 1st natural parameter (precision) :param v: cavity distribution 2nd natural paramenter (mu*precision)
def moments_match_ep(self,obs,tau,v,Y_metadata_i=None): """ Calculation of moments using quadrature :param obs: observed output :param tau: cavity distribution 1st natural parameter (precision) :param v: cavity distribution 2nd natural paramenter (mu*precision) """ ...
Use Gauss-Hermite Quadrature to compute E_p(f) [ log p(y|f) ] d/dm E_p(f) [ log p(y|f) ] d/dv E_p(f) [ log p(y|f) ] where p(f) is a Gaussian with mean m and variance v. The shapes of Y, m and v should match. if no gh_points are passed, we construct them using defualt ...
def variational_expectations(self, Y, m, v, gh_points=None, Y_metadata=None): """ Use Gauss-Hermite Quadrature to compute E_p(f) [ log p(y|f) ] d/dm E_p(f) [ log p(y|f) ] d/dv E_p(f) [ log p(y|f) ] where p(f) is a Gaussian with mean m and variance v. The shapes...
Quadrature calculation of the predictive mean: E(Y_star|Y) = E( E(Y_star|f_star, Y) ) :param mu: mean of posterior :param sigma: standard deviation of posterior
def predictive_mean(self, mu, variance, Y_metadata=None): """ Quadrature calculation of the predictive mean: E(Y_star|Y) = E( E(Y_star|f_star, Y) ) :param mu: mean of posterior :param sigma: standard deviation of posterior """ #conditional_mean: the edpected value of y ...
Approximation to the predictive variance: V(Y_star) The following variance decomposition is used: V(Y_star) = E( V(Y_star|f_star)**2 ) + V( E(Y_star|f_star) )**2 :param mu: mean of posterior :param sigma: standard deviation of posterior :predictive_mean: output's predictive mea...
def predictive_variance(self, mu,variance, predictive_mean=None, Y_metadata=None): """ Approximation to the predictive variance: V(Y_star) The following variance decomposition is used: V(Y_star) = E( V(Y_star|f_star)**2 ) + V( E(Y_star|f_star) )**2 :param mu: mean of posterior ...
Evaluates the link function link(f) then computes the likelihood (pdf) using it .. math: p(y|\\lambda(f)) :param f: latent variables f :type f: Nx1 array :param y: data :type y: Nx1 array :param Y_metadata: Y_metadata which is not used in student t distribut...
def pdf(self, f, y, Y_metadata=None): """ Evaluates the link function link(f) then computes the likelihood (pdf) using it .. math: p(y|\\lambda(f)) :param f: latent variables f :type f: Nx1 array :param y: data :type y: Nx1 array :param Y_met...
Convenience function that can overridden for functions where this could be computed more efficiently
def logpdf_sum(self, f, y, Y_metadata=None): """ Convenience function that can overridden for functions where this could be computed more efficiently """ return np.sum(self.logpdf(f, y, Y_metadata=Y_metadata))
Evaluates the link function link(f) then computes the log likelihood (log pdf) using it .. math: \\log p(y|\\lambda(f)) :param f: latent variables f :type f: Nx1 array :param y: data :type y: Nx1 array :param Y_metadata: Y_metadata which is not used in stude...
def logpdf(self, f, y, Y_metadata=None): """ Evaluates the link function link(f) then computes the log likelihood (log pdf) using it .. math: \\log p(y|\\lambda(f)) :param f: latent variables f :type f: Nx1 array :param y: data :type y: Nx1 array ...
Evaluates the link function link(f) then computes the derivative of log likelihood using it Uses the Faa di Bruno's formula for the chain rule .. math:: \\frac{d\\log p(y|\\lambda(f))}{df} = \\frac{d\\log p(y|\\lambda(f))}{d\\lambda(f)}\\frac{d\\lambda(f)}{df} :param f: latent vari...
def dlogpdf_df(self, f, y, Y_metadata=None): """ Evaluates the link function link(f) then computes the derivative of log likelihood using it Uses the Faa di Bruno's formula for the chain rule .. math:: \\frac{d\\log p(y|\\lambda(f))}{df} = \\frac{d\\log p(y|\\lambda(f))}{d\\...
Evaluates the link function link(f) then computes the second derivative of log likelihood using it Uses the Faa di Bruno's formula for the chain rule .. math:: \\frac{d^{2}\\log p(y|\\lambda(f))}{df^{2}} = \\frac{d^{2}\\log p(y|\\lambda(f))}{d^{2}\\lambda(f)}\\left(\\frac{d\\lambda(f)}{df}\...
def d2logpdf_df2(self, f, y, Y_metadata=None): """ Evaluates the link function link(f) then computes the second derivative of log likelihood using it Uses the Faa di Bruno's formula for the chain rule .. math:: \\frac{d^{2}\\log p(y|\\lambda(f))}{df^{2}} = \\frac{d^{2}\\log ...
Evaluates the link function link(f) then computes the third derivative of log likelihood using it Uses the Faa di Bruno's formula for the chain rule .. math:: \\frac{d^{3}\\log p(y|\\lambda(f))}{df^{3}} = \\frac{d^{3}\\log p(y|\\lambda(f)}{d\\lambda(f)^{3}}\\left(\\frac{d\\lambda(f)}{df}\\r...
def d3logpdf_df3(self, f, y, Y_metadata=None): """ Evaluates the link function link(f) then computes the third derivative of log likelihood using it Uses the Faa di Bruno's formula for the chain rule .. math:: \\frac{d^{3}\\log p(y|\\lambda(f))}{df^{3}} = \\frac{d^{3}\\log p...
TODO: Doc strings
def dlogpdf_dtheta(self, f, y, Y_metadata=None): """ TODO: Doc strings """ if self.size > 0: if self.not_block_really: raise NotImplementedError("Need to make a decorator for this!") if isinstance(self.gp_link, link_functions.Identity): ...
TODO: Doc strings
def dlogpdf_df_dtheta(self, f, y, Y_metadata=None): """ TODO: Doc strings """ if self.size > 0: if self.not_block_really: raise NotImplementedError("Need to make a decorator for this!") if isinstance(self.gp_link, link_functions.Identity): ...
TODO: Doc strings
def d2logpdf_df2_dtheta(self, f, y, Y_metadata=None): """ TODO: Doc strings """ if self.size > 0: if self.not_block_really: raise NotImplementedError("Need to make a decorator for this!") if isinstance(self.gp_link, link_functions.Identity): ...
Compute mean, variance of the predictive distibution. :param mu: mean of the latent variable, f, of posterior :param var: variance of the latent variable, f, of posterior :param full_cov: whether to use the full covariance or just the diagonal :type full_cov: Boolean
def predictive_values(self, mu, var, full_cov=False, Y_metadata=None): """ Compute mean, variance of the predictive distibution. :param mu: mean of the latent variable, f, of posterior :param var: variance of the latent variable, f, of posterior :param full_cov: whether to use...
Simple implementation of Metropolis sampling algorithm Will run a parallel chain for each input dimension (treats each f independently) Thus assumes f*_1 independant of f*_2 etc. :param num_samples: Number of samples to take :param fNew: f at which to sample around :param start...
def MCMC_pdf_samples(self, fNew, num_samples=1000, starting_loc=None, stepsize=0.1, burn_in=1000, Y_metadata=None): """ Simple implementation of Metropolis sampling algorithm Will run a parallel chain for each input dimension (treats each f independently) Thus assumes f*_1 independant o...
Compute psi-statistics for ss-linear kernel
def psicomputations(variance, Z, variational_posterior, return_psi2_n=False): """ Compute psi-statistics for ss-linear kernel """ # here are the "statistics" for psi0, psi1 and psi2 # Produced intermediate results: # psi0 N # psi1 NxM # psi2 MxM mu = variational_posterior.me...
Z - MxQ mu - NxQ S - NxQ gamma - NxQ
def _psi2computations(dL_dpsi2, variance, Z, mu, S, gamma): """ Z - MxQ mu - NxQ S - NxQ gamma - NxQ """ # here are the "statistics" for psi1 and psi2 # Produced intermediate results: # _psi2_dvariance Q # _psi2_dZ MxQ # _psi2_dgamma NxQ # _psi2_d...
Posterior mean $$ K_{xx}v v := \texttt{Woodbury vector} $$
def mean(self): """ Posterior mean $$ K_{xx}v v := \texttt{Woodbury vector} $$ """ if self._mean is None: self._mean = np.dot(self._K, self.woodbury_vector) return self._mean
Posterior covariance $$ K_{xx} - K_{xx}W_{xx}^{-1}K_{xx} W_{xx} := \texttt{Woodbury inv} $$
def covariance(self): """ Posterior covariance $$ K_{xx} - K_{xx}W_{xx}^{-1}K_{xx} W_{xx} := \texttt{Woodbury inv} $$ """ if self._covariance is None: # LiK, _ = dtrtrs(self.woodbury_chol, self._K, lower=1) self._covariance = ( ...
Computes the posterior covariance between points. :param kern: GP kernel :param X: current input observations :param X1: some input observations :param X2: other input observations
def covariance_between_points(self, kern, X, X1, X2): """ Computes the posterior covariance between points. :param kern: GP kernel :param X: current input observations :param X1: some input observations :param X2: other input observations """ # ndim == 3 ...
Inverse of posterior covariance
def precision(self): """ Inverse of posterior covariance """ if self._precision is None: cov = np.atleast_3d(self.covariance) self._precision = np.zeros(cov.shape) # if one covariance per dimension for p in range(cov.shape[-1]): self._...
return $L_{W}$ where L is the lower triangular Cholesky decomposition of the Woodbury matrix $$ L_{W}L_{W}^{\top} = W^{-1} W^{-1} := \texttt{Woodbury inv} $$
def woodbury_chol(self): """ return $L_{W}$ where L is the lower triangular Cholesky decomposition of the Woodbury matrix $$ L_{W}L_{W}^{\top} = W^{-1} W^{-1} := \texttt{Woodbury inv} $$ """ if self._woodbury_chol is None: # compute woodbury ch...
The inverse of the woodbury matrix, in the gaussian likelihood case it is defined as $$ (K_{xx} + \Sigma_{xx})^{-1} \Sigma_{xx} := \texttt{Likelihood.variance / Approximate likelihood covariance} $$
def woodbury_inv(self): """ The inverse of the woodbury matrix, in the gaussian likelihood case it is defined as $$ (K_{xx} + \Sigma_{xx})^{-1} \Sigma_{xx} := \texttt{Likelihood.variance / Approximate likelihood covariance} $$ """ if self._woodbury_inv is ...
Woodbury vector in the gaussian likelihood case only is defined as $$ (K_{xx} + \Sigma)^{-1}Y \Sigma := \texttt{Likelihood.variance / Approximate likelihood covariance} $$
def woodbury_vector(self): """ Woodbury vector in the gaussian likelihood case only is defined as $$ (K_{xx} + \Sigma)^{-1}Y \Sigma := \texttt{Likelihood.variance / Approximate likelihood covariance} $$ """ if self._woodbury_vector is None: sel...
Cholesky of the prior covariance K
def K_chol(self): """ Cholesky of the prior covariance K """ if self._K_chol is None: self._K_chol = jitchol(self._K) return self._K_chol
Compute the diagonal of the covariance matrix for X.
def Kdiag(self, X, target): """Compute the diagonal of the covariance matrix for X.""" np.add(target, self.variance, target)
Derivative of the covariance with respect to the parameters.
def _param_grad_helper(self, dL_dK, X, X2, target): """Derivative of the covariance with respect to the parameters.""" self._K_computations(X, X2) self._dK_computations(dL_dK) if X2==None: gmapping = self.mapping.df_dtheta(2*self._dL_dl[:, None], X) else: ...
Derivative of the covariance matrix with respect to X.
def gradients_X(self, dL_dK, X, X2, target): """Derivative of the covariance matrix with respect to X.""" # First account for gradients arising from presence of X in exponent. self._K_computations(X, X2) if X2 is None: _K_dist = 2*(X[:, None, :] - X[None, :, :]) else:...
Pre-computations for the covariance function (used both when computing the covariance and its gradients). Here self._dK_dvar and self._K_dist2 are updated.
def _K_computations(self, X, X2=None): """Pre-computations for the covariance function (used both when computing the covariance and its gradients). Here self._dK_dvar and self._K_dist2 are updated.""" self._lengthscales=self.mapping.f(X) self._lengthscales2=np.square(self._lengthscales) ...
Pre-computations for the gradients of the covaraince function. Here the gradient of the covariance with respect to all the individual lengthscales is computed. :param dL_dK: the gradient of the objective with respect to the covariance function. :type dL_dK: ndarray
def _dK_computations(self, dL_dK): """Pre-computations for the gradients of the covaraince function. Here the gradient of the covariance with respect to all the individual lengthscales is computed. :param dL_dK: the gradient of the objective with respect to the covariance function. :type dL_dK: ...
If summize is true, we want to get the summerized view of the sensitivities, otherwise put everything into an array with shape (#kernels, input_dim) in the order of appearance of the kernels in the parameterized object.
def input_sensitivity(self, summarize=True): """ If summize is true, we want to get the summerized view of the sensitivities, otherwise put everything into an array with shape (#kernels, input_dim) in the order of appearance of the kernels in the parameterized object. """ ...
Simulate some data drawn from a matern covariance and a periodic exponential for use in MRD demos.
def _simulate_matern(D1, D2, D3, N, num_inducing, plot_sim=False): """Simulate some data drawn from a matern covariance and a periodic exponential for use in MRD demos.""" Q_signal = 4 import GPy import numpy as np np.random.seed(3000) k = GPy.kern.Matern32(Q_signal, 1., lengthscale=(np.random....
Simulate some data drawn from sine and cosine for use in demos of MRD
def _simulate_sincos(D1, D2, D3, N, num_inducing, plot_sim=False): """Simulate some data drawn from sine and cosine for use in demos of MRD""" _np.random.seed(1234) x = _np.linspace(0, 4 * _np.pi, N)[:, None] s1 = _np.vectorize(lambda x: _np.sin(x)) s2 = _np.vectorize(lambda x: _np.cos(x)) s3 =...
Interactive visualisation of the Stick Man data from Ohio State University with the Bayesian GPLVM.
def stick_bgplvm(model=None, optimize=True, verbose=True, plot=True): """Interactive visualisation of the Stick Man data from Ohio State University with the Bayesian GPLVM.""" from GPy.models import BayesianGPLVM from matplotlib import pyplot as plt import numpy as np import GPy import pods ...
Get the LL of a combined set of clusters, ignoring time series offsets. Get the log likelihood of a cluster without worrying about the fact different time series are offset. We're using it here really for those cases in which we only have one cluster to get the loglikelihood of. arguments: ...
def get_log_likelihood(inputs,data,clust): """Get the LL of a combined set of clusters, ignoring time series offsets. Get the log likelihood of a cluster without worrying about the fact different time series are offset. We're using it here really for those cases in which we only have one cluster to...
Get the log likelihood of a combined set of clusters, fitting the offsets arguments: inputs -- the 'X's in a list, one item per cluster data -- the 'Y's in a list, one item per cluster clust -- list of clusters to use returns a tuple: log likelihood and the offset
def get_log_likelihood_offset(inputs,data,clust): """Get the log likelihood of a combined set of clusters, fitting the offsets arguments: inputs -- the 'X's in a list, one item per cluster data -- the 'Y's in a list, one item per cluster clust -- list of clusters to use returns a tuple...
Clusters data Using the new offset model, this method uses a greedy algorithm to cluster the data. It starts with all the data points in separate clusters and tests whether combining them increases the overall log-likelihood (LL). It then iteratively joins pairs of clusters which cause the greatest...
def cluster(data,inputs,verbose=False): """Clusters data Using the new offset model, this method uses a greedy algorithm to cluster the data. It starts with all the data points in separate clusters and tests whether combining them increases the overall log-likelihood (LL). It then iteratively j...
Return covariance between X and X2.
def K(self, X, X2, target): """Return covariance between X and X2.""" if (X2 is None) or (X2 is X): target[np.diag_indices_from(target)] += self._Kdiag(X)
Derivative of the covariance with respect to the parameters.
def _param_grad_helper(self, dL_dK, X, X2, target): """Derivative of the covariance with respect to the parameters.""" if (X2 is None) or (X2 is X): dL_dKdiag = dL_dK.flat[::dL_dK.shape[0]+1] self.dKdiag_dtheta(dL_dKdiag, X, target)
Gradient of diagonal of covariance with respect to parameters.
def dKdiag_dtheta(self, dL_dKdiag, X, target): """Gradient of diagonal of covariance with respect to parameters.""" target += 2.*self.mapping.df_dtheta(dL_dKdiag[:, None]*self.mapping.f(X), X)
Derivative of the covariance matrix with respect to X.
def gradients_X(self, dL_dK, X, X2, target): """Derivative of the covariance matrix with respect to X.""" if X2==None or X2 is X: dL_dKdiag = dL_dK.flat[::dL_dK.shape[0]+1] self.dKdiag_dX(dL_dKdiag, X, target)
Gradient of diagonal of covariance with respect to X.
def dKdiag_dX(self, dL_dKdiag, X, target): """Gradient of diagonal of covariance with respect to X.""" target += 2.*self.mapping.df_dX(dL_dKdiag[:, None], X)*self.mapping.f(X)
Log Likelihood Function given link(f) .. math:: :param link_f: latent variables (link(f)) :type link_f: Nx1 array :param y: data :type y: Nx1 array :param Y_metadata: includes censoring information in dictionary key 'censored' :returns: likelihood evaluated for...
def logpdf_link(self, link_f, y, Y_metadata=None): """ Log Likelihood Function given link(f) .. math:: :param link_f: latent variables (link(f)) :type link_f: Nx1 array :param y: data :type y: Nx1 array :param Y_metadata: includes censoring information ...
Gradient of the log likelihood function at y, given link(f) w.r.t link(f) .. math:: :param link_f: latent variables (f) :type link_f: Nx1 array :param y: data :type y: Nx1 array :param Y_metadata: includes censoring information in dictionary key 'censored' :retu...
def dlogpdf_dlink(self, link_f, y, Y_metadata=None): """ Gradient of the log likelihood function at y, given link(f) w.r.t link(f) .. math:: :param link_f: latent variables (f) :type link_f: Nx1 array :param y: data :type y: Nx1 array :param Y_metadata: ...
Hessian at y, given link(f), w.r.t link(f) i.e. second derivative logpdf at y given link(f_i) and link(f_j) w.r.t link(f_i) and link(f_j) The hessian will be 0 unless i == j .. math:: :param link_f: latent variables link(f) :type link_f: Nx1 array :param y: data ...
def d2logpdf_dlink2(self, link_f, y, Y_metadata=None): """ Hessian at y, given link(f), w.r.t link(f) i.e. second derivative logpdf at y given link(f_i) and link(f_j) w.r.t link(f_i) and link(f_j) The hessian will be 0 unless i == j .. math:: :param link_f: latent var...
Third order derivative log-likelihood function at y given link(f) w.r.t link(f) .. math:: :param link_f: latent variables link(f) :type link_f: Nx1 array :param y: data :type y: Nx1 array :param Y_metadata: includes censoring information in dictionary key 'censored' ...
def d3logpdf_dlink3(self, link_f, y, Y_metadata=None): """ Third order derivative log-likelihood function at y given link(f) w.r.t link(f) .. math:: :param link_f: latent variables link(f) :type link_f: Nx1 array :param y: data :type y: Nx1 array :param...
Gradient of the log-likelihood function at y given f, w.r.t shape parameter .. math:: :param inv_link_f: latent variables link(f) :type inv_link_f: Nx1 array :param y: data :type y: Nx1 array :param Y_metadata: includes censoring information in dictionary key 'censored'...
def dlogpdf_link_dr(self, inv_link_f, y, Y_metadata=None): """ Gradient of the log-likelihood function at y given f, w.r.t shape parameter .. math:: :param inv_link_f: latent variables link(f) :type inv_link_f: Nx1 array :param y: data :type y: Nx1 array ...
Gradient of the hessian (d2logpdf_dlink2) w.r.t shape parameter .. math:: :param inv_link_f: latent variables link(f) :type inv_link_f: Nx1 array :param y: data :type y: Nx1 array :param Y_metadata: includes censoring information in dictionary key 'censored' :re...
def d2logpdf_dlink2_dr(self, inv_link_f, y, Y_metadata=None): """ Gradient of the hessian (d2logpdf_dlink2) w.r.t shape parameter .. math:: :param inv_link_f: latent variables link(f) :type inv_link_f: Nx1 array :param y: data :type y: Nx1 array :param Y...
Optimize the model parameters through a pre-defined protocol. :param int max_iters: the maximum number of iterations. :param boolean verbose: print the progress of optimization or not.
def optimize_auto(self,max_iters=10000,verbose=True): """ Optimize the model parameters through a pre-defined protocol. :param int max_iters: the maximum number of iterations. :param boolean verbose: print the progress of optimization or not. """ self.Z.fix(warning=False...
Function for stably computing the log of difference of two erfs in a numerically stable manner. :param x1 : argument of the positive erf :type x1: ndarray :param x2 : argument of the negative erf :type x2: ndarray :return: tuple containing (log(abs(erf(x1) - erf(x2))), sign(erf(x1) - erf(x2))) ...
def ln_diff_erfs(x1, x2, return_sign=False): """Function for stably computing the log of difference of two erfs in a numerically stable manner. :param x1 : argument of the positive erf :type x1: ndarray :param x2 : argument of the negative erf :type x2: ndarray :return: tuple containing (log(abs...
Returns a Posterior class containing essential quantities of the posterior
def inference(self, kern, X, likelihood, Y, mean_function=None, Y_metadata=None, K=None, variance=None, Z_tilde=None): """ Returns a Posterior class containing essential quantities of the posterior """ if mean_function is None: m = 0 else: m = mean_functi...
Leave one out error as found in "Bayesian leave-one-out cross-validation approximations for Gaussian latent variable models" Vehtari et al. 2014.
def LOO(self, kern, X, Y, likelihood, posterior, Y_metadata=None, K=None): """ Leave one out error as found in "Bayesian leave-one-out cross-validation approximations for Gaussian latent variable models" Vehtari et al. 2014. """ g = posterior.woodbury_vector c = p...
Leave one out log predictive density as found in "Bayesian leave-one-out cross-validation approximations for Gaussian latent variable models" Vehtari et al. 2014.
def LOO(self, kern, X, Y, likelihood, posterior, Y_metadata=None, K=None, f_hat=None, W=None, Ki_W_i=None): """ Leave one out log predictive density as found in "Bayesian leave-one-out cross-validation approximations for Gaussian latent variable models" Vehtari et al. 2014. """ ...
Returns a Posterior class containing essential quantities of the posterior
def inference(self, kern, X, likelihood, Y, mean_function=None, Y_metadata=None): """ Returns a Posterior class containing essential quantities of the posterior """ assert mean_function is None, "inference with a mean function not implemented" # Compute K K = kern.K(X) ...
Rasmussen's numerically stable mode finding For nomenclature see Rasmussen & Williams 2006 Influenced by GPML (BSD) code, all errors are our own :param K: Covariance matrix evaluated at locations X :type K: NxD matrix :param Y: The data :type Y: np.ndarray :param...
def rasm_mode(self, K, Y, likelihood, Ki_f_init, Y_metadata=None, *args, **kwargs): """ Rasmussen's numerically stable mode finding For nomenclature see Rasmussen & Williams 2006 Influenced by GPML (BSD) code, all errors are our own :param K: Covariance matrix evaluated at locat...
At the mode, compute the hessian and effective covariance matrix. returns: logZ : approximation to the marginal likelihood woodbury_inv : variable required for calculating the approximation to the covariance matrix dL_dthetaL : array of derivatives (1 x num_kernel_params) ...
def mode_computations(self, f_hat, Ki_f, K, Y, likelihood, kern, Y_metadata): """ At the mode, compute the hessian and effective covariance matrix. returns: logZ : approximation to the marginal likelihood woodbury_inv : variable required for calculating the approximation to the...
Rasmussen suggests the use of a numerically stable positive definite matrix B Which has a positive diagonal elements and can be easily inverted :param K: Prior Covariance matrix evaluated at locations X :type K: NxN matrix :param W: Negative hessian at a point (diagonal matrix) ...
def _compute_B_statistics(self, K, W, log_concave, *args, **kwargs): """ Rasmussen suggests the use of a numerically stable positive definite matrix B Which has a positive diagonal elements and can be easily inverted :param K: Prior Covariance matrix evaluated at locations X :ty...
Rasmussen suggests the use of a numerically stable positive definite matrix B Which has a positive diagonal element and can be easyily inverted :param K: Prior Covariance matrix evaluated at locations X :type K: NxN matrix :param W: Negative hessian at a point (diagonal matrix) ...
def _compute_B_statistics(self, K, W, log_concave, *args, **kwargs): """ Rasmussen suggests the use of a numerically stable positive definite matrix B Which has a positive diagonal element and can be easyily inverted :param K: Prior Covariance matrix evaluated at locations X :ty...
Given the derivative of an objective fn with respect to the cholesky L, compute the derivate with respect to the original matrix K, defined as K = LL^T where L was obtained by Cholesky decomposition
def _backprop_gradient_pure(dL, L): """ Given the derivative of an objective fn with respect to the cholesky L, compute the derivate with respect to the original matrix K, defined as K = LL^T where L was obtained by Cholesky decomposition """ dL_dK = np.tril(dL).copy() N = L.shape[...
Work out which indexes of the flatteneed array should be fixed if we want the cholesky to represent a low rank matrix
def indexes_to_fix_for_low_rank(rank, size): """ Work out which indexes of the flatteneed array should be fixed if we want the cholesky to represent a low rank matrix """ #first we'll work out what to keep, and the do the set difference. #here are the indexes of the first column, which are the ...
Likelihood function given inverse link of f. .. math:: p(y_{i}|\\lambda(f_{i})) = \\lambda(f_{i})^{y_{i}}(1-f_{i})^{1-y_{i}} :param inv_link_f: latent variables inverse link of f. :type inv_link_f: Nx1 array :param y: data :type y: Nx1 array :param Y_metadat...
def pdf_link(self, inv_link_f, y, Y_metadata): """ Likelihood function given inverse link of f. .. math:: p(y_{i}|\\lambda(f_{i})) = \\lambda(f_{i})^{y_{i}}(1-f_{i})^{1-y_{i}} :param inv_link_f: latent variables inverse link of f. :type inv_link_f: Nx1 array ...
Log Likelihood function given inverse link of f. .. math:: \\ln p(y_{i}|\\lambda(f_{i})) = y_{i}\\log\\lambda(f_{i}) + (1-y_{i})\\log (1-f_{i}) :param inv_link_f: latent variables inverse link of f. :type inv_link_f: Nx1 array :param y: data :type y: Nx1 array ...
def logpdf_link(self, inv_link_f, y, Y_metadata=None): """ Log Likelihood function given inverse link of f. .. math:: \\ln p(y_{i}|\\lambda(f_{i})) = y_{i}\\log\\lambda(f_{i}) + (1-y_{i})\\log (1-f_{i}) :param inv_link_f: latent variables inverse link of f. :type in...
Gradient of the pdf at y, given inverse link of f w.r.t inverse link of f. .. math:: \\frac{d^{2}\\ln p(y_{i}|\\lambda(f_{i}))}{d\\lambda(f)^{2}} = \\frac{y_{i}}{\\lambda(f)} - \\frac{(N-y_{i})}{(1-\\lambda(f))} :param inv_link_f: latent variables inverse link of f. :type inv_link_...
def dlogpdf_dlink(self, inv_link_f, y, Y_metadata=None): """ Gradient of the pdf at y, given inverse link of f w.r.t inverse link of f. .. math:: \\frac{d^{2}\\ln p(y_{i}|\\lambda(f_{i}))}{d\\lambda(f)^{2}} = \\frac{y_{i}}{\\lambda(f)} - \\frac{(N-y_{i})}{(1-\\lambda(f))} :...
Returns a set of samples of observations based on a given value of the latent variable. :param gp: latent variable
def samples(self, gp, Y_metadata=None, **kw): """ Returns a set of samples of observations based on a given value of the latent variable. :param gp: latent variable """ orig_shape = gp.shape gp = gp.flatten() N = Y_metadata['trials'] Ysim = np.random.bino...
Return image data from Netpbm file as numpy array. `args` and `kwargs` are arguments to NetpbmFile.asarray(). Examples -------- >>> image = imread('_tmp.pgm')
def imread(filename, *args, **kwargs): """Return image data from Netpbm file as numpy array. `args` and `kwargs` are arguments to NetpbmFile.asarray(). Examples -------- >>> image = imread('_tmp.pgm') """ try: netpbm = NetpbmFile(filename) image = netpbm.asarray() fina...
Write image data to Netpbm file. Examples -------- >>> image = numpy.array([[0, 1],[65534, 65535]], dtype=numpy.uint16) >>> imsave('_tmp.pgm', image)
def imsave(filename, data, maxval=None, pam=False): """Write image data to Netpbm file. Examples -------- >>> image = numpy.array([[0, 1],[65534, 65535]], dtype=numpy.uint16) >>> imsave('_tmp.pgm', image) """ try: netpbm = NetpbmFile(data, maxval=maxval) netpbm.write(filena...
Return image data from file as numpy array.
def asarray(self, copy=True, cache=False, **kwargs): """Return image data from file as numpy array.""" data = self._data if data is None: data = self._read_data(self._fh, **kwargs) if cache: self._data = data else: return data ...
Write instance to file.
def write(self, arg, **kwargs): """Write instance to file.""" if hasattr(arg, 'seek'): self._tofile(arg, **kwargs) else: with open(arg, 'wb') as fid: self._tofile(fid, **kwargs)
Close open file. Future asarray calls might fail.
def close(self): """Close open file. Future asarray calls might fail.""" if self._filename and self._fh: self._fh.close() self._fh = None
Initialize instance from open file.
def _fromfile(self, fh): """Initialize instance from open file.""" fh.seek(0) data = fh.read(4096) if (len(data) < 7) or not (b'0' < data[1:2] < b'8'): raise ValueError("Not a Netpbm file:\n%s" % data[:32]) try: self._read_pam_header(data) except E...
Read PAM header and initialize instance.
def _read_pam_header(self, data): """Read PAM header and initialize instance.""" regroups = re.search( b"(^P7[\n\r]+(?:(?:[\n\r]+)|(?:#.*)|" b"(HEIGHT\s+\d+)|(WIDTH\s+\d+)|(DEPTH\s+\d+)|(MAXVAL\s+\d+)|" b"(?:TUPLTYPE\s+\w+))*ENDHDR\n)", data).groups() self.hea...
Read PNM header and initialize instance.
def _read_pnm_header(self, data): """Read PNM header and initialize instance.""" bpm = data[1:2] in b"14" regroups = re.search(b"".join(( b"(^(P[123456]|P7 332)\s+(?:#.*[\r\n])*", b"\s*(\d+)\s+(?:#.*[\r\n])*", b"\s*(\d+)\s+(?:#.*[\r\n])*" * (not bpm), ...
Return image data from open file as numpy array.
def _read_data(self, fh, byteorder='>'): """Return image data from open file as numpy array.""" fh.seek(len(self.header)) data = fh.read() dtype = 'u1' if self.maxval < 256 else byteorder + 'u2' depth = 1 if self.magicnum == b"P7 332" else self.depth shape = [-1, self.hei...
Initialize instance from numpy array.
def _fromdata(self, data, maxval=None): """Initialize instance from numpy array.""" data = numpy.array(data, ndmin=2, copy=True) if data.dtype.kind not in "uib": raise ValueError("not an integer type: %s" % data.dtype) if data.dtype.kind == 'i' and numpy.min(data) < 0: ...
Write Netbm file.
def _tofile(self, fh, pam=False): """Write Netbm file.""" fh.seek(0) fh.write(self._header(pam)) data = self.asarray(copy=False) if self.maxval == 1: data = numpy.packbits(data, axis=-1) data.tofile(fh)
Return file header as byte string.
def _header(self, pam=False): """Return file header as byte string.""" if pam or self.magicnum == b'P7': header = "\n".join(( "P7", "HEIGHT %i" % self.height, "WIDTH %i" % self.width, "DEPTH %i" % self.depth, "MA...
This wraps a function and it silences numpy errors that happen during the execution. After the function has exited, it restores the previous state of the warnings.
def silence_errors(f): """ This wraps a function and it silences numpy errors that happen during the execution. After the function has exited, it restores the previous state of the warnings. """ @wraps(f) def wrapper(*args, **kwds): status = np.seterr(all='ignore') result = f...
Return the state space representation of the standard periodic covariance. ! Note: one must constrain lengthscale not to drop below 0.2. (independently of approximation order) After this Bessel functions of the first becomes NaN. Rescaling time variable might help. ...
def sde(self): """ Return the state space representation of the standard periodic covariance. ! Note: one must constrain lengthscale not to drop below 0.2. (independently of approximation order) After this Bessel functions of the first becomes NaN. Rescaling t...
Likelihood function given link(f) .. math:: p(y_{i}|\\lambda(f_{i})) = \\lambda(f_{i})\\exp (-y\\lambda(f_{i})) :param link_f: latent variables link(f) :type link_f: Nx1 array :param y: data :type y: Nx1 array :param Y_metadata: Y_metadata which is not used ...
def pdf_link(self, link_f, y, Y_metadata=None): """ Likelihood function given link(f) .. math:: p(y_{i}|\\lambda(f_{i})) = \\lambda(f_{i})\\exp (-y\\lambda(f_{i})) :param link_f: latent variables link(f) :type link_f: Nx1 array :param y: data :type y...
Log Likelihood Function given link(f) .. math:: \\ln p(y_{i}|\lambda(f_{i})) = \\ln \\lambda(f_{i}) - y_{i}\\lambda(f_{i}) :param link_f: latent variables (link(f)) :type link_f: Nx1 array :param y: data :type y: Nx1 array :param Y_metadata: Y_metadata which...
def logpdf_link(self, link_f, y, Y_metadata=None): """ Log Likelihood Function given link(f) .. math:: \\ln p(y_{i}|\lambda(f_{i})) = \\ln \\lambda(f_{i}) - y_{i}\\lambda(f_{i}) :param link_f: latent variables (link(f)) :type link_f: Nx1 array :param y: data...
Likelihood function given link(f) .. math:: p(y_{i}|\\lambda(f_{i})) = \\frac{\\lambda(f_{i})^{y_{i}}}{y_{i}!}e^{-\\lambda(f_{i})} :param link_f: latent variables link(f) :type link_f: Nx1 array :param y: data :type y: Nx1 array :param Y_metadata: Y_metadata...
def pdf_link(self, link_f, y, Y_metadata=None): """ Likelihood function given link(f) .. math:: p(y_{i}|\\lambda(f_{i})) = \\frac{\\lambda(f_{i})^{y_{i}}}{y_{i}!}e^{-\\lambda(f_{i})} :param link_f: latent variables link(f) :type link_f: Nx1 array :param y: d...