INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Log Likelihood Function given link(f) .. math:: \\ln p(y_{i}|\lambda(f_{i})) = -\\lambda(f_{i}) + y_{i}\\log \\lambda(f_{i}) - \\log y_{i}! :param link_f: latent variables (link(f)) :type link_f: Nx1 array :param y: data :type y: Nx1 array :param Y_metadata:...
def logpdf_link(self, link_f, y, Y_metadata=None): """ Log Likelihood Function given link(f) .. math:: \\ln p(y_{i}|\lambda(f_{i})) = -\\lambda(f_{i}) + y_{i}\\log \\lambda(f_{i}) - \\log y_{i}! :param link_f: latent variables (link(f)) :type link_f: Nx1 array ...
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): """ 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() # Ysim = np.random.poisson(self.gp_link.transf(gp), [samples...
Calculate the numerical inverse of f. This should be overwritten for specific warping functions where the inverse can be found in closed form. :param max_iterations: maximum number of N.R. iterations
def f_inv(self, z, max_iterations=250, y=None): """ Calculate the numerical inverse of f. This should be overwritten for specific warping functions where the inverse can be found in closed form. :param max_iterations: maximum number of N.R. iterations """ z = z....
Transform y with f using parameter vector psi psi = [[a,b,c]] :math:`f = (y * d) + \\sum_{terms} a * tanh(b *(y + c))`
def f(self, y): """ Transform y with f using parameter vector psi psi = [[a,b,c]] :math:`f = (y * d) + \\sum_{terms} a * tanh(b *(y + c))` """ d = self.d mpsi = self.psi z = d * y.copy() for i in range(len(mpsi)): a, b, c = mpsi[i] ...
gradient of f w.r.t to y ([N x 1]) :returns: Nx1 vector of derivatives, unless return_precalc is true, then it also returns the precomputed stuff
def fgrad_y(self, y, return_precalc=False): """ gradient of f w.r.t to y ([N x 1]) :returns: Nx1 vector of derivatives, unless return_precalc is true, then it also returns the precomputed stuff """ d = self.d mpsi = self.psi # vectorized version ...
gradient of f w.r.t to y and psi :returns: NxIx4 tensor of partial derivatives
def fgrad_y_psi(self, y, return_covar_chain=False): """ gradient of f w.r.t to y and psi :returns: NxIx4 tensor of partial derivatives """ mpsi = self.psi w, s, r, d = self.fgrad_y(y, return_precalc=True) gradients = np.zeros((y.shape[0], y.shape[1], len(mpsi), ...
Inverse cumulative standard Gaussian distribution Based on Winitzki, S. (2008)
def inv_std_norm_cdf(x): """ Inverse cumulative standard Gaussian distribution Based on Winitzki, S. (2008) """ z = 2*x -1 ln1z2 = np.log(1-z**2) a = 8*(np.pi -3)/(3*np.pi*(4-np.pi)) b = 2/(np.pi * a) + ln1z2/2 inv_erf = np.sign(z) * np.sqrt( np.sqrt(b**2 - ln1z2/a) - b ) return ...
Robust implementations of cdf of a standard normal. @see [[https://github.com/mseeger/apbsint/blob/master/src/eptools/potentials/SpecfunServices.h original implementation]] in C from Matthias Seeger. */
def cdfNormal(z): """ Robust implementations of cdf of a standard normal. @see [[https://github.com/mseeger/apbsint/blob/master/src/eptools/potentials/SpecfunServices.h original implementation]] in C from Matthias Seeger. */ """ if (abs(z) < ERF_CODY_LIMIT1): # Phi(z) approx (1+y ...
Robust implementations of log cdf of a standard normal. @see [[https://github.com/mseeger/apbsint/blob/master/src/eptools/potentials/SpecfunServices.h original implementation]] in C from Matthias Seeger.
def logCdfNormal(z): """ Robust implementations of log cdf of a standard normal. @see [[https://github.com/mseeger/apbsint/blob/master/src/eptools/potentials/SpecfunServices.h original implementation]] in C from Matthias Seeger. """ if (abs(z) < ERF_CODY_LIMIT1): # Phi(z) approx (1+y...
Robust implementations of derivative of the log cdf of a standard normal. @see [[https://github.com/mseeger/apbsint/blob/master/src/eptools/potentials/SpecfunServices.h original implementation]] in C from Matthias Seeger.
def derivLogCdfNormal(z): """ Robust implementations of derivative of the log cdf of a standard normal. @see [[https://github.com/mseeger/apbsint/blob/master/src/eptools/potentials/SpecfunServices.h original implementation]] in C from Matthias Seeger. """ if (abs(z) < ERF_CODY_LIMIT1): ...
take a numpy array of integers (index) and return a nested list of slices such that the slices describe the start, stop points for each integer in the index. e.g. >>> index = np.asarray([0,0,0,1,1,1,2,2,2]) returns >>> [[slice(0,3,None)],[slice(3,6,None)],[slice(6,9,None)]] or, a more complicated...
def index_to_slices(index): """ take a numpy array of integers (index) and return a nested list of slices such that the slices describe the start, stop points for each integer in the index. e.g. >>> index = np.asarray([0,0,0,1,1,1,2,2,2]) returns >>> [[slice(0,3,None)],[slice(3,6,None)],[slice...
Ask user for agreeing to data set licenses.
def prompt_user(prompt): """Ask user for agreeing to data set licenses.""" # raw_input returns the empty string for "enter" yes = set(['yes', 'y']) no = set(['no','n']) try: print(prompt) choice = input().lower() # would like to test for exception here, but not sure if we ca...
Check if the data set is available on the local machine already.
def data_available(dataset_name=None): """Check if the data set is available on the local machine already.""" try: from itertools import zip_longest except ImportError: from itertools import izip_longest as zip_longest dr = data_resources[dataset_name] zip_urls = (dr['files'], ) ...
Download a file from a url and save it to disk.
def download_url(url, store_directory, save_name=None, messages=True, suffix=''): """Download a file from a url and save it to disk.""" i = url.rfind('/') file = url[i+1:] print(file) dir_name = os.path.join(data_path, store_directory) if save_name is None: save_name = os.path.join(dir_name, fi...
Check with the user that the are happy with terms and conditions for the data set.
def authorize_download(dataset_name=None): """Check with the user that the are happy with terms and conditions for the data set.""" print(('Acquiring resource: ' + dataset_name)) # TODO, check resource is in dictionary! print('') dr = data_resources[dataset_name] print('Details of data: ') p...
Check with the user that the are happy with terms and conditions for the data set, then download it.
def download_data(dataset_name=None): """Check with the user that the are happy with terms and conditions for the data set, then download it.""" try: from itertools import zip_longest except ImportError: from itertools import izip_longest as zip_longest dr = data_resources[dataset_name]...
Find which resources are missing on the local disk for the requested CMU motion capture motions.
def cmu_urls_files(subj_motions, messages = True): ''' Find which resources are missing on the local disk for the requested CMU motion capture motions. ''' dr = data_resources['cmu_mocap_full'] cmu_url = dr['urls'][0] subjects_num = subj_motions[0] motions_num = subj_motions[1] resourc...
Football data from English games since 1993. This downloads data from football-data.co.uk for the given season.
def football_data(season='1314', data_set='football_data'): """Football data from English games since 1993. This downloads data from football-data.co.uk for the given season. """ def league2num(string): league_dict = {'E0':0, 'E1':1, 'E2': 2, 'E3': 3, 'EC':4} return league_dict[string] def ...
The HapMap phase three SNP dataset - 1184 samples out of 11 populations. SNP_matrix (A) encoding [see Paschou et all. 2007 (PCA-Correlated SNPs...)]: Let (B1,B2) be the alphabetically sorted bases, which occur in the j-th SNP, then / 1, iff SNPij==(B1,B1) Aij = | 0, iff SNPij==(B1,B2) ...
def hapmap3(data_set='hapmap3'): """ The HapMap phase three SNP dataset - 1184 samples out of 11 populations. SNP_matrix (A) encoding [see Paschou et all. 2007 (PCA-Correlated SNPs...)]: Let (B1,B2) be the alphabetically sorted bases, which occur in the j-th SNP, then / 1, iff SNPij==(B1,B1...
Samples values of a function from an RBF covariance with very small noise for inputs uniformly distributed between -1 and 1. :param seed: seed to use for random sampling. :type seed: int :param num_samples: number of samples to sample in the function (default 500). :type num_samples: int
def toy_rbf_1d(seed=default_seed, num_samples=500): """ Samples values of a function from an RBF covariance with very small noise for inputs uniformly distributed between -1 and 1. :param seed: seed to use for random sampling. :type seed: int :param num_samples: number of samples to sample in the f...
Data set formed from a mixture of four Gaussians. In each class two of the Gaussians are elongated at right angles to each other and offset to form an approximation to the crescent data that is popular in semi-supervised learning as a toy problem. :param num_data_part: number of data to be sampled (default is 200)...
def crescent_data(num_data=200, seed=default_seed): """ Data set formed from a mixture of four Gaussians. In each class two of the Gaussians are elongated at right angles to each other and offset to form an approximation to the crescent data that is popular in semi-supervised learning as a toy problem. :param ...
Brun and Yoshida's metal creep rupture data.
def creep_data(data_set='creep_rupture'): """Brun and Yoshida's metal creep rupture data.""" if not data_available(data_set): download_data(data_set) path = os.path.join(data_path, data_set) tar_file = os.path.join(path, 'creeprupt.tar') tar = tarfile.open(tar_file) print...
The Candian Institute for Advanced Research 10 image data set. Code for loading in this data is taken from this Boris Babenko's blog post, original code available here: http://bbabenko.tumblr.com/post/86756017649/learning-low-level-vision-feautres-in-10-lines-of-code
def cifar10_patches(data_set='cifar-10'): """The Candian Institute for Advanced Research 10 image data set. Code for loading in this data is taken from this Boris Babenko's blog post, original code available here: http://bbabenko.tumblr.com/post/86756017649/learning-low-level-vision-feautres-in-10-lines-of-code""" ...
Load CMU subject 49's one legged balancing motion that was used by Alvarez, Luengo and Lawrence at AISTATS 2009.
def cmu_mocap_49_balance(data_set='cmu_mocap'): """Load CMU subject 49's one legged balancing motion that was used by Alvarez, Luengo and Lawrence at AISTATS 2009.""" train_motions = ['18', '19'] test_motions = ['20'] data = cmu_mocap('49', train_motions, test_motions, sample_every=4, data_set=data_set)...
Load CMU subject 35's walking and jogging motions, the same data that was used by Taylor, Roweis and Hinton at NIPS 2007. but without their preprocessing. Also used by Lawrence at AISTATS 2007.
def cmu_mocap_35_walk_jog(data_set='cmu_mocap'): """Load CMU subject 35's walking and jogging motions, the same data that was used by Taylor, Roweis and Hinton at NIPS 2007. but without their preprocessing. Also used by Lawrence at AISTATS 2007.""" train_motions = ['01', '02', '03', '04', '05', '06', ...
Load a given subject's training and test motions from the CMU motion capture data.
def cmu_mocap(subject, train_motions, test_motions=[], sample_every=4, data_set='cmu_mocap'): """Load a given subject's training and test motions from the CMU motion capture data.""" # Load in subject skeleton. subject_dir = os.path.join(data_path, data_set) # Make sure the data is downloaded. all_...
derivative of the covariance matrix with respect to the parameters (shape is N x num_inducing x num_params)
def update_gradients_full(self, dL_dK, X, X2=None): """derivative of the covariance matrix with respect to the parameters (shape is N x num_inducing x num_params)""" if X2 is None: X2 = X FX = self._cos(self.basis_alpha[None,:],self.basis_omega[None,:],self.basis_phi[None,:])(X) FX2 = s...
Set the gradients of the posterior distribution of X in its specific form.
def set_X_gradients(self, X, X_grad): """Set the gradients of the posterior distribution of X in its specific form.""" X.mean.gradient, X.variance.gradient = X_grad
Likelihood function given link(f) .. math:: p(y_{i}|\\lambda(f_{i})) = \\frac{\\beta^{\\alpha_{i}}}{\\Gamma(\\alpha_{i})}y_{i}^{\\alpha_{i}-1}e^{-\\beta y_{i}}\\\\ \\alpha_{i} = \\beta y_{i} :param link_f: latent variables link(f) :type link_f: Nx1 array :param ...
def pdf_link(self, link_f, y, Y_metadata=None): """ Likelihood function given link(f) .. math:: p(y_{i}|\\lambda(f_{i})) = \\frac{\\beta^{\\alpha_{i}}}{\\Gamma(\\alpha_{i})}y_{i}^{\\alpha_{i}-1}e^{-\\beta y_{i}}\\\\ \\alpha_{i} = \\beta y_{i} :param link_f: late...
Log Likelihood Function given link(f) .. math:: \\ln p(y_{i}|\lambda(f_{i})) = \\alpha_{i}\\log \\beta - \\log \\Gamma(\\alpha_{i}) + (\\alpha_{i} - 1)\\log y_{i} - \\beta y_{i}\\\\ \\alpha_{i} = \\beta y_{i} :param link_f: latent variables (link(f)) :type link_f: Nx1 a...
def logpdf_link(self, link_f, y, Y_metadata=None): """ Log Likelihood Function given link(f) .. math:: \\ln p(y_{i}|\lambda(f_{i})) = \\alpha_{i}\\log \\beta - \\log \\Gamma(\\alpha_{i}) + (\\alpha_{i} - 1)\\log y_{i} - \\beta y_{i}\\\\ \\alpha_{i} = \\beta y_{i} ...
Gradient of the log likelihood function at y, given link(f) w.r.t link(f) .. math:: \\frac{d \\ln p(y_{i}|\\lambda(f_{i}))}{d\\lambda(f)} = \\beta (\\log \\beta y_{i}) - \\Psi(\\alpha_{i})\\beta\\\\ \\alpha_{i} = \\beta y_{i} :param link_f: latent variables (f) :type li...
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:: \\frac{d \\ln p(y_{i}|\\lambda(f_{i}))}{d\\lambda(f)} = \\beta (\\log \\beta y_{i}) - \\Psi(\\alpha_{i})\\beta\\\\ \\alpha_{i} = \...
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:: \\frac{d^{2} \\ln p(y_{i}|\lambda(f_{i}))}{d^{2}\\lambda(f)} = -\\beta^{2}\\frac{d\\Psi(\\alpha_{i...
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:: \\frac{d^{2} \\ln p(y_{...
Third order derivative log-likelihood function at y given link(f) w.r.t link(f) .. math:: \\frac{d^{3} \\ln p(y_{i}|\lambda(f_{i}))}{d^{3}\\lambda(f)} = -\\beta^{3}\\frac{d^{2}\\Psi(\\alpha_{i})}{d\\alpha_{i}}\\\\ \\alpha_{i} = \\beta y_{i} :param link_f: latent variables link(...
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:: \\frac{d^{3} \\ln p(y_{i}|\lambda(f_{i}))}{d^{3}\\lambda(f)} = -\\beta^{3}\\frac{d^{2}\\Psi(\\alpha_{i})}{d\\alpha_{i}}\\\\ ...
Update the gradients of parameters for warping function This method is called when having new values of parameters for warping function, kernels and other parameters in a normal GP
def parameters_changed(self): """Update the gradients of parameters for warping function This method is called when having new values of parameters for warping function, kernels and other parameters in a normal GP """ # using the warped X to update self.X = self.transfor...
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
def transform_data(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 """ ...
Prediction on the new data Parameters ---------- Xnew : array_like, shape = (n_samples, n_features) The test data. Returns ------- mean : array_like, shape = (n_samples, output.dim) Posterior mean at the location of Xnew var : array_like...
def predict(self, Xnew): """Prediction on the new data Parameters ---------- Xnew : array_like, shape = (n_samples, n_features) The test data. Returns ------- mean : array_like, shape = (n_samples, output.dim) Posterior mean at the locati...
Set the name space for use when calling eval. This needs to contain all the relvant functions for mapping from symbolic python to the numerical python. It also contains variables, cached portions etc.
def _set_namespace(self, namespaces): """Set the name space for use when calling eval. This needs to contain all the relvant functions for mapping from symbolic python to the numerical python. It also contains variables, cached portions etc.""" self.namespace = {} for m in namespaces[::-1]: ...
Extract expressions and variables from the user provided expressions.
def _set_expressions(self, expressions): """Extract expressions and variables from the user provided expressions.""" self.expressions = {} for key, item in expressions.items(): self.expressions[key] = {'function': item}
Pull the variable names out of the provided expressions and separate into cacheable expressions and normal parameters. Those that are only stored in the cache, the parameters are stored in this object.
def _set_variables(self, cacheable): """Pull the variable names out of the provided expressions and separate into cacheable expressions and normal parameters. Those that are only stored in the cache, the parameters are stored in this object.""" # pull the parameters and inputs out of the symbolic pdf ...
Add parameters to the model and initialize with given values.
def _set_parameters(self, parameters): """Add parameters to the model and initialize with given values.""" for theta in self.variables['theta']: val = 1.0 # TODO: improve approach for initializing parameters. if parameters is not None: if theta.name in...
Make sure namespace gets updated when setting attributes.
def _set_attribute(self, name, value): """Make sure namespace gets updated when setting attributes.""" setattr(self, name, value) self.namespace.update({name: getattr(self, name)})
Extract a list of expressions from the dictionary of expressions.
def update_expression_list(self): """Extract a list of expressions from the dictionary of expressions.""" self.expression_list = [] # code arrives in dictionary, but is passed in this list self.expression_keys = [] # Keep track of the dictionary keys. self.expression_order = [] # This ma...
Generate code for the list of expressions provided using the common sub-expression eliminator to separate out portions that are computed multiple times.
def _gen_code(self): """Generate code for the list of expressions provided using the common sub-expression eliminator to separate out portions that are computed multiple times.""" # This is the dictionary that stores all the generated code. self.code = {} def match_key(expr): ...
Convert the given symbolic expression into code.
def _expr2code(self, arg_list, expr): """Convert the given symbolic expression into code.""" code = lambdastr(arg_list, expr) function_code = code.split(':')[1].strip() #for arg in arg_list: # function_code = function_code.replace(arg.name, 'self.'+arg.name) return fu...
Prepare code for string writing.
def _print_code(self, code): """Prepare code for string writing.""" # This needs a rewrite --- it doesn't check for match clashes! So sub11 would be replaced by sub1 before being replaced with sub11!! for key in self.variables.keys(): for arg in self.variables[key]: c...
Helper function for human friendly display of the symbolic components.
def _display_expression(self, keys, user_substitutes={}): """Helper function for human friendly display of the symbolic components.""" # Create some pretty maths symbols for the display. sigma, alpha, nu, omega, l, variance = sym.var('\sigma, \alpha, \nu, \omega, \ell, \sigma^2') substit...
Here you put the values, which were collected before in the right places. E.g. set the gradients of parameters, etc.
def _outer_values_update(self, full_values): """ Here you put the values, which were collected before in the right places. E.g. set the gradients of parameters, etc. """ super(BayesianGPLVMMiniBatch, self)._outer_values_update(full_values) if self.has_uncertain_inputs(): ...
Compute the covariance matrix between X and X2.
def K(self, X, X2=None): """Compute the covariance matrix between X and X2.""" X,slices = X[:,:-1],index_to_slices(X[:,-1]) if X2 is None: X2,slices2 = X,slices K = np.zeros((X.shape[0], X.shape[0])) ...
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 K = np.zeros((X.shape[0]...
Do all the computations for the ode parts of the covariance function.
def _dK_ode_dtheta(self, target): """Do all the computations for the ode parts of the covariance function.""" t_ode = self._t[self._index>0] dL_dK_ode = self._dL_dK[self._index>0, :] index_ode = self._index[self._index>0]-1 if self._t2 is None: if t_ode.size==0: ...
Extract times and output indices from the input matrix X. Times are ordered according to their index for convenience of computation, this ordering is stored in self._order and self.order2. These orderings are then mapped back to the original ordering (in X) using self._rorder and self._rorder2.
def _extract_t_indices(self, X, X2=None, dL_dK=None): """Extract times and output indices from the input matrix X. Times are ordered according to their index for convenience of computation, this ordering is stored in self._order and self.order2. These orderings are then mapped back to the original ordering (in ...
Perform main body of computations for the ode1 covariance function.
def _K_computations(self, X, X2): """Perform main body of computations for the ode1 covariance function.""" # First extract times and indices. self._extract_t_indices(X, X2) self._K_compute_eq() self._K_compute_ode_eq() if X2 is None: self._K_eq_ode = self._K...
Compute covariance for latent covariance.
def _K_compute_eq(self): """Compute covariance for latent covariance.""" t_eq = self._t[self._index==0] if self._t2 is None: if t_eq.size==0: self._K_eq = np.zeros((0, 0)) return self._dist2 = np.square(t_eq[:, None] - t_eq[None, :]) ...
Compute the cross covariances between latent exponentiated quadratic and observed ordinary differential equations. :param transpose: if set to false the exponentiated quadratic is on the rows of the matrix and is computed according to self._t, if set to true it is on the columns and is computed according to se...
def _K_compute_ode_eq(self, transpose=False): """Compute the cross covariances between latent exponentiated quadratic and observed ordinary differential equations. :param transpose: if set to false the exponentiated quadratic is on the rows of the matrix and is computed according to self._t, if set to ...
Helper function for computing part of the ode1 covariance function. :param t: first time input. :type t: array :param index: Indices of first output. :type index: array of int :param t2: second time input. :type t2: array :param index2: Indices of second output. ...
def _compute_H(self, t, index, t2, index2, update_derivatives=False, stationary=False): """Helper function for computing part of the ode1 covariance function. :param t: first time input. :type t: array :param index: Indices of first output. :type index: array of int :par...
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...
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, indexD, output_dim): """ The SVI-VarDTC inference """ N, D, Mr, Mc, Qr, Qc = Y.shape[0], output_dim,Zr.shape[0], Zc.shape[0], Zr.shape[1], Zc.shape[1] uncertain_inputs_r = isinstance...
Find common subarrays of 2 dimensional X, where axis is the axis to apply the search over. Common subarrays are returned as a dictionary of <subarray, [index]> pairs, where the subarray is a tuple representing the subarray and the index is the index for the subarray in X, where index is the index to the rem...
def common_subarrays(X, axis=0): """ Find common subarrays of 2 dimensional X, where axis is the axis to apply the search over. Common subarrays are returned as a dictionary of <subarray, [index]> pairs, where the subarray is a tuple representing the subarray and the index is the index for the subar...
Prediction for data set Yindex[default=0]. This predicts the output mean and variance for the dataset given in Ylist[Yindex]
def predict(self, Xnew, full_cov=False, Y_metadata=None, kern=None, Yindex=0): """ Prediction for data set Yindex[default=0]. This predicts the output mean and variance for the dataset given in Ylist[Yindex] """ b = self.bgplvms[Yindex] self.posterior = b.posterior ...
Plot input sensitivity for all datasets, to see which input dimensions are significant for which dataset. :param titles: titles for axes of datasets kwargs go into plot_ARD for each kernel.
def plot_scales(self, titles=None, fig_kwargs={}, **kwargs): """ Plot input sensitivity for all datasets, to see which input dimensions are significant for which dataset. :param titles: titles for axes of datasets kwargs go into plot_ARD for each kernel. """ fro...
see plotting.matplot_dep.dim_reduction_plots.plot_latent if predict_kwargs is None, will plot latent spaces for 0th dataset (and kernel), otherwise give predict_kwargs=dict(Yindex='index') for plotting only the latent space of dataset with 'index'.
def plot_latent(self, labels=None, which_indices=None, resolution=60, legend=True, plot_limits=None, updates=False, kern=None, marker='<>^vsd', num_samples=1000, projection='2d', predict_kwargs={}, scatter_kw...
Given a trained MRD model, this function looks at the optimized ARD weights (lengthscales) and decides which part of the latent space is shared across views or private, according to a threshold. The threshold is applied after all weights are normalized so that the maximum value is 1.
def factorize_space(self, threshold=0.005, printOut=False, views=None): """ Given a trained MRD model, this function looks at the optimized ARD weights (lengthscales) and decides which part of the latent space is shared across views or private, according to a threshold. The threshold is ...
Plot the mean of the GP. 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. :param plot_limits: The limits of the plot. If 1D [xmin,xmax], if 2D [[xmin,ymin],[xmax,ymax]]. Defaluts to data limits :type plot_limits: np.ar...
def plot_mean(self, plot_limits=None, fixed_inputs=None, resolution=None, plot_raw=False, apply_link=False, visible_dims=None, which_data_ycols='all', levels=20, projection='2d', label='gp mean', predict_kw=None, **kwargs)...
Plot the confidence interval between the percentiles lower and upper. 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. Give the Y_metadata in the predict_kw if you need it. :para...
def plot_confidence(self, lower=2.5, upper=97.5, plot_limits=None, fixed_inputs=None, resolution=None, plot_raw=False, apply_link=False, visible_dims=None, which_data_ycols='all', label='gp confidence', predict_kw=None, **kwargs): """ Plot th...
Plot the mean of the GP. 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. :param plot_limits: The limits of the plot. If 1D [xmin,xmax], if 2D [[xmin,ymin],[xmax,ymax]]. Defaluts to data limits :type plot_limits: np.ar...
def plot_samples(self, plot_limits=None, fixed_inputs=None, resolution=None, plot_raw=True, apply_link=False, visible_dims=None, which_data_ycols='all', samples=3, projection='2d', label='gp_samples', predict_kw=None, **kwargs): """...
Plot the confidence interval between the percentiles lower and upper. 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. Give the Y_metadata in the predict_kw if you need it. :param...
def plot_density(self, plot_limits=None, fixed_inputs=None, resolution=None, plot_raw=False, apply_link=False, visible_dims=None, which_data_ycols='all', levels=35, label='gp density', predict_kw=None, **kwargs): """ Plot the co...
Convinience function for plotting the fit of a GP. This is the same as plot, except it plots the latent function fit of the GP! If you want fine graned control use the specific plotting functions supplied in the model. You can deactivate the legend for this one plot by supplying None to label. Give t...
def plot_f(self, plot_limits=None, fixed_inputs=None, resolution=None, apply_link=False, which_data_ycols='all', which_data_rows='all', visible_dims=None, levels=20, samples=0, lower=2.5, upper=97.5, plot_density=False, pl...
Convenience function for plotting the fit of a GP. 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. If you want fine graned control use the specific plotting functions supplied in the model. :param plot_limits: The lim...
def plot(self, plot_limits=None, fixed_inputs=None, resolution=None, plot_raw=False, apply_link=False, which_data_ycols='all', which_data_rows='all', visible_dims=None, levels=20, samples=0, samples_likelihood=0, lower=2.5, upper=97.5, ...
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, data=None): """ 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_dic...
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...
Builds a kernel for an Intrinsic Coregionalization Model :input_dim: Input dimensionality (does not include dimension of indices) :num_outputs: Number of outputs :param kernel: kernel that will be multiplied by the coregionalize kernel (matrix B). :type kernel: a GPy kernel :param W_rank: number tu...
def ICM(input_dim, num_outputs, kernel, W_rank=1,W=None,kappa=None,name='ICM'): """ Builds a kernel for an Intrinsic Coregionalization Model :input_dim: Input dimensionality (does not include dimension of indices) :num_outputs: Number of outputs :param kernel: kernel that will be multiplied by the ...
Builds a kernel for an Linear Coregionalization Model :input_dim: Input dimensionality (does not include dimension of indices) :num_outputs: Number of outputs :param kernel: kernel that will be multiplied by the coregionalize kernel (matrix B). :type kernel: a GPy kernel :param W_rank: number tuple...
def LCM(input_dim, num_outputs, kernels_list, W_rank=1,name='ICM'): """ Builds a kernel for an Linear Coregionalization Model :input_dim: Input dimensionality (does not include dimension of indices) :num_outputs: Number of outputs :param kernel: kernel that will be multiplied by the coregionalize k...
Builds a kernel for an Intrinsic Coregionalization Model :input_dim: Input dimensionality :num_outputs: Number of outputs :param kernel: kernel that will be multiplied by the coregionalize kernel (matrix B). :type kernel: a GPy kernel :param W_rank: number tuples of the corregionalization parameter...
def Private(input_dim, num_outputs, kernel, output, kappa=None,name='X'): """ Builds a kernel for an Intrinsic Coregionalization Model :input_dim: Input dimensionality :num_outputs: Number of outputs :param kernel: kernel that will be multiplied by the coregionalize kernel (matrix B). :type ker...
Kernel function 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. K(X, X2) = K_of_r((X-X2)**2)
def K(self, X, X2=None): """ Kernel function 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. K(X, X2) = K_of_r((X-X2)**2) """ r = self._scaled_dist(X, X2) return self.K_of_r(...
compute the derivative of K wrt X going through X
def dK_dr_via_X(self, X, X2): """ compute the derivative of K wrt X going through X """ #a convenience function, so we can cache dK_dr return self.dK_dr(self._scaled_dist(X, X2))
Compute the Euclidean distance between each row of X and X2, or between each pair of rows of X if X2 is None.
def _unscaled_dist(self, X, X2=None): """ Compute the Euclidean distance between each row of X and X2, or between each pair of rows of X if X2 is None. """ #X, = self._slice_X(X) if X2 is None: Xsq = np.sum(np.square(X),1) r2 = -2.*tdot(X) + (Xsq[:...
Efficiently compute the scaled distance, r. ..math:: r = \sqrt( \sum_{q=1}^Q (x_q - x'q)^2/l_q^2 ) Note that if thre is only one lengthscale, l comes outside the sum. In this case we compute the unscaled distance first (in a separate function for caching) and divide by leng...
def _scaled_dist(self, X, X2=None): """ Efficiently compute the scaled distance, r. ..math:: r = \sqrt( \sum_{q=1}^Q (x_q - x'q)^2/l_q^2 ) Note that if thre is only one lengthscale, l comes outside the sum. In this case we compute the unscaled distance first (in a s...
Given the derivative of the objective wrt the covariance matrix (dL_dK), compute the gradient wrt the parameters of this kernel, and store in the parameters object as e.g. self.variance.gradient
def update_gradients_full(self, dL_dK, X, X2=None, reset=True): """ Given the derivative of the objective wrt the covariance matrix (dL_dK), compute the gradient wrt the parameters of this kernel, and store in the parameters object as e.g. self.variance.gradient """ self....
Specially intended for the Grid regression case. Given the computed log likelihood derivates, update the corresponding kernel and likelihood gradients. Useful for when gradients have been computed a priori.
def update_gradients_direct(self, dL_dVar, dL_dLen): """ Specially intended for the Grid regression case. Given the computed log likelihood derivates, update the corresponding kernel and likelihood gradients. Useful for when gradients have been computed a priori. """ ...
Compute the elementwise inverse of the distance matrix, expecpt on the diagonal, where we return zero (the distance on the diagonal is zero). This term appears in derviatives.
def _inv_dist(self, X, X2=None): """ Compute the elementwise inverse of the distance matrix, expecpt on the diagonal, where we return zero (the distance on the diagonal is zero). This term appears in derviatives. """ dist = self._scaled_dist(X, X2).copy() return 1...
Given the derivative of the objective wrt K (dL_dK), compute the derivative wrt X
def gradients_X(self, dL_dK, X, X2=None): """ Given the derivative of the objective wrt K (dL_dK), compute the derivative wrt X """ if use_stationary_cython: return self._gradients_X_cython(dL_dK, X, X2) else: return self._gradients_X_pure(dL_dK, X, X2)
Given the derivative of the objective K(dL_dK), compute the second derivative of K wrt X and X2: returns the full covariance matrix [QxQ] of the input dimensionfor each pair or vectors, thus the returned array is of shape [NxNxQxQ]. ..math: \frac{\partial^2 K}{\partial X2 ^2} = - \...
def gradients_XX(self, dL_dK, X, X2=None): """ Given the derivative of the objective K(dL_dK), compute the second derivative of K wrt X and X2: returns the full covariance matrix [QxQ] of the input dimensionfor each pair or vectors, thus the returned array is of shape [NxNxQxQ]. ...
Given the derivative of the objective dL_dK, compute the second derivative of K wrt X: ..math: \frac{\partial^2 K}{\partial X\partial X} ..returns: dL2_dXdX: [NxQxQ]
def gradients_XX_diag(self, dL_dK_diag, X): """ Given the derivative of the objective dL_dK, compute the second derivative of K wrt X: ..math: \frac{\partial^2 K}{\partial X\partial X} ..returns: dL2_dXdX: [NxQxQ] """ dL_dK_diag = dL_dK_diag.copy()...
Return the state space representation of the covariance.
def sde(self): """ Return the state space representation of the covariance. """ variance = float(self.variance.values) lengthscale = float(self.lengthscale.values) foo = np.sqrt(3.)/lengthscale F = np.array([[0, 1], [-foo**2, -2*foo]]) L = np.array(...
Return the Gram matrix of the vector of functions F with respect to the RKHS norm. The use of this function is limited to input_dim=1. :param F: vector of functions :type F: np.array :param F1: vector of derivatives of F :type F1: np.array :param F2: vector of second derivatives...
def Gram_matrix(self, F, F1, F2, F3, lower, upper): """ Return the Gram matrix of the vector of functions F with respect to the RKHS norm. The use of this function is limited to input_dim=1. :param F: vector of functions :type F: np.array :param F1: vector of derivatives of F ...
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...
Convenience function for returning back fixed_inputs where the other inputs are fixed using fix_routine :param model: model :type model: Model :param non_fixed_inputs: dimensions of non fixed inputs :type non_fixed_inputs: list :param fix_routine: fixing routine to use, 'mean', 'median', 'zero' ...
def fixed_inputs(model, non_fixed_inputs, fix_routine='median', as_list=True, X_all=False): """ Convenience function for returning back fixed_inputs where the other inputs are fixed using fix_routine :param model: model :type model: Model :param non_fixed_inputs: dimensions of non fixed inputs ...
Infer the distribution of X for the new observed data *Y_new*. :param model: the GPy model used in inference :type model: GPy.core.Model :param Y_new: the new observed data for inference :type Y_new: numpy.ndarray :param optimize: whether to optimize the location of new X (True by default) :typ...
def infer_newX(model, Y_new, optimize=True, init='L2'): """ Infer the distribution of X for the new observed data *Y_new*. :param model: the GPy model used in inference :type model: GPy.core.Model :param Y_new: the new observed data for inference :type Y_new: numpy.ndarray :param optimize: ...
Return the state space representation of the covariance. Note! For Sparse GP inference too small or two high values of lengthscale lead to instabilities. This is because Qc are too high or too low and P_inf are not full rank. This effect depends on approximatio order. For N = 10...
def sde(self): """ Return the state space representation of the covariance. Note! For Sparse GP inference too small or two high values of lengthscale lead to instabilities. This is because Qc are too high or too low and P_inf are not full rank. This effect depends on app...
Return the state space representation of the covariance.
def sde(self): """ Return the state space representation of the covariance. """ variance = float(self.variance.values) lengthscale = float(self.lengthscale) F = np.array(((-1.0/lengthscale,),)) L = np.array(((1.0,),)) Qc = np.array( ((2.0*variance/lengt...
Likelihood function given link(f) :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 in weibull distribution :returns: likelihood evaluated for this point :rtype: floa...
def pdf_link(self, link_f, y, Y_metadata=None): """ Likelihood function given link(f) :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 in weibull distribution ...
Log Likelihood Function given link(f) .. math:: \\ln p(y_{i}|\lambda(f_{i})) = \\alpha_{i}\\log \\beta - \\log \\Gamma(\\alpha_{i}) + (\\alpha_{i} - 1)\\log y_{i} - \\beta y_{i}\\\\ \\alpha_{i} = \\beta y_{i} :param link_f: latent variables (link(f)) :type link_f: Nx1 a...
def logpdf_link(self, link_f, y, Y_metadata=None): """ Log Likelihood Function given link(f) .. math:: \\ln p(y_{i}|\lambda(f_{i})) = \\alpha_{i}\\log \\beta - \\log \\Gamma(\\alpha_{i}) + (\\alpha_{i} - 1)\\log y_{i} - \\beta y_{i}\\\\ \\alpha_{i} = \\beta y_{i} ...
Gradient of the log likelihood function at y, given link(f) w.r.t link(f) .. math:: \\frac{d \\ln p(y_{i}|\\lambda(f_{i}))}{d\\lambda(f)} = \\beta (\\log \\beta y_{i}) - \\Psi(\\alpha_{i})\\beta\\\\ \\alpha_{i} = \\beta y_{i} :param link_f: latent variables (f) :type li...
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:: \\frac{d \\ln p(y_{i}|\\lambda(f_{i}))}{d\\lambda(f)} = \\beta (\\log \\beta y_{i}) - \\Psi(\\alpha_{i})\\beta\\\\ \\alpha_{i} = \...
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:: \\frac{d^{2} \\ln p(y_{i}|\lambda(f_{i}))}{d^{2}\\lambda(f)} = -\\beta^{2}\\frac{d\\Psi(\\alpha_{i...
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:: \\frac{d^{2} \\ln p(y_{...
Third order derivative log-likelihood function at y given link(f) w.r.t link(f) .. math:: \\frac{d^{3} \\ln p(y_{i}|\lambda(f_{i}))}{d^{3}\\lambda(f)} = -\\beta^{3}\\frac{d^{2}\\Psi(\\alpha_{i})}{d\\alpha_{i}}\\\\ \\alpha_{i} = \\beta y_{i} :param link_f: latent variables link(...
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:: \\frac{d^{3} \\ln p(y_{i}|\lambda(f_{i}))}{d^{3}\\lambda(f)} = -\\beta^{3}\\frac{d^{2}\\Psi(\\alpha_{i})}{d\\alpha_{i}}\\\\ ...
First order derivative derivative of loglikelihood wrt r:shape parameter :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 in gamma distribution :returns: third derivative of ...
def dlogpdf_dlink_dr(self, inv_link_f, y, Y_metadata=None): """ First order derivative derivative of loglikelihood wrt r:shape parameter :param link_f: latent variables link(f) :type link_f: Nx1 array :param y: data :type y: Nx1 array :param Y_metadata: Y_metadat...
Returns a set of samples of observations conditioned on a given value of latent variable f. :param gp: latent variable
def samples(self, gp, Y_metadata=None): """ Returns a set of samples of observations conditioned on a given value of latent variable f. :param gp: latent variable """ orig_shape = gp.shape gp = gp.flatten() weibull_samples = np.array([sp.stats.weibull_min.rvs(sel...
The first phase of inference: Compute: log-likelihood, dL_dKmm Cached intermediate results: Kmm, KmmInv,
def inference_likelihood(self, kern, X, Z, likelihood, Y): """ The first phase of inference: Compute: log-likelihood, dL_dKmm Cached intermediate results: Kmm, KmmInv, """ num_data, output_dim = Y.shape input_dim = Z.shape[0] if self.mpi_comm != None: ...
The second phase of inference: Computing the derivatives over a minibatch of Y Compute: dL_dpsi0, dL_dpsi1, dL_dpsi2, dL_dthetaL return a flag showing whether it reached the end of Y (isEnd)
def inference_minibatch(self, kern, X, Z, likelihood, Y): """ The second phase of inference: Computing the derivatives over a minibatch of Y Compute: dL_dpsi0, dL_dpsi1, dL_dpsi2, dL_dthetaL return a flag showing whether it reached the end of Y (isEnd) """ num_data, outp...
The second phase of inference: Computing the derivatives over a minibatch of Y Compute: dL_dpsi0, dL_dpsi1, dL_dpsi2, dL_dthetaL return a flag showing whether it reached the end of Y (isEnd)
def inference_minibatch(self, kern, X, Z, likelihood, Y, Zp): """ The second phase of inference: Computing the derivatives over a minibatch of Y Compute: dL_dpsi0, dL_dpsi1, dL_dpsi2, dL_dthetaL return a flag showing whether it reached the end of Y (isEnd) """ num_data, ...