INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Convert the object into a json serializable dictionary. Note: It uses the private method _save_to_input_dict of the parent. :return dict: json serializable dictionary containing the needed information to instantiate the object
def to_dict(self): """ Convert the object into a json serializable dictionary. Note: It uses the private method _save_to_input_dict of the parent. :return dict: json serializable dictionary containing the needed information to instantiate the object """ #TODO: Implemen...
Convert the object into a json serializable dictionary. Note: It uses the private method _save_to_input_dict of the parent. :return dict: json serializable dictionary containing the needed information to instantiate the object
def to_dict(self): """ Convert the object into a json serializable dictionary. Note: It uses the private method _save_to_input_dict of the parent. :return dict: json serializable dictionary containing the needed information to instantiate the object """ input_dict = su...
Convert the object into a json serializable dictionary. Note: It uses the private method _save_to_input_dict of the parent. :return dict: json serializable dictionary containing the needed information to instantiate the object
def to_dict(self): """ Convert the object into a json serializable dictionary. Note: It uses the private method _save_to_input_dict of the parent. :return dict: json serializable dictionary containing the needed information to instantiate the object """ input_dict = su...
Compute the KL divergence to another NormalPosterior Object. This only holds, if the two NormalPosterior objects have the same shape, as we do computational tricks for the multivariate normal KL divergence.
def KL(self, other): """Compute the KL divergence to another NormalPosterior Object. This only holds, if the two NormalPosterior objects have the same shape, as we do computational tricks for the multivariate normal KL divergence. """ return .5*( np.sum(self.variance/other.variance) ...
Plot latent space X in 1D: See GPy.plotting.matplot_dep.variational_plots
def plot(self, *args, **kwargs): """ Plot latent space X in 1D: See GPy.plotting.matplot_dep.variational_plots """ import sys assert "matplotlib" in sys.modules, "matplotlib package has not been imported." from ...plotting.matplot_dep import variational_plots ...
Generic chaining function for second derivative .. math:: \\frac{d^{2}(f . g)}{dx^{2}} = \\frac{d^{2}f}{dg^{2}}(\\frac{dg}{dx})^{2} + \\frac{df}{dg}\\frac{d^{2}g}{dx^{2}}
def chain_2(d2f_dg2, dg_dx, df_dg, d2g_dx2): """ Generic chaining function for second derivative .. math:: \\frac{d^{2}(f . g)}{dx^{2}} = \\frac{d^{2}f}{dg^{2}}(\\frac{dg}{dx})^{2} + \\frac{df}{dg}\\frac{d^{2}g}{dx^{2}} """ if np.all(dg_dx==1.) and np.all(d2g_dx2 == 0): return d2f_d...
Generic chaining function for third derivative .. math:: \\frac{d^{3}(f . g)}{dx^{3}} = \\frac{d^{3}f}{dg^{3}}(\\frac{dg}{dx})^{3} + 3\\frac{d^{2}f}{dg^{2}}\\frac{dg}{dx}\\frac{d^{2}g}{dx^{2}} + \\frac{df}{dg}\\frac{d^{3}g}{dx^{3}}
def chain_3(d3f_dg3, dg_dx, d2f_dg2, d2g_dx2, df_dg, d3g_dx3): """ Generic chaining function for third derivative .. math:: \\frac{d^{3}(f . g)}{dx^{3}} = \\frac{d^{3}f}{dg^{3}}(\\frac{dg}{dx})^{3} + 3\\frac{d^{2}f}{dg^{2}}\\frac{dg}{dx}\\frac{d^{2}g}{dx^{2}} + \\frac{df}{dg}\\frac{d^{3}g}{dx^{3}} ...
Creates a D-dimensional grid of n linearly spaced points :param D: dimension of the grid :param n: number of points :param min_max: (min, max) list
def linear_grid(D, n = 100, min_max = (-100, 100)): """ Creates a D-dimensional grid of n linearly spaced points :param D: dimension of the grid :param n: number of points :param min_max: (min, max) list """ g = np.linspace(min_max[0], min_max[1], n) G = np.ones((n, D)) return G*...
This is the same initialization algorithm that is used in Kmeans++. It's quite simple and very useful to initialize the locations of the inducing points in sparse GPs. :param X: data :param m: number of inducing points
def kmm_init(X, m = 10): """ This is the same initialization algorithm that is used in Kmeans++. It's quite simple and very useful to initialize the locations of the inducing points in sparse GPs. :param X: data :param m: number of inducing points """ # compute the distances XXT =...
Convert an arbitrary number of parameters to :class:ndarray class objects. This is for converting parameter objects to numpy arrays, when using scipy.weave.inline routine. In scipy.weave.blitz there is no automatic array detection (even when the array inherits from :class:ndarray)
def param_to_array(*param): """ Convert an arbitrary number of parameters to :class:ndarray class objects. This is for converting parameter objects to numpy arrays, when using scipy.weave.inline routine. In scipy.weave.blitz there is no automatic array detection (even when the array inherits from :...
Compute the diagonal of the covariance matrix associated to X.
def Kdiag(self, X): """Compute the diagonal of the covariance matrix associated to X.""" Kdiag = np.zeros(X.shape[0]) ly=1/self.lengthscale_Y lu=np.sqrt(3)/self.lengthscale_U Vu = self.variance_U Vy=self.variance_Y k1 = (2*lu+ly)/(lu+ly)**2 k2 = (ly-2*lu...
derivative of the covariance matrix with respect to the parameters.
def update_gradients_full(self, dL_dK, X, X2=None): """derivative of the covariance matrix with respect to the parameters.""" X,slices = X[:,:-1],index_to_slices(X[:,-1]) if X2 is None: X2,slices2 = X,slices else: X2,slices2 = X2[:,:-1],index_to_slices(X2[:,-1]) ...
Set the data without calling parameters_changed to avoid wasted computation If this is called by the stochastic_grad function this will immediately update the gradients
def set_data(self, X, Y): """ Set the data without calling parameters_changed to avoid wasted computation If this is called by the stochastic_grad function this will immediately update the gradients """ assert X.shape[1]==self.Z.shape[1] self.X, self.Y = X, Y
Return a new batch of X and Y by taking a chunk of data from the complete X and Y
def new_batch(self): """ Return a new batch of X and Y by taking a chunk of data from the complete X and Y """ i = next(self.slicer) return self.X_all[i], self.Y_all[i]
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...
Convert the object into a json serializable dictionary. Note: It uses the private method _save_to_input_dict of the parent. :return dict: json serializable dictionary containing the needed information to instantiate the object
def to_dict(self): """ Convert the object into a json serializable dictionary. Note: It uses the private method _save_to_input_dict of the parent. :return dict: json serializable dictionary containing the needed information to instantiate the object """ input_dict = su...
Make a prediction for the function, to which we will pass the additional arguments
def predict(self,function,args): """Make a prediction for the function, to which we will pass the additional arguments""" param = self.model.param_array fs = [] for p in self.chain: self.model.param_array = p fs.append(function(*args)) # reset model to sta...
Return shape is NxMx(Ntheta)
def _param_grad_helper(self,X,X2,target): """Return shape is NxMx(Ntheta)""" if X2 is None: X2 = X FX = np.column_stack([f(X) for f in self.F]) FX2 = np.column_stack([f(X2) for f in self.F]) DER = np.zeros((self.n,self.n,self.n)) for i in range(self.n): DER[i,...
Set the input / output data of the model This is useful if we wish to change our existing data but maintain the same model :param X: input observations :type X: np.ndarray :param Y: output observations :type Y: np.ndarray or ObsAr
def set_XY(self, X, Y): """ Set the input / output data of the model This is useful if we wish to change our existing data but maintain the same model :param X: input observations :type X: np.ndarray :param Y: output observations :type Y: np.ndarray or ObsAr ...
Set the input data of the model :param X: input observations :type X: np.ndarray
def set_X(self, X): """ Set the input data of the model :param X: input observations :type X: np.ndarray """ assert isinstance(X, np.ndarray) state = self.update_model() self.update_model(False) self.X = ObsAr(X) self.update_model(state)
Set the output data of the model :param Y: output observations :type Y: np.ndarray or ObsArray
def set_Y(self, Y): """ Set the output data of the model :param Y: output observations :type Y: np.ndarray or ObsArray """ assert isinstance(Y, (np.ndarray, ObsAr)) state = self.update_model() self.update_model(False) if self.normalizer is not Non...
Method that is called upon any changes to :class:`~GPy.core.parameterization.param.Param` variables within the model. In particular in this class this method re-performs inference, recalculating the posterior, log marginal likelihood and gradients of the model .. warning:: This method is no...
def parameters_changed(self): """ Method that is called upon any changes to :class:`~GPy.core.parameterization.param.Param` variables within the model. In particular in this class this method re-performs inference, recalculating the posterior, log marginal likelihood and gradients of the model ...
For making predictions, does not account for normalization or likelihood full_cov is a boolean which defines whether the full covariance matrix of the prediction is computed. If full_cov is False (default), only the diagonal of the covariance is returned. .. math:: p(f*|X*,...
def _raw_predict(self, Xnew, full_cov=False, kern=None): """ For making predictions, does not account for normalization or likelihood full_cov is a boolean which defines whether the full covariance matrix of the prediction is computed. If full_cov is False (default), only the di...
Predict the function(s) at the new point(s) Xnew. For Student-t processes, this method is equivalent to predict_noiseless as no likelihood is included in the model.
def predict(self, Xnew, full_cov=False, kern=None, **kwargs): """ Predict the function(s) at the new point(s) Xnew. For Student-t processes, this method is equivalent to predict_noiseless as no likelihood is included in the model. """ return self.predict_noiseless(Xnew, full_cov=...
Predict the underlying function f at the new point(s) Xnew. :param Xnew: The points at which to make a prediction :type Xnew: np.ndarray (Nnew x self.input_dim) :param full_cov: whether to return the full covariance matrix, or just the diagonal :type full_cov: bool :param kern:...
def predict_noiseless(self, Xnew, full_cov=False, kern=None): """ Predict the underlying function f at the new point(s) Xnew. :param Xnew: The points at which to make a prediction :type Xnew: np.ndarray (Nnew x self.input_dim) :param full_cov: whether to return the full covaria...
Get the predictive quantiles around the prediction at X :param X: The points at which to make a prediction :type X: np.ndarray (Xnew x self.input_dim) :param quantiles: tuple of quantiles, default is (2.5, 97.5) which is the 95% interval :type quantiles: tuple :param kern: optio...
def predict_quantiles(self, X, quantiles=(2.5, 97.5), kern=None, **kwargs): """ Get the predictive quantiles around the prediction at X :param X: The points at which to make a prediction :type X: np.ndarray (Xnew x self.input_dim) :param quantiles: tuple of quantiles, default is...
Samples the posterior GP at the points X, equivalent to posterior_samples_f due to the absence of a likelihood.
def posterior_samples(self, X, size=10, full_cov=False, Y_metadata=None, likelihood=None, **predict_kwargs): """ Samples the posterior GP at the points X, equivalent to posterior_samples_f due to the absence of a likelihood. """ return self.posterior_samples_f(X, size, full_cov=full_cov,...
Samples the posterior TP at the points X. :param X: The points at which to take the samples. :type X: np.ndarray (Nnew x self.input_dim) :param size: the number of a posteriori samples. :type size: int. :param full_cov: whether to return the full covariance matrix, or just the d...
def posterior_samples_f(self, X, size=10, full_cov=True, **predict_kwargs): """ Samples the posterior TP at the points X. :param X: The points at which to take the samples. :type X: np.ndarray (Nnew x self.input_dim) :param size: the number of a posteriori samples. :type...
Get a view on the diagonal elements of a 2D array. This is actually a view (!) on the diagonal of the array, so you can in-place adjust the view. :param :class:`ndarray` A: 2 dimensional numpy array :param int offset: view offset to give back (negative entries allowed) :rtype: :class:`ndarray` vie...
def view(A, offset=0): """ Get a view on the diagonal elements of a 2D array. This is actually a view (!) on the diagonal of the array, so you can in-place adjust the view. :param :class:`ndarray` A: 2 dimensional numpy array :param int offset: view offset to give back (negative entries allowe...
Times the view of A with b in place (!). Returns modified A Broadcasting is allowed, thus b can be scalar. if offset is not zero, make sure b is of right shape! :param ndarray A: 2 dimensional array :param ndarray-like b: either one dimensional or scalar :param int offset: same as in view. ...
def times(A, b, offset=0): """ Times the view of A with b in place (!). Returns modified A Broadcasting is allowed, thus b can be scalar. if offset is not zero, make sure b is of right shape! :param ndarray A: 2 dimensional array :param ndarray-like b: either one dimensional or scalar ...
Divide the view of A by b in place (!). Returns modified A Broadcasting is allowed, thus b can be scalar. if offset is not zero, make sure b is of right shape! :param ndarray A: 2 dimensional array :param ndarray-like b: either one dimensional or scalar :param int offset: same as in view. ...
def divide(A, b, offset=0): """ Divide the view of A by b in place (!). Returns modified A Broadcasting is allowed, thus b can be scalar. if offset is not zero, make sure b is of right shape! :param ndarray A: 2 dimensional array :param ndarray-like b: either one dimensional or scalar ...
Add b to the view of A in place (!). Returns modified A. Broadcasting is allowed, thus b can be scalar. if offset is not zero, make sure b is of right shape! :param ndarray A: 2 dimensional array :param ndarray-like b: either one dimensional or scalar :param int offset: same as in view. :r...
def add(A, b, offset=0): """ Add b to the view of A in place (!). Returns modified A. Broadcasting is allowed, thus b can be scalar. if offset is not zero, make sure b is of right shape! :param ndarray A: 2 dimensional array :param ndarray-like b: either one dimensional or scalar :para...
Subtract b from the view of A in place (!). Returns modified A. Broadcasting is allowed, thus b can be scalar. if offset is not zero, make sure b is of right shape! :param ndarray A: 2 dimensional array :param ndarray-like b: either one dimensional or scalar :param int offset: same as in view....
def subtract(A, b, offset=0): """ Subtract b from the view of A in place (!). Returns modified A. Broadcasting is allowed, thus b can be scalar. if offset is not zero, make sure b is of right shape! :param ndarray A: 2 dimensional array :param ndarray-like b: either one dimensional or scal...
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...
Convert the object into a json serializable dictionary. Note: It uses the private method _save_to_input_dict of the parent. :return dict: json serializable dictionary containing the needed information to instantiate the object
def to_dict(self): """ Convert the object into a json serializable dictionary. Note: It uses the private method _save_to_input_dict of the parent. :return dict: json serializable dictionary containing the needed information to instantiate the object """ input_dict = su...
Compute the gradient of the objective function with respect to X. :param dL_dK: An array of gradients of the objective function with respect to the covariance function. :type dL_dK: np.ndarray (num_samples x num_inducing) :param X: Observed data inputs :type X: np.ndarray (num_samples x...
def gradients_X(self, dL_dK, X, X2=None): """Compute the gradient of the objective function with respect to X. :param dL_dK: An array of gradients of the objective function with respect to the covariance function. :type dL_dK: np.ndarray (num_samples x num_inducing) :param X: Observed d...
Support adding kernels for sde representation
def sde(self): """ Support adding kernels for sde representation """ import scipy.linalg as la F = None L = None Qc = None H = None Pinf = None P0 = None dF = None dQc = None dPinf = None ...
Returns error rate and true/false positives in a binary classification problem - Actual classes are displayed by column. - Predicted classes are displayed by row. :param p: array of class '1' probabilities. :param labels: array of actual classes. :param names: list of class names, defaults to ['1',...
def conf_matrix(p,labels,names=['1','0'],threshold=.5,show=True): """ Returns error rate and true/false positives in a binary classification problem - Actual classes are displayed by column. - Predicted classes are displayed by row. :param p: array of class '1' probabilities. :param labels: arr...
Convert the object into a json serializable dictionary. :param boolean save_data: if true, it adds the training data self.X and self.Y to the dictionary :return dict: json serializable dictionary containing the needed information to instantiate the object
def to_dict(self, save_data=True): """ Convert the object into a json serializable dictionary. :param boolean save_data: if true, it adds the training data self.X and self.Y to the dictionary :return dict: json serializable dictionary containing the needed information to instantiate the...
return a F ordered version of A, assuming A is symmetric
def force_F_ordered_symmetric(A): """ return a F ordered version of A, assuming A is symmetric """ if A.flags['F_CONTIGUOUS']: return A if A.flags['C_CONTIGUOUS']: return A.T else: return np.asfortranarray(A)
Wrapper for lapack dtrtrs function DTRTRS solves a triangular system of the form A * X = B or A**T * X = B, where A is a triangular matrix of order N, and B is an N-by-NRHS matrix. A check is made to verify that A is nonsingular. :param A: Matrix A(triangular) :param B: Matrix B :...
def dtrtrs(A, B, lower=1, trans=0, unitdiag=0): """ Wrapper for lapack dtrtrs function DTRTRS solves a triangular system of the form A * X = B or A**T * X = B, where A is a triangular matrix of order N, and B is an N-by-NRHS matrix. A check is made to verify that A is nonsingular. ...
Wrapper for lapack dpotrs function :param A: Matrix A :param B: Matrix B :param lower: is matrix lower (true) or upper (false) :returns:
def dpotrs(A, B, lower=1): """ Wrapper for lapack dpotrs function :param A: Matrix A :param B: Matrix B :param lower: is matrix lower (true) or upper (false) :returns: """ A = force_F_ordered(A) return lapack.dpotrs(A, B, lower=lower)
Wrapper for lapack dpotri function DPOTRI - compute the inverse of a real symmetric positive definite matrix A using the Cholesky factorization A = U**T*U or A = L*L**T computed by DPOTRF :param A: Matrix A :param lower: is matrix lower (true) or upper (false) :returns: A inverse
def dpotri(A, lower=1): """ Wrapper for lapack dpotri function DPOTRI - compute the inverse of a real symmetric positive definite matrix A using the Cholesky factorization A = U**T*U or A = L*L**T computed by DPOTRF :param A: Matrix A :param lower: is matrix lower (true) or upper (fals...
Determinant of a positive definite matrix, only symmetric matricies though
def pddet(A): """ Determinant of a positive definite matrix, only symmetric matricies though """ L = jitchol(A) logdetA = 2*sum(np.log(np.diag(L))) return logdetA
Multiply all the arguments using matrix product rules. The output is equivalent to multiplying the arguments one by one from left to right using dot(). Precedence can be controlled by creating tuples of arguments, for instance mdot(a,((b,c),d)) multiplies a (a*((b*c)*d)). Note that this means the ou...
def mdot(*args): """ Multiply all the arguments using matrix product rules. The output is equivalent to multiplying the arguments one by one from left to right using dot(). Precedence can be controlled by creating tuples of arguments, for instance mdot(a,((b,c),d)) multiplies a (a*((b*c)*d)). ...
Recursive helper for mdot
def _mdot_r(a, b): """Recursive helper for mdot""" if type(a) == tuple: if len(a) > 1: a = mdot(*a) else: a = a[0] if type(b) == tuple: if len(b) > 1: b = mdot(*b) else: b = b[0] return np.dot(a, b)
:param A: A DxD pd numpy array :rval Ai: the inverse of A :rtype Ai: np.ndarray :rval L: the Cholesky decomposition of A :rtype L: np.ndarray :rval Li: the Cholesky decomposition of Ai :rtype Li: np.ndarray :rval logdet: the log of the determinant of A :rtype logdet: float64
def pdinv(A, *args): """ :param A: A DxD pd numpy array :rval Ai: the inverse of A :rtype Ai: np.ndarray :rval L: the Cholesky decomposition of A :rtype L: np.ndarray :rval Li: the Cholesky decomposition of Ai :rtype Li: np.ndarray :rval logdet: the log of the determinant of A :...
:param A: A DxDxN numpy array (each A[:,:,i] is pd) :rval invs: the inverses of A :rtype invs: np.ndarray :rval hld: 0.5* the log of the determinants of A :rtype hld: np.array
def multiple_pdinv(A): """ :param A: A DxDxN numpy array (each A[:,:,i] is pd) :rval invs: the inverses of A :rtype invs: np.ndarray :rval hld: 0.5* the log of the determinants of A :rtype hld: np.array """ N = A.shape[-1] chols = [jitchol(A[:, :, i]) for i in range(N)] halflog...
Principal component analysis: maximum likelihood solution by SVD :param Y: NxD np.array of data :param input_dim: int, dimension of projection :rval X: - Nxinput_dim np.array of dimensionality reduced data :rval W: - input_dimxD mapping from X to Y
def pca(Y, input_dim): """ Principal component analysis: maximum likelihood solution by SVD :param Y: NxD np.array of data :param input_dim: int, dimension of projection :rval X: - Nxinput_dim np.array of dimensionality reduced data :rval W: - input_dimxD mapping from X to Y """ if n...
EM implementation for probabilistic pca. :param array-like Y: Observed Data :param int Q: Dimensionality for reduced array :param int iterations: number of iterations for EM
def ppca(Y, Q, iterations=100): """ EM implementation for probabilistic pca. :param array-like Y: Observed Data :param int Q: Dimensionality for reduced array :param int iterations: number of iterations for EM """ from numpy.ma import dot as madot N, D = Y.shape # Initialise W rando...
returns np.dot(mat, mat.T), but faster for large 2D arrays of doubles.
def tdot_blas(mat, out=None): """returns np.dot(mat, mat.T), but faster for large 2D arrays of doubles.""" if (mat.dtype != 'float64') or (len(mat.shape) != 2): return np.dot(mat, mat.T) nn = mat.shape[0] if out is None: out = np.zeros((nn, nn)) else: assert(out.dtype == 'flo...
Performs a symmetric rank-1 update operation: A <- A + alpha * np.dot(x,x.T) :param A: Symmetric NxN np.array :param x: Nx1 np.array :param alpha: scalar
def DSYR_blas(A, x, alpha=1.): """ Performs a symmetric rank-1 update operation: A <- A + alpha * np.dot(x,x.T) :param A: Symmetric NxN np.array :param x: Nx1 np.array :param alpha: scalar """ At = blas.dsyr(lower=0, x=x, a=A, alpha=alpha, overwrite_a=False) #See https://github.com/sci...
Performs a symmetric rank-1 update operation: A <- A + alpha * np.dot(x,x.T) :param A: Symmetric NxN np.array :param x: Nx1 np.array :param alpha: scalar
def DSYR_numpy(A, x, alpha=1.): """ Performs a symmetric rank-1 update operation: A <- A + alpha * np.dot(x,x.T) :param A: Symmetric NxN np.array :param x: Nx1 np.array :param alpha: scalar """ A += alpha * np.dot(x[:, None], x[None, :])
Take the square matrix A and make it symmetrical by copting elements from the lower half to the upper works IN PLACE. note: tries to use cython, falls back to a slower numpy version
def symmetrify(A, upper=False): """ Take the square matrix A and make it symmetrical by copting elements from the lower half to the upper works IN PLACE. note: tries to use cython, falls back to a slower numpy version """ if use_linalg_cython: _symmetrify_cython(A, upper) else:...
Return L^-T * X * L^-1, assumuing X is symmetrical and L is lower cholesky
def backsub_both_sides(L, X, transpose='left'): """ Return L^-T * X * L^-1, assumuing X is symmetrical and L is lower cholesky """ if transpose == 'left': tmp, _ = dtrtrs(L, X, lower=1, trans=1) return dtrtrs(L, tmp.T, lower=1, trans=1)[0].T else: tmp, _ = dtrtrs(L, X, lower=...
Faster version of einsum 'ij,jlk->ilk'
def ij_jlk_to_ilk(A, B): """ Faster version of einsum 'ij,jlk->ilk' """ return A.dot(B.reshape(B.shape[0], -1)).reshape(A.shape[0], B.shape[1], B.shape[2])
Faster version of einsum einsum('ijk,jlk->il', A,B)
def ijk_jlk_to_il(A, B): """ Faster version of einsum einsum('ijk,jlk->il', A,B) """ res = np.zeros((A.shape[0], B.shape[1])) [np.add(np.dot(A[:,:,k], B[:,:,k]), res, out=res) for k in range(B.shape[-1])] return res
Faster version of einsum np.einsum('ijk,ljk->ilk', A, B) I.e A.dot(B.T) for every dimension
def ijk_ljk_to_ilk(A, B): """ Faster version of einsum np.einsum('ijk,ljk->ilk', A, B) I.e A.dot(B.T) for every dimension """ res = np.zeros((A.shape[-1], A.shape[0], B.shape[0])) [np.dot(A[:,:,i], B[:,:,i].T, out=res[i,:,:]) for i in range(A.shape[-1])] res = res.swapaxes(0, 2).swapaxes(0,...
Load a previously pickled model, using `m.pickle('path/to/file.pickle)' :param file_name: path/to/file.pickle
def load(file_or_path): """ Load a previously pickled model, using `m.pickle('path/to/file.pickle)' :param file_name: path/to/file.pickle """ # This is the pickling pain when changing _src -> src import sys import inspect sys.modules['GPy.kern._src'] = kern.src for name, module in i...
numpy implementation makes use of the code here: http://se.mathworks.com/matlabcentral/fileexchange/18801-quadvgk We here use gaussian kronrod integration already used in gpstuff for evaluating one dimensional integrals. This is vectorised quadrature which means that several functions can be evaluated at the sa...
def quadvgk(feval, fmin, fmax, tol1=1e-5, tol2=1e-5): """ numpy implementation makes use of the code here: http://se.mathworks.com/matlabcentral/fileexchange/18801-quadvgk We here use gaussian kronrod integration already used in gpstuff for evaluating one dimensional integrals. This is vectorised quadra...
Integrate f from fmin to fmax, do integration by substitution x = r / (1-r**2) when r goes from -1 to 1 , x goes from -inf to inf. the interval for quadgk function is from -1 to +1, so we transform the space from (-inf,inf) to (-1,1) :param f: :param fmin: :param fmax: :param difftol: ...
def quadgk_int(f, fmin=-np.inf, fmax=np.inf, difftol=0.1): """ Integrate f from fmin to fmax, do integration by substitution x = r / (1-r**2) when r goes from -1 to 1 , x goes from -inf to inf. the interval for quadgk function is from -1 to +1, so we transform the space from (-inf,inf) to (-1,1)...
Make an update of the internal status by gathering the variational posteriors for all the individual models.
def _update_inernal(self, varp_list): """Make an update of the internal status by gathering the variational posteriors for all the individual models.""" # The probability for the binary variable for the same latent dimension of any of the models is on. if self.group_spike: self._b_pr...
Make an update of the internal status by gathering the variational posteriors for all the individual models.
def _update_inernal(self, varp_list): """Make an update of the internal status by gathering the variational posteriors for all the individual models.""" # The probability for the binary variable for the same latent dimension of any of the models is on. self._b_prob_all = 1.-param_to_array(varp_l...
Compute the covariance matrix between X and X2.
def K(self,X,X2,target): """Compute the covariance matrix between X and X2.""" AX = np.dot(X,self.transform) if X2 is None: X2 = X AX2 = AX else: AX2 = np.dot(X2, self.transform) self.k.K(X,X2,target) self.k.K(AX,X2,target) self...
derivative of the covariance matrix with respect to the parameters.
def _param_grad_helper(self,dL_dK,X,X2,target): """derivative of the covariance matrix with respect to the parameters.""" AX = np.dot(X,self.transform) if X2 is None: X2 = X ZX2 = AX else: AX2 = np.dot(X2, self.transform) self.k._param_grad_hel...
Compute the diagonal of the covariance matrix associated to X.
def Kdiag(self,X,target): """Compute the diagonal of the covariance matrix associated to X.""" foo = np.zeros((X.shape[0],X.shape[0])) self.K(X,X,foo) target += np.diag(foo)
Shape N,num_inducing,num_inducing,Ntheta
def dpsi2_dtheta(self, dL_dpsi2, Z, mu, S, target): """Shape N,num_inducing,num_inducing,Ntheta""" self._psi_computations(Z, mu, S) d_var = 2.*self._psi2 / self.variance # d_length = 2.*self._psi2[:, :, :, None] * (self._psi2_Zdist_sq * self._psi2_denom + self._psi2_mudist_sq + S[:, None...
Think N,num_inducing,num_inducing,input_dim
def dpsi2_dmuS(self, dL_dpsi2, Z, mu, S, target_mu, target_S): """Think N,num_inducing,num_inducing,input_dim """ self._psi_computations(Z, mu, S) tmp = (self.inv_lengthscale2 * self._psi2[:, :, :, None]) / self._psi2_denom target_mu += -2.*(dL_dpsi2[:, :, :, None] * tmp * self._psi2_mud...
Z - MxQ mu - NxQ S - NxQ
def _psicomputations(self, kern, Z, variational_posterior, return_psi2_n=False): """ Z - MxQ mu - NxQ S - NxQ """ variance, lengthscale = kern.variance, kern.lengthscale N,M,Q = self.get_dimensions(Z, variational_posterior) self._initGPUCache(N,M,Q) ...
The SVI-VarDTC inference
def inference(self, kern_r, kern_c, Xr, Xc, Zr, Zc, likelihood, Y, qU_mean ,qU_var_r, qU_var_c): """ The SVI-VarDTC inference """ N, D, Mr, Mc, Qr, Qc = Y.shape[0], Y.shape[1], Zr.shape[0], Zc.shape[0], Zr.shape[1], Zc.shape[1] uncertain_inputs_r = isinstance(Xr, VariationalPos...
Set the prior for this object to prior. :param :class:`~GPy.priors.Prior` prior: a prior to set for this parameter :param bool warning: whether to warn if another prior was set for this parameter
def set_prior(self, prior, warning=True): """ Set the prior for this object to prior. :param :class:`~GPy.priors.Prior` prior: a prior to set for this parameter :param bool warning: whether to warn if another prior was set for this parameter """ repriorized = self.unset_p...
evaluate the prior
def log_prior(self): """evaluate the prior""" if self.priors.size == 0: return 0. x = self.param_array #evaluate the prior log densities log_p = reduce(lambda a, b: a + b, (p.lnpdf(x[ind]).sum() for p, ind in self.priors.items()), 0) #account for the transfor...
evaluate the gradients of the priors
def _log_prior_gradients(self): """evaluate the gradients of the priors""" if self.priors.size == 0: return 0. x = self.param_array ret = np.zeros(x.size) #compute derivate of prior density [np.put(ret, ind, p.lnpdf_grad(x[ind])) for p, ind in self.priors.item...
Zero-mean, unit-variance normalization by default
def _preprocess(self, data, train): """Zero-mean, unit-variance normalization by default""" if train: inputs, labels = data self.data_mean = inputs.mean(axis=0) self.data_std = inputs.std(axis=0) self.labels_mean = labels.mean(axis=0) self.lab...
Given a 3d matrix, make a block matrix, where the first and second dimensions are blocked according to blocksizes, and the pages are blocked using pagesizes
def get_blocks_3d(A, blocksizes, pagesizes=None): """ Given a 3d matrix, make a block matrix, where the first and second dimensions are blocked according to blocksizes, and the pages are blocked using pagesizes """ assert (A.shape[0]==A.shape[1]) and len(A.shape)==3, "can't blockify this non-square ...
Element wise dot product on block matricies +------+------+ +------+------+ +-------+-------+ | | | | | | |A11.B11|B12.B12| | A11 | A12 | | B11 | B12 | | | | +------+------+ o +------+------| = +-------+-------+ | | | | | | ...
def block_dot(A, B, diagonal=False): """ Element wise dot product on block matricies +------+------+ +------+------+ +-------+-------+ | | | | | | |A11.B11|B12.B12| | A11 | A12 | | B11 | B12 | | | | +------+------+ o +------+------| = +-------...
Run a Gaussian process classification on the three phase oil data. The demonstration calls the basic GP classification model and uses EP to approximate the likelihood.
def oil(num_inducing=50, max_iters=100, kernel=None, optimize=True, plot=True): """ Run a Gaussian process classification on the three phase oil data. The demonstration calls the basic GP classification model and uses EP to approximate the likelihood. """ try:import pods except ImportError:raise Im...
Simple 1D classification example using EP approximation :param seed: seed value for data generation (default is 4). :type seed: int
def toy_linear_1d_classification(seed=default_seed, optimize=True, plot=True): """ Simple 1D classification example using EP approximation :param seed: seed value for data generation (default is 4). :type seed: int """ try:import pods except ImportError:raise ImportWarning('Need pods for e...
Simple 1D classification example using Laplace approximation :param seed: seed value for data generation (default is 4). :type seed: int
def toy_linear_1d_classification_laplace(seed=default_seed, optimize=True, plot=True): """ Simple 1D classification example using Laplace approximation :param seed: seed value for data generation (default is 4). :type seed: int """ try:import pods except ImportError:print('pods unavailabl...
Sparse 1D classification example :param seed: seed value for data generation (default is 4). :type seed: int
def sparse_toy_linear_1d_classification_uncertain_input(num_inducing=10, seed=default_seed, optimize=True, plot=True): """ Sparse 1D classification example :param seed: seed value for data generation (default is 4). :type seed: int """ try:import pods except ImportError:print('pods unavai...
Simple 1D classification example using a heavy side gp transformation :param seed: seed value for data generation (default is 4). :type seed: int
def toy_heaviside(seed=default_seed, max_iters=100, optimize=True, plot=True): """ Simple 1D classification example using a heavy side gp transformation :param seed: seed value for data generation (default is 4). :type seed: int """ try:import pods except ImportError:print('pods unavailab...
Run a Gaussian process classification on the crescent data. The demonstration calls the basic GP classification model and uses EP to approximate the likelihood. :param model_type: type of model to fit ['Full', 'FITC', 'DTC']. :param inducing: number of inducing variables (only used for 'FITC' or 'DTC'). :t...
def crescent_data(model_type='Full', num_inducing=10, seed=default_seed, kernel=None, optimize=True, plot=True): """ Run a Gaussian process classification on the crescent data. The demonstration calls the basic GP classification model and uses EP to approximate the likelihood. :param model_type: type of mo...
Apply warping_function to some Input data Parameters: ----------- X : array_like, shape = (n_samples, n_features) test_data: bool, optional Default to False, should set to True when transforming test data Returns ------- X_warped : array_like, shape...
def f(self, X, test_data=False): """Apply warping_function to some Input data Parameters: ----------- X : array_like, shape = (n_samples, n_features) test_data: bool, optional Default to False, should set to True when transforming test data Returns ...
Compute the gradient of warping function with respect to X Parameters ---------- X : array_like, shape = (n_samples, n_features) The location to compute gradient Returns ------- grad : array_like, shape = (n_samples, n_features) The gradient for ...
def fgrad_X(self, X): """Compute the gradient of warping function with respect to X Parameters ---------- X : array_like, shape = (n_samples, n_features) The location to compute gradient Returns ------- grad : array_like, shape = (n_samples, n_featur...
Update the gradients of marginal log likelihood with respect to the parameters of warping function Parameters ---------- X : array_like, shape = (n_samples, n_features) The input BEFORE warping dL_dW : array_like, shape = (n_samples, n_features) The gradient of ...
def update_grads(self, X, dL_dW): """Update the gradients of marginal log likelihood with respect to the parameters of warping function Parameters ---------- X : array_like, shape = (n_samples, n_features) The input BEFORE warping dL_dW : array_like, shape = (n_samp...
The first phase of inference: Compute: log-likelihood, dL_dKmm Cached intermediate results: Kmm, KmmInv,
def inference(self, kern, X, Z, likelihood, Y, indexD, output_dim, Y_metadata=None, Lm=None, dL_dKmm=None, Kuu_sigma=None): """ The first phase of inference: Compute: log-likelihood, dL_dKmm Cached intermediate results: Kmm, KmmInv, """ input_dim = Z.shape[0] u...
Plot latent space X in 1D: - if fig is given, create input_dim subplots in fig and plot in these - if ax is given plot input_dim 1D latent space plots of X into each `axis` - if neither fig nor ax is given create a figure with fignum and plot in there colors: colors of different la...
def plot(parameterized, fignum=None, ax=None, colors=None, figsize=(12, 6)): """ Plot latent space X in 1D: - if fig is given, create input_dim subplots in fig and plot in these - if ax is given plot input_dim 1D latent space plots of X into each `axis` - if neither fig nor ax is given ...
Plot latent space X in 1D: - if fig is given, create input_dim subplots in fig and plot in these - if ax is given plot input_dim 1D latent space plots of X into each `axis` - if neither fig nor ax is given create a figure with fignum and plot in there colors: colors of different la...
def plot_SpikeSlab(parameterized, fignum=None, ax=None, colors=None, side_by_side=True): """ Plot latent space X in 1D: - if fig is given, create input_dim subplots in fig and plot in these - if ax is given plot input_dim 1D latent space plots of X into each `axis` - if neither fig nor ...
Plots the mapping associated with the model. - In one dimension, the function is plotted. - In two dimsensions, a contour-plot shows the function - In higher dimensions, we've not implemented this yet !TODO! Can plot only part of the data and part of the posterior functions using which_data a...
def plot_mapping(self, plot_limits=None, which_data='all', which_parts='all', resolution=None, levels=20, samples=0, fignum=None, ax=None, fixed_inputs=[], linecol=Tango.colorsHex['darkBlue']): """ Plots the mapping associated with the model. - In one dimension, the function is plotted. - In two dim...
Parameters have now changed
def parameters_changed(self): """ Parameters have now changed """ #np.set_printoptions(16) #print(self.param_array) # Get the model matrices from the kernel (F,L,Qc,H,P_inf, P0, dFt,dQct,dP_inft, dP0t) = self.kern.sde() # neces...
Performs the actual prediction for new X points. Inner function. It is called only from inside this class. Input: --------------------- Xnews: vector or (n_points,1) matrix New time points where to evaluate predictions. Ynews: (n_train_points, ts_no) matrix ...
def _raw_predict(self, Xnew=None, Ynew=None, filteronly=False, p_balance=False, **kw): """ Performs the actual prediction for new X points. Inner function. It is called only from inside this class. Input: --------------------- Xnews: vector or (n_points,1) matrix ...
Inputs: ------------------ balance: bool Whether to balance or not the model as a whole
def predict(self, Xnew=None, filteronly=False, include_likelihood=True, balance=None, **kw): """ Inputs: ------------------ balance: bool Whether to balance or not the model as a whole """ if balance is None: p_balance = self...
Inputs: ------------------ balance: bool Whether to balance or not the model as a whole
def predict_quantiles(self, Xnew=None, quantiles=(2.5, 97.5), balance=None, **kw): """ Inputs: ------------------ balance: bool Whether to balance or not the model as a whole """ if balance is None: p_balance = self.balance el...
Play a data set using the data_show object given. :Y: the data set to be visualized. :param visualizer: the data show objectwhether to display during optimisation :type visualizer: data_show Example usage: This example loads in the CMU mocap database (http://mocap.cs.cmu.edu) subject number 35 mo...
def data_play(Y, visualizer, frame_rate=30): """Play a data set using the data_show object given. :Y: the data set to be visualized. :param visualizer: the data show objectwhether to display during optimisation :type visualizer: data_show Example usage: This example loads in the CMU mocap dat...
When latent values are modified update the latent representation and ulso update the output visualization.
def modify(self, vals): """When latent values are modified update the latent representation and ulso update the output visualization.""" self.vals = vals.view(np.ndarray).copy() y = self.model.predict(self.vals)[0] self.data_visualize.modify(y) self.latent_handle.set_data(self.va...
Set up the axes with the right limits and scaling.
def initialize_axes(self, boundary=0.05): """Set up the axes with the right limits and scaling.""" bs = [(self.vals[:, i].max()-self.vals[:, i].min())*boundary for i in range(3)] self.x_lim = np.array([self.vals[:, 0].min()-bs[0], self.vals[:, 0].max()+bs[0]]) self.y_lim = np.array([self...
Takes a set of angles and converts them to the x,y,z coordinates in the internal prepresentation of the class, ready for plotting. :param vals: the values that are being modelled.
def process_values(self): """Takes a set of angles and converts them to the x,y,z coordinates in the internal prepresentation of the class, ready for plotting. :param vals: the values that are being modelled.""" if self.padding>0: channels = np.zeros((self.vals.shape[0], self.vals....
Return a canvas, kwargupdate for your plotting library. if figure is not None, create a canvas in the figure at subplot position (col, row). This method does two things, it creates an empty canvas and updates the kwargs (deletes the unnecessary kwargs) for further usag...
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): """ Return a canvas, kwargupdate for your plotting library. if figure is not None, create a canvas in the figure at subplot po...
Make a line plot from for Y on X (Y = f(X)) on the canvas. If Z is not None, plot in 3d! the kwargs are plotting library specific kwargs!
def plot(self, cavas, X, Y, Z=None, color=None, label=None, **kwargs): """ Make a line plot from for Y on X (Y = f(X)) on the canvas. If Z is not None, plot in 3d! the kwargs are plotting library specific kwargs! """ raise NotImplementedError("Implement all plot ...
Plot a surface for 3d plotting for the inputs (X, Y, Z). the kwargs are plotting library specific kwargs!
def surface(self, canvas, X, Y, Z, color=None, label=None, **kwargs): """ Plot a surface for 3d plotting for the inputs (X, Y, Z). the kwargs are plotting library specific kwargs! """ raise NotImplementedError("Implement all plot functions in AbstractPlottingLibrary in o...