INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Gradient of the log likelihood function at y given link ( f ) w. r. t link ( f ) | 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 | 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 ) | 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 | 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. | 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 | 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, ... |
Convert the object into a json serializable dictionary. | 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. | 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 | 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. | 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. | 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. | 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 ) | 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 ) | 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 ) | 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 | 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 ) | 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 ) | 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 ) | 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 ) | 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. | 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. | 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. | 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. | 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 | 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 ). | 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. | 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 | 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 ) | 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 ) | 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 ) | 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 ) | 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 ) | 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 ) | 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 ) | 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 ) | 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. | 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. | 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 | 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 ). | 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. | 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 | 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 * | 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. | 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. | 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 | 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. | 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. | 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: | 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 *. | 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 | 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 | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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(
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.