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 """ input_dict = su...
Specially intended for Grid regression.
def get_one_dimensional_kernel(self, dim): """ Specially intended for Grid regression. """ oneDkernel = GridRBF(input_dim=1, variance=self.variance.copy(), originalDimensions=dim) return oneDkernel
Load in a data set of marker points from the Ohio State University C3D motion capture files (http://accad.osu.edu/research/mocap/mocap_data.htm).
def load_text_data(dataset, directory, centre=True): """Load in a data set of marker points from the Ohio State University C3D motion capture files (http://accad.osu.edu/research/mocap/mocap_data.htm).""" points, point_names = parse_text(os.path.join(directory, dataset + '.txt'))[0:2] # Remove markers wher...
Parse data from Ohio State University text mocap files (http://accad.osu.edu/research/mocap/mocap_data.htm).
def parse_text(file_name): """Parse data from Ohio State University text mocap files (http://accad.osu.edu/research/mocap/mocap_data.htm).""" # Read the header fid = open(file_name, 'r') point_names = np.array(fid.readline().split())[2:-1:3] fid.close() for i in range(len(point_names)): ...
Read a file detailing which markers should be connected to which for motion capture data.
def read_connections(file_name, point_names): """Read a file detailing which markers should be connected to which for motion capture data.""" connections = [] fid = open(file_name, 'r') line=fid.readline() while(line): connections.append(np.array(line.split(','))) connections[-1][0]...
Take a tree and set the children according to the parents. Takes a tree structure which lists the parents of each vertex and computes the children for each vertex and places them in.
def find_children(self): """Take a tree and set the children according to the parents. Takes a tree structure which lists the parents of each vertex and computes the children for each vertex and places them in.""" for i in range(len(self.vertices)): self.vertices[i].children...
Take a tree and set the parents according to the children Takes a tree structure which lists the children of each vertex and computes the parents for each vertex and places them in.
def find_parents(self): """Take a tree and set the parents according to the children Takes a tree structure which lists the children of each vertex and computes the parents for each vertex and places them in.""" for i in range(len(self.vertices)): self.vertices[i].parents = ...
Finds the index of the root node of the tree.
def find_root(self): """Finds the index of the root node of the tree.""" self.find_parents() index = 0 while len(self.vertices[index].parents)>0: index = self.vertices[index].parents[0] return index
Give the index associated with a given vertex id.
def get_index_by_id(self, id): """Give the index associated with a given vertex id.""" for i in range(len(self.vertices)): if self.vertices[i].id == id: return i raise ValueError('Reverse look up of id failed.')
Give the index associated with a given vertex name.
def get_index_by_name(self, name): """Give the index associated with a given vertex name.""" for i in range(len(self.vertices)): if self.vertices[i].name == name: return i raise ValueError('Reverse look up of name failed.')
Order vertices in the graph such that parents always have a lower index than children.
def order_vertices(self): """Order vertices in the graph such that parents always have a lower index than children.""" ordered = False while ordered == False: for i in range(len(self.vertices)): ordered = True for parent in self.vertices[i].pa...
Swap two vertices in the tree structure array. swap_vertex swaps the location of two vertices in a tree structure array. :param tree: the tree for which two vertices are to be swapped. :param i: the index of the first vertex to be swapped. :param j: the index of the second vertex to be...
def swap_vertices(self, i, j): """ Swap two vertices in the tree structure array. swap_vertex swaps the location of two vertices in a tree structure array. :param tree: the tree for which two vertices are to be swapped. :param i: the index of the first vertex to be swapped. ...
Remove discontinuities in angle channels so that they don't cause artifacts in algorithms that rely on the smoothness of the functions.
def smooth_angle_channels(self, channels): """Remove discontinuities in angle channels so that they don't cause artifacts in algorithms that rely on the smoothness of the functions.""" for vertex in self.vertices: for col in vertex.meta['rot_ind']: if col: ...
Loads an ASF file into a skeleton structure. :param file_name: The file name to load in.
def load_skel(self, file_name): """ Loads an ASF file into a skeleton structure. :param file_name: The file name to load in. """ fid = open(file_name, 'r') self.read_skel(fid) fid.close() self.name = file_name
Read bone data from an acclaim skeleton file stream.
def read_bonedata(self, fid): """Read bone data from an acclaim skeleton file stream.""" bone_count = 0 lin = self.read_line(fid) while lin[0]!=':': parts = lin.split() if parts[0] == 'begin': bone_count += 1 self.vertices.append(v...
Read channels from an acclaim file.
def read_channels(self, fid): """Read channels from an acclaim file.""" bones = [[] for i in self.vertices] num_channels = 0 for vertex in self.vertices: num_channels = num_channels + len(vertex.meta['channels']) lin = self.read_line(fid) while lin != ':DEGRE...
Read documentation from an acclaim skeleton file stream.
def read_documentation(self, fid): """Read documentation from an acclaim skeleton file stream.""" lin = self.read_line(fid) while lin[0] != ':': self.documentation.append(lin) lin = self.read_line(fid) return lin
Read hierarchy information from acclaim skeleton file stream.
def read_hierarchy(self, fid): """Read hierarchy information from acclaim skeleton file stream.""" lin = self.read_line(fid) while lin != 'end': parts = lin.split() if lin != 'begin': ind = self.get_index_by_name(parts[0]) ...
Read a line from a file string and check it isn't either empty or commented before returning.
def read_line(self, fid): """Read a line from a file string and check it isn't either empty or commented before returning.""" lin = '#' while lin[0] == '#': lin = fid.readline().strip() if lin == '': return lin return lin
Read the root node from an acclaim skeleton file stream.
def read_root(self, fid): """Read the root node from an acclaim skeleton file stream.""" lin = self.read_line(fid) while lin[0] != ':': parts = lin.split() if parts[0]=='order': order = [] for i in range(1, len(parts)): ...
Loads an acclaim skeleton format from a file stream.
def read_skel(self, fid): """Loads an acclaim skeleton format from a file stream.""" lin = self.read_line(fid) while lin: if lin[0]==':': if lin[1:]== 'name': lin = self.read_line(fid) self.name = lin elif lin[1:...
Read units from an acclaim skeleton file stream.
def read_units(self, fid): """Read units from an acclaim skeleton file stream.""" lin = self.read_line(fid) while lin[0] != ':': parts = lin.split() if parts[0]=='mass': self.mass = float(parts[1]) elif parts[0]=='length': ...
Get indices for the skeleton from the channels when loading in channel data.
def resolve_indices(self, index, start_val): """Get indices for the skeleton from the channels when loading in channel data.""" channels = self.vertices[index].meta['channels'] base_channel = start_val rot_ind = -np.ones(3, dtype=int) pos_ind = -np.ones(3, dtype=int) fo...
Set the meta information at each vertex to contain the correct matrices C and Cinv as prescribed by the rotations and rotation orders.
def set_rotation_matrices(self): """Set the meta information at each vertex to contain the correct matrices C and Cinv as prescribed by the rotations and rotation orders.""" for i in range(len(self.vertices)): self.vertices[i].meta['C'] = rotation_matrix(self.vertices[i].meta['axis'][0], ...
Compute the diagonal of the covariance matrix for X.
def Kdiag(self, X): """Compute the diagonal of the covariance matrix for X.""" X_prod = self._comp_prod(X) return self.variance*four_over_tau*np.arcsin(X_prod/(X_prod+1.))
Derivative of the covariance with respect to the parameters.
def update_gradients_full(self, dL_dK, X, X2=None): """Derivative of the covariance with respect to the parameters.""" dvar, dw, db = self._comp_grads(dL_dK, X, X2)[:3] self.variance.gradient = dvar self.weight_variance.gradient = dw self.bias_variance.gradient = db
Derivative of the covariance matrix with respect to X
def gradients_X(self, dL_dK, X, X2): """Derivative of the covariance matrix with respect to X""" return self._comp_grads(dL_dK, X, X2)[3]
Derivative of the covariance matrix with respect to X
def gradients_X_X2(self, dL_dK, X, X2): """Derivative of the covariance matrix with respect to X""" return self._comp_grads(dL_dK, X, X2)[3:]
return the value of the parameters.
def _get_params(self): """return the value of the parameters.""" return np.hstack((self.varianceU,self.varianceY, self.lengthscaleU,self.lengthscaleY))
set the value of the parameters.
def _set_params(self, x): """set the value of the parameters.""" assert x.size == self.num_params self.varianceU = x[0] self.varianceY = x[1] self.lengthscaleU = x[2] self.lengthscaleY = x[3]
Compute the covariance matrix between X and X2.
def K(self, X, X2, target): """Compute the covariance matrix between X and X2.""" if X2 is None: X2 = X # i1 = X[:,1] # i2 = X2[:,1] # X = X[:,0].reshape(-1,1) # X2 = X2[:,0].reshape(-1,1) dist = np.abs(X - X2.T) ly=1/self.lengthscaleY lu=np.s...
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.""" ly=1/self.lengthscaleY lu=np.sqrt(3)/self.lengthscaleU #ly=self.lengthscaleY #lu=self.lengthscaleU k1 = (2*lu+ly)/(lu+ly)**2 k2 = (ly-2*lu + 2*lu-ly ) / (ly-l...
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.""" if X2 is None: X2 = X dist = np.abs(X - X2.T) ly=1/self.lengthscaleY lu=np.sqrt(3)/self.lengthscaleU #ly=self.lengthscaleY #lu=self.lengt...
Returns a GridPosterior class containing essential quantities of the posterior
def inference(self, kern, X, likelihood, Y, Y_metadata=None): """ Returns a GridPosterior class containing essential quantities of the posterior """ N = X.shape[0] #number of training points D = X.shape[1] #number of dimensions Kds = np.zeros(D, dtype=object) #vector fo...
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 = sup...
Pull out the gradients, be careful as the order must match the order in which the parameters are added
def update_gradients(self, grads): """ Pull out the gradients, be careful as the order must match the order in which the parameters are added """ self.sigma2.gradient = grads[0] self.v.gradient = grads[1]
Likelihood function given link(f) .. math:: p(y_{i}|\\lambda(f_{i})) = \\frac{\\Gamma\\left(\\frac{v+1}{2}\\right)}{\\Gamma\\left(\\frac{v}{2}\\right)\\sqrt{v\\pi\\sigma^{2}}}\\left(1 + \\frac{1}{v}\\left(\\frac{(y_{i} - \\lambda(f_{i}))^{2}}{\\sigma^{2}}\\right)\\right)^{\\frac{-v+1}{2}} ...
def pdf_link(self, inv_link_f, y, Y_metadata=None): """ Likelihood function given link(f) .. math:: p(y_{i}|\\lambda(f_{i})) = \\frac{\\Gamma\\left(\\frac{v+1}{2}\\right)}{\\Gamma\\left(\\frac{v}{2}\\right)\\sqrt{v\\pi\\sigma^{2}}}\\left(1 + \\frac{1}{v}\\left(\\frac{(y_{i} - \\lamb...
Log Likelihood Function given link(f) .. math:: \\ln p(y_{i}|\lambda(f_{i})) = \\ln \\Gamma\\left(\\frac{v+1}{2}\\right) - \\ln \\Gamma\\left(\\frac{v}{2}\\right) - \\ln \\sqrt{v \\pi\\sigma^{2}} - \\frac{v+1}{2}\\ln \\left(1 + \\frac{1}{v}\\left(\\frac{(y_{i} - \lambda(f_{i}))^{2}}{\\sigma^{2}}\\r...
def logpdf_link(self, inv_link_f, y, Y_metadata=None): """ Log Likelihood Function given link(f) .. math:: \\ln p(y_{i}|\lambda(f_{i})) = \\ln \\Gamma\\left(\\frac{v+1}{2}\\right) - \\ln \\Gamma\\left(\\frac{v}{2}\\right) - \\ln \\sqrt{v \\pi\\sigma^{2}} - \\frac{v+1}{2}\\ln \\left(...
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)} = \\frac{(v+1)(y_{i}-\lambda(f_{i}))}{(y_{i}-\lambda(f_{i}))^{2} + \\sigma^{2}v} :param inv_link_f: latent variables (f) :type inv_link_f: Nx1 ar...
def dlogpdf_dlink(self, inv_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)} = \\frac{(v+1)(y_{i}-\lambda(f_{i}))}{(y_{i}-\lambda(f_{i}))^{2} + \\sigma^{2}v} ...
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)} = \\frac{(v+1)((y_{i}-\lambda(f_{i}))...
def d2logpdf_dlink2(self, inv_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...
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)} = \\frac{-2(v+1)((y_{i} - \lambda(f_{i}))^3 - 3(y_{i} - \lambda(f_{i})) \\sigma^{2} v))}{((y_{i} - \lambda(f_{i})) + \\sigma^{2} v)^3} :par...
def d3logpdf_dlink3(self, inv_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)} = \\frac{-2(v+1)((y_{i} - \lambda(f_{i}))^3 - 3(y_{i} - \lambda(f_{i}...
Gradient of the log-likelihood function at y given f, w.r.t variance parameter (t_noise) .. math:: \\frac{d \\ln p(y_{i}|\lambda(f_{i}))}{d\\sigma^{2}} = \\frac{v((y_{i} - \lambda(f_{i}))^{2} - \\sigma^{2})}{2\\sigma^{2}(\\sigma^{2}v + (y_{i} - \lambda(f_{i}))^{2})} :param inv_link_f: late...
def dlogpdf_link_dvar(self, inv_link_f, y, Y_metadata=None): """ Gradient of the log-likelihood function at y given f, w.r.t variance parameter (t_noise) .. math:: \\frac{d \\ln p(y_{i}|\lambda(f_{i}))}{d\\sigma^{2}} = \\frac{v((y_{i} - \lambda(f_{i}))^{2} - \\sigma^{2})}{2\\sigma^{...
Derivative of the dlogpdf_dlink w.r.t variance parameter (t_noise) .. math:: \\frac{d}{d\\sigma^{2}}(\\frac{d \\ln p(y_{i}|\lambda(f_{i}))}{df}) = \\frac{-2\\sigma v(v + 1)(y_{i}-\lambda(f_{i}))}{(y_{i}-\lambda(f_{i}))^2 + \\sigma^2 v)^2} :param inv_link_f: latent variables inv_link_f ...
def dlogpdf_dlink_dvar(self, inv_link_f, y, Y_metadata=None): """ Derivative of the dlogpdf_dlink w.r.t variance parameter (t_noise) .. math:: \\frac{d}{d\\sigma^{2}}(\\frac{d \\ln p(y_{i}|\lambda(f_{i}))}{df}) = \\frac{-2\\sigma v(v + 1)(y_{i}-\lambda(f_{i}))}{(y_{i}-\lambda(f_{i})...
Gradient of the hessian (d2logpdf_dlink2) w.r.t variance parameter (t_noise) .. math:: \\frac{d}{d\\sigma^{2}}(\\frac{d^{2} \\ln p(y_{i}|\lambda(f_{i}))}{d^{2}f}) = \\frac{v(v+1)(\\sigma^{2}v - 3(y_{i} - \lambda(f_{i}))^{2})}{(\\sigma^{2}v + (y_{i} - \lambda(f_{i}))^{2})^{3}} :param inv_li...
def d2logpdf_dlink2_dvar(self, inv_link_f, y, Y_metadata=None): """ Gradient of the hessian (d2logpdf_dlink2) w.r.t variance parameter (t_noise) .. math:: \\frac{d}{d\\sigma^{2}}(\\frac{d^{2} \\ln p(y_{i}|\lambda(f_{i}))}{d^{2}f}) = \\frac{v(v+1)(\\sigma^{2}v - 3(y_{i} - \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): """ 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() #FIXME: Very slow as we are computing a new random variable ...
This is the standard part, which usually belongs in parameters_changed. For automatic handling of subsampling (such as missing_data, stochastics etc.), we need to put this into an inner loop, in order to ensure a different handling of gradients etc of different subsets of data. The dic...
def _inner_parameters_changed(self, kern, X, Z, likelihood, Y, Y_metadata, Lm=None, dL_dKmm=None, psi0=None, psi1=None, psi2=None, **kwargs): """ This is the standard part, which usually belongs in parameters_changed. For automatic handling of subsampling (such as missing_data, stochastics etc....
This is for automatic updates of values in the inner loop of missing data handling. Both arguments are dictionaries and the values in full_values will be updated by the current_gradients. If a key from current_values does not exist in full_values, it will be initialized to the value in ...
def _inner_take_over_or_update(self, full_values=None, current_values=None, value_indices=None): """ This is for automatic updates of values in the inner loop of missing data handling. Both arguments are dictionaries and the values in full_values will be updated by the current_gradients....
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. """ if self.has_uncertain_inputs(): #gradients wrt kernel dL_dKmm = full_values['dL_dKmm']...
If full_values has indices in values_indices, we might want to initialize the full_values differently, so that subsetting is possible. Here you can initialize the full_values for the values needed. Keep in mind, that if a key does not exist in full_values when updating values, it will ...
def _outer_init_full_values(self): """ If full_values has indices in values_indices, we might want to initialize the full_values differently, so that subsetting is possible. Here you can initialize the full_values for the values needed. Keep in mind, that if a key does not exis...
Store the object into a json serializable dictionary :param boolean save_data: if true, it adds the 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): """ Store the object into a json serializable dictionary :param boolean save_data: if true, it adds the data self.X and self.Y to the dictionary :return dict: json serializable dictionary containing the needed information to instantiate the object ...
Instantiate an SparseGPClassification object using the information in input_dict (built by the to_dict method). :param data: It is used to provide X and Y for the case when the model was saved using save_data=False in to_dict method. :type data: tuple(:class:`np.ndarray`, :class:`np....
def from_dict(input_dict, data=None): """ Instantiate an SparseGPClassification object using the information in input_dict (built by the to_dict method). :param data: It is used to provide X and Y for the case when the model was saved using save_data=False in to_dict method. ...
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...
Moments match of the marginal approximation in EP algorithm :param i: number of observation (int) :param tau_i: precision of the cavity distribution (float) :param v_i: mean/variance of the cavity distribution (float)
def moments_match_ep(self, data_i, tau_i, v_i, Y_metadata_i=None): """ Moments match of the marginal approximation in EP algorithm :param i: number of observation (int) :param tau_i: precision of the cavity distribution (float) :param v_i: mean/variance of the cavity distributio...
Likelihood function given link(f) .. math:: \\ln p(y_{i}|\\lambda(f_{i})) = -\\frac{N \\ln 2\\pi}{2} - \\frac{\\ln |K|}{2} - \\frac{(y_{i} - \\lambda(f_{i}))^{T}\\sigma^{-2}(y_{i} - \\lambda(f_{i}))}{2} :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:: \\ln p(y_{i}|\\lambda(f_{i})) = -\\frac{N \\ln 2\\pi}{2} - \\frac{\\ln |K|}{2} - \\frac{(y_{i} - \\lambda(f_{i}))^{T}\\sigma^{-2}(y_{i} - \\lambda(f_{i}))}{2} :param link_f: late...
Log likelihood function given link(f) .. math:: \\ln p(y_{i}|\\lambda(f_{i})) = -\\frac{N \\ln 2\\pi}{2} - \\frac{\\ln |K|}{2} - \\frac{(y_{i} - \\lambda(f_{i}))^{T}\\sigma^{-2}(y_{i} - \\lambda(f_{i}))}{2} :param link_f: latent variables link(f) :type link_f: Nx1 array :pa...
def logpdf_link(self, link_f, y, Y_metadata=None): """ Log likelihood function given link(f) .. math:: \\ln p(y_{i}|\\lambda(f_{i})) = -\\frac{N \\ln 2\\pi}{2} - \\frac{\\ln |K|}{2} - \\frac{(y_{i} - \\lambda(f_{i}))^{T}\\sigma^{-2}(y_{i} - \\lambda(f_{i}))}{2} :param link_...
Gradient of the pdf at y, given link(f) w.r.t link(f) .. math:: \\frac{d \\ln p(y_{i}|\\lambda(f_{i}))}{d\\lambda(f)} = \\frac{1}{\\sigma^{2}}(y_{i} - \\lambda(f_{i})) :param link_f: latent variables link(f) :type link_f: Nx1 array :param y: data :type y: Nx1 array ...
def dlogpdf_dlink(self, link_f, y, Y_metadata=None): """ Gradient of the pdf at y, given link(f) w.r.t link(f) .. math:: \\frac{d \\ln p(y_{i}|\\lambda(f_{i}))}{d\\lambda(f)} = \\frac{1}{\\sigma^{2}}(y_{i} - \\lambda(f_{i})) :param link_f: latent variables link(f) :...
Hessian at y, given link_f, w.r.t link_f. i.e. second derivative logpdf at y given link(f_i) 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}f} = -\\frac{1}{\\sigma^{2}} :param link_f: ...
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) 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}|\...
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)} = 0 :param link_f: latent variables link(f) :type link_f: Nx1 array :param y: data :type y: Nx1 array :par...
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)} = 0 :param link_f: latent variables link(f) :type link_...
Gradient of the log-likelihood function at y given link(f), w.r.t variance parameter (noise_variance) .. math:: \\frac{d \\ln p(y_{i}|\\lambda(f_{i}))}{d\\sigma^{2}} = -\\frac{N}{2\\sigma^{2}} + \\frac{(y_{i} - \\lambda(f_{i}))^{2}}{2\\sigma^{4}} :param link_f: latent variables link(f) ...
def dlogpdf_link_dvar(self, link_f, y, Y_metadata=None): """ Gradient of the log-likelihood function at y given link(f), w.r.t variance parameter (noise_variance) .. math:: \\frac{d \\ln p(y_{i}|\\lambda(f_{i}))}{d\\sigma^{2}} = -\\frac{N}{2\\sigma^{2}} + \\frac{(y_{i} - \\lambda(f_...
Derivative of the dlogpdf_dlink w.r.t variance parameter (noise_variance) .. math:: \\frac{d}{d\\sigma^{2}}(\\frac{d \\ln p(y_{i}|\\lambda(f_{i}))}{d\\lambda(f)}) = \\frac{1}{\\sigma^{4}}(-y_{i} + \\lambda(f_{i})) :param link_f: latent variables link(f) :type link_f: Nx1 array ...
def dlogpdf_dlink_dvar(self, link_f, y, Y_metadata=None): """ Derivative of the dlogpdf_dlink w.r.t variance parameter (noise_variance) .. math:: \\frac{d}{d\\sigma^{2}}(\\frac{d \\ln p(y_{i}|\\lambda(f_{i}))}{d\\lambda(f)}) = \\frac{1}{\\sigma^{4}}(-y_{i} + \\lambda(f_{i})) ...
Gradient of the hessian (d2logpdf_dlink2) w.r.t variance parameter (noise_variance) .. math:: \\frac{d}{d\\sigma^{2}}(\\frac{d^{2} \\ln p(y_{i}|\\lambda(f_{i}))}{d^{2}\\lambda(f)}) = \\frac{1}{\\sigma^{4}} :param link_f: latent variables link(f) :type link_f: Nx1 array :par...
def d2logpdf_dlink2_dvar(self, link_f, y, Y_metadata=None): """ Gradient of the hessian (d2logpdf_dlink2) w.r.t variance parameter (noise_variance) .. math:: \\frac{d}{d\\sigma^{2}}(\\frac{d^{2} \\ln p(y_{i}|\\lambda(f_{i}))}{d^{2}\\lambda(f)}) = \\frac{1}{\\sigma^{4}} :par...
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() #orig_shape = gp.shape gp = gp.flatten() Ysi...
assumes independence
def log_predictive_density(self, y_test, mu_star, var_star, Y_metadata=None): """ assumes independence """ v = var_star + self.variance return -0.5*np.log(2*np.pi) -0.5*np.log(v) - 0.5*np.square(y_test - mu_star)/v
Convert the object into a json serializable dictionary. Note: It uses the private method _save_to_input_dict of the parent. :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 informati...
def to_dict(self, save_data=True): """ Convert the object into a json serializable dictionary. Note: It uses the private method _save_to_input_dict of the parent. :param boolean save_data: if true, it adds the training data self.X and self.Y to the dictionary :return dict: json ...
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
def set_XY(self, X=None, Y=None): """ 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 ...
Predict the function(s) at the new point(s) Xnew. This includes the likelihood variance added to the predicted underlying function (usually referred to as f). In order to predict without adding in the likelihood give `include_likelihood=False`, or refer to self.predict_noiseless(). ...
def predict(self, Xnew, full_cov=False, Y_metadata=None, kern=None, likelihood=None, include_likelihood=True): """ Predict the function(s) at the new point(s) Xnew. This includes the likelihood variance added to the predicted underlying function (usually referred to as f)...
Convenience function to predict the underlying function of the GP (often referred to as f) without adding the likelihood variance on the prediction function. This is most likely what you want to use for your predictions. :param Xnew: The points at which to make a prediction :ty...
def predict_noiseless(self, Xnew, full_cov=False, Y_metadata=None, kern=None): """ Convenience function to predict the underlying function of the GP (often referred to as f) without adding the likelihood variance on the prediction function. This is most likely what you want to ...
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), Y_metadata=None, kern=None, likelihood=None): """ 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 ...
Compute the derivatives of the predicted latent function with respect to X* Given a set of points at which to predict X* (size [N*,Q]), compute the derivatives of the mean and variance. Resulting arrays are sized: dmu_dX* -- [N*, Q ,D], where D is the number of output in this GP ...
def predictive_gradients(self, Xnew, kern=None): """ Compute the derivatives of the predicted latent function with respect to X* Given a set of points at which to predict X* (size [N*,Q]), compute the derivatives of the mean and variance. Resulting arrays are sized: ...
Compute the derivatives of the posterior of the GP. Given a set of points at which to predict X* (size [N*,Q]), compute the mean and variance of the derivative. Resulting arrays are sized: dL_dX* -- [N*, Q ,D], where D is the number of output in this GP (usually one). Note that this...
def predict_jacobian(self, Xnew, kern=None, full_cov=False): """ Compute the derivatives of the posterior of the GP. Given a set of points at which to predict X* (size [N*,Q]), compute the mean and variance of the derivative. Resulting arrays are sized: dL_dX* -- [N*, Q ,D], w...
Predict the wishart embedding G of the GP. This is the density of the input of the GP defined by the probabilistic function mapping f. G = J_mean.T*J_mean + output_dim*J_cov. :param array-like Xnew: The points at which to evaluate the magnification. :param :py:class:`~GPy.kern.Kern` ker...
def predict_wishart_embedding(self, Xnew, kern=None, mean=True, covariance=True): """ Predict the wishart embedding G of the GP. This is the density of the input of the GP defined by the probabilistic function mapping f. G = J_mean.T*J_mean + output_dim*J_cov. :param array-like ...
Predict the magnification factor as sqrt(det(G)) for each point N in Xnew. :param bool mean: whether to include the mean of the wishart embedding. :param bool covariance: whether to include the covariance of the wishart embedding. :param array-like dimensions: which dimensions...
def predict_magnification(self, Xnew, kern=None, mean=True, covariance=True, dimensions=None): """ Predict the magnification factor as sqrt(det(G)) for each point N in Xnew. :param bool mean: whether to include the mean of the wishart embedding. :param bool covariance:...
Samples the posterior GP 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. :returns: set of simulations :rtype: np.ndarray (Nnew x D x samples)
def posterior_samples_f(self,X, size=10, **predict_kwargs): """ Samples the posterior GP 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. ...
Samples the posterior GP 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 noise_model: for mixed noise likelihood, the noise model to use in t...
def posterior_samples(self, X, size=10, Y_metadata=None, likelihood=None, **predict_kwargs): """ Samples the posterior GP 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 samp...
Optimize the model using self.log_likelihood and self.log_likelihood_gradient, as well as self.priors. kwargs are passed to the optimizer. They can be: :param max_iters: maximum number of function evaluations :type max_iters: int :param messages: whether to display during optimisation ...
def optimize(self, optimizer=None, start=None, messages=False, max_iters=1000, ipython_notebook=True, clear_after_finish=False, **kwargs): """ Optimize the model using self.log_likelihood and self.log_likelihood_gradient, as well as self.priors. kwargs are passed to the optimizer. They can be: ...
Infer X for the new observed data *Y_new*. :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) :type optimize: boolean :return: a tuple containing the posterior estimation of X ...
def infer_newX(self, Y_new, optimize=True): """ Infer X for the new observed data *Y_new*. :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) :type optimize: boolean ...
Calculation of the log predictive density .. math: p(y_{*}|D) = p(y_{*}|f_{*})p(f_{*}|\mu_{*}\\sigma^{2}_{*}) :param x_test: test locations (x_{*}) :type x_test: (Nx1) array :param y_test: test observations (y_{*}) :type y_test: (Nx1) array :param Y_metadata...
def log_predictive_density(self, x_test, y_test, Y_metadata=None): """ Calculation of the log predictive density .. math: p(y_{*}|D) = p(y_{*}|f_{*})p(f_{*}|\mu_{*}\\sigma^{2}_{*}) :param x_test: test locations (x_{*}) :type x_test: (Nx1) array :param y_test...
Calculation of the log predictive density by sampling .. math: p(y_{*}|D) = p(y_{*}|f_{*})p(f_{*}|\mu_{*}\\sigma^{2}_{*}) :param x_test: test locations (x_{*}) :type x_test: (Nx1) array :param y_test: test observations (y_{*}) :type y_test: (Nx1) array :para...
def log_predictive_density_sampling(self, x_test, y_test, Y_metadata=None, num_samples=1000): """ Calculation of the log predictive density by sampling .. math: p(y_{*}|D) = p(y_{*}|f_{*})p(f_{*}|\mu_{*}\\sigma^{2}_{*}) :param x_test: test locations (x_{*}) :type x_...
Computes the posterior covariance between points. :param X1: some input observations :param X2: other input observations
def posterior_covariance_between_points(self, X1, X2): """ Computes the posterior covariance between points. :param X1: some input observations :param X2: other input observations """ return self.posterior.covariance_between_points(self.kern, self.X, X1, X2)
Generate default dimensions and coordinates for a variable. Parameters ---------- shape : tuple[int] Shape of the variable var_name : str Name of the variable. Used in the default name, if necessary dims : list List of dimensions for the variable coords : dict[str] -> li...
def generate_dims_coords(shape, var_name, dims=None, coords=None, default_dims=None): """Generate default dimensions and coordinates for a variable. Parameters ---------- shape : tuple[int] Shape of the variable var_name : str Name of the variable. Used in the default name, if neces...
Convert a numpy array to an xarray.DataArray. The first two dimensions will be (chain, draw), and any remaining dimensions will be "shape". If the numpy array is 1d, this dimension is interpreted as draw If the numpy array is 2d, it is interpreted as (chain, draw) If the numpy array is 3 or more di...
def numpy_to_data_array(ary, *, var_name="data", coords=None, dims=None): """Convert a numpy array to an xarray.DataArray. The first two dimensions will be (chain, draw), and any remaining dimensions will be "shape". If the numpy array is 1d, this dimension is interpreted as draw If the numpy array...
Convert a dictionary of numpy arrays to an xarray.Dataset. Parameters ---------- data : dict[str] -> ndarray Data to convert. Keys are variable names. attrs : dict Json serializable metadata to attach to the dataset, in addition to defaults. library : module Library used for...
def dict_to_dataset(data, *, attrs=None, library=None, coords=None, dims=None): """Convert a dictionary of numpy arrays to an xarray.Dataset. Parameters ---------- data : dict[str] -> ndarray Data to convert. Keys are variable names. attrs : dict Json serializable metadata to attach...
Make standard attributes to attach to xarray datasets. Parameters ---------- attrs : dict (optional) Additional attributes to add or overwrite Returns ------- dict attrs
def make_attrs(attrs=None, library=None): """Make standard attributes to attach to xarray datasets. Parameters ---------- attrs : dict (optional) Additional attributes to add or overwrite Returns ------- dict attrs """ default_attrs = {"created_at": datetime.datetim...
Return the path of the arviz data dir. This folder is used by some dataset loaders to avoid downloading the data several times. By default the data dir is set to a folder named 'arviz_data' in the user home folder. Alternatively, it can be set by the 'ARVIZ_DATA' environment variable or progr...
def get_data_home(data_home=None): """Return the path of the arviz data dir. This folder is used by some dataset loaders to avoid downloading the data several times. By default the data dir is set to a folder named 'arviz_data' in the user home folder. Alternatively, it can be set by the 'ARV...
Calculate the sha256 hash of the file at path.
def _sha256(path): """Calculate the sha256 hash of the file at path.""" sha256hash = hashlib.sha256() chunk_size = 8192 with open(path, "rb") as buff: while True: buffer = buff.read(chunk_size) if not buffer: break sha256hash.update(buffer) ...
Load a local or remote pre-made dataset. Run with no parameters to get a list of all available models. The directory to save to can also be set with the environement variable `ARVIZ_HOME`. The checksum of the dataset is checked against a hardcoded value to watch for data corruption. Run `az.clear...
def load_arviz_data(dataset=None, data_home=None): """Load a local or remote pre-made dataset. Run with no parameters to get a list of all available models. The directory to save to can also be set with the environement variable `ARVIZ_HOME`. The checksum of the dataset is checked against a hardco...
Get a string representation of all available datasets with descriptions.
def list_datasets(): """Get a string representation of all available datasets with descriptions.""" lines = [] for name, resource in itertools.chain(LOCAL_DATASETS.items(), REMOTE_DATASETS.items()): if isinstance(resource, LocalFileMetadata): location = "local: {}".format(resource.filen...
Make sure var_names and arg_names are assigned reasonably. This is meant to run before loading emcee objects into InferenceData. In case var_names or arg_names is None, will provide defaults. If they are not None, it verifies there are the right number of them. Throws a ValueError in case validation f...
def _verify_names(sampler, var_names, arg_names): """Make sure var_names and arg_names are assigned reasonably. This is meant to run before loading emcee objects into InferenceData. In case var_names or arg_names is None, will provide defaults. If they are not None, it verifies there are the right numb...
Convert emcee data into an InferenceData object. Parameters ---------- sampler : emcee.EnsembleSampler Fitted sampler from emcee. var_names : list[str] (Optional) A list of names for variables in the sampler arg_names : list[str] (Optional) A list of names for args in the sa...
def from_emcee(sampler=None, *, var_names=None, arg_names=None, coords=None, dims=None): """Convert emcee data into an InferenceData object. Parameters ---------- sampler : emcee.EnsembleSampler Fitted sampler from emcee. var_names : list[str] (Optional) A list of names for variable...
Convert the posterior to an xarray dataset.
def posterior_to_xarray(self): """Convert the posterior to an xarray dataset.""" data = {} for idx, var_name in enumerate(self.var_names): # Use emcee3 syntax, else use emcee2 data[var_name] = ( self.sampler.get_chain()[(..., idx)].T if has...
Convert observed data to xarray.
def observed_data_to_xarray(self): """Convert observed data to xarray.""" data = {} for idx, var_name in enumerate(self.arg_names): # Use emcee3 syntax, else use emcee2 data[var_name] = ( self.sampler.log_prob_fn.args[idx] if hasattr(self.s...
Convert tfp data into an InferenceData object.
def from_tfp( posterior=None, *, var_names=None, model_fn=None, feed_dict=None, posterior_predictive_samples=100, posterior_predictive_size=1, observed=None, coords=None, dims=None ): """Convert tfp data into an InferenceData object.""" return TfpConverter( ...
Convert the posterior to an xarray dataset.
def posterior_to_xarray(self): """Convert the posterior to an xarray dataset.""" data = {} for i, var_name in enumerate(self.var_names): data[var_name] = np.expand_dims(self.posterior[i], axis=0) return dict_to_dataset(data, library=self.tfp, coords=self.coords, dims=sel...
Convert observed data to xarray.
def observed_data_to_xarray(self): """Convert observed data to xarray.""" if self.observed is None: return None observed_data = {} if isinstance(self.observed, self.tf.Tensor): with self.tf.Session() as sess: vals = sess.run(self.observed,...
Convert posterior_predictive samples to xarray.
def posterior_predictive_to_xarray(self): """Convert posterior_predictive samples to xarray.""" if self.model_fn is None: return None posterior_preds = [] sample_size = self.posterior[0].shape[0] for i in np.arange(0, sample_size, int(sample_size / self.post...
Extract sample_stats from tfp trace.
def sample_stats_to_xarray(self): """Extract sample_stats from tfp trace.""" if self.model_fn is None or self.observed is None: return None log_likelihood = [] sample_size = self.posterior[0].shape[0] for i in range(sample_size): variables = {} ...
Convert all available data to an InferenceData object. Note that if groups can not be created (i.e., there is no `trace`, so the `posterior` and `sample_stats` can not be extracted), then the InferenceData will not have those groups.
def to_inference_data(self): """Convert all available data to an InferenceData object. Note that if groups can not be created (i.e., there is no `trace`, so the `posterior` and `sample_stats` can not be extracted), then the InferenceData will not have those groups. """ ...
Convert pymc3 data into an InferenceData object.
def from_pymc3(trace=None, *, prior=None, posterior_predictive=None, coords=None, dims=None): """Convert pymc3 data into an InferenceData object.""" return PyMC3Converter( trace=trace, prior=prior, posterior_predictive=posterior_predictive, coords=coords, dims=dims, )...
Compute log likelihood of each observation. Return None if there is not exactly 1 observed random variable.
def _extract_log_likelihood(self): """Compute log likelihood of each observation. Return None if there is not exactly 1 observed random variable. """ # This next line is brittle and may not work forever, but is a secret # way to access the model from the trace. model = s...
Convert the posterior to an xarray dataset.
def posterior_to_xarray(self): """Convert the posterior to an xarray dataset.""" var_names = self.pymc3.util.get_default_varnames( # pylint: disable=no-member self.trace.varnames, include_transformed=False ) data = {} for var_name in var_names: data[var_n...