INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
r Construct a tf function to compute the likelihood of a general GP model. | def _build_likelihood(self):
r"""
Construct a tf function to compute the likelihood of a general GP
model.
\log p(Y, V | theta).
"""
K = self.kern.K(self.X)
L = tf.cholesky(
K + tf.eye(tf.shape(self.X)[0], dtype=settings.float_type) * settings.nu... |
Xnew is a data matrix point at which we want to predict | def _build_predict(self, Xnew, full_cov=False):
"""
Xnew is a data matrix, point at which we want to predict
This method computes
p(F* | (F=LV) )
where F* are points on the GP at Xnew, F=LV are points on the GP at X.
"""
mu, var = conditional(Xnew, self.X,... |
Constructs the mean and cholesky of the covariance of the variational Gaussian posterior. If a user passes values for q_mu and q_sqrt the routine checks if they have consistent and correct shapes. If a user does not specify any values for q_mu and q_sqrt the routine initializes them their shape depends on num_inducing ... | def _init_variational_parameters(self, num_inducing, q_mu, q_sqrt, q_diag):
"""
Constructs the mean and cholesky of the covariance of the variational Gaussian posterior.
If a user passes values for `q_mu` and `q_sqrt` the routine checks if they have consistent
and correct shapes. If a us... |
This gives a variational bound on the model likelihood. | def _build_likelihood(self):
"""
This gives a variational bound on the model likelihood.
"""
# Get prior KL.
KL = self.build_prior_KL()
# Get conditionals
fmean, fvar = self._build_predict(self.X, full_cov=False, full_output_cov=False)
# Get variational... |
Compile is two phase operation: at first it calls build method and then intializes the node for passed session. The policy around session is defined inside the initialize method. | def compile(self, session=None):
"""
Compile is two phase operation: at first it calls `build` method and then
intializes the node for passed session. The policy around `session` is defined
inside the `initialize` method.
:param session: TensorFlow session used for initializing.... |
Initializes TensorFlow variables which are returned by initializables property and uses feed dictionary returned by initializable_feeds property defined at ICompilable interface and implemented by descendants. | def initialize(self, session=None, force=False):
"""
Initializes TensorFlow variables, which are returned by `initializables` property and
uses feed dictionary returned by `initializable_feeds` property defined at ICompilable
interface and implemented by descendants.
:param sess... |
Calls _clear abstract method which must be implemented by descendants. | def clear(self):
"""
Calls `_clear` abstract method which must be implemented by descendants.
:raises: GPflowError exception when parent of the node is built.
"""
parent = self.parent
if parent is not self and parent.is_built_coherence(self.graph) is Build.YES:
... |
Verifies and returns relevant TensorFlow graph. If non - None graph were passed the same graph is returned. Otherwise nodes s graph is exposed and it is undefined the default TensorFlow graph is used. | def enquire_graph(self, graph=None):
"""
Verifies and returns relevant TensorFlow graph. If non-None graph were passed,
the same graph is returned. Otherwise, nodes's graph is exposed and it is
undefined the default TensorFlow graph is used.
:param graph: TensorFlow graph or Non... |
Verifies and returns relevant TensorFlow session. If non - None session were passed session is checked for graph compliance and returned back. Otherwise default TensorFlow session is returned. When TensorFlow default session is not set up GPflow session s manager creates or uses existing one for returning. | def enquire_session(self, session=None):
"""
Verifies and returns relevant TensorFlow session. If non-None session
were passed, session is checked for graph compliance and returned back.
Otherwise, default TensorFlow session is returned. When TensorFlow default
session is not set... |
Checks that node was build using input graph. | def is_built_coherence(self, graph=None):
"""
Checks that node was build using input `graph`.
:return: `Build` status.
:raises GPflowError: Valid passed TensorFlow graph is different from
used graph in node.
"""
graph = self.enquire_graph(graph=graph)
... |
Implementation for ICompilable interface build method. Builds tensors within TensorFlow name scope using parentable node s name. Hidden name is used when no parent exists for current node. | def build(self):
"""
Implementation for ICompilable interface `build` method. Builds tensors within
TensorFlow name scope using parentable node's name. Hidden name is used when
no parent exists for current node.
:raises GPflowError: Node's parts were built with different graph ... |
Auxilary method for composing gpflow s tree name scopes. The Parentable pathname can be considered as a set of name scopes. This method grabs pathname and returns only name of the node in that path. Leading node name is always replaced with two parts: the name and the index for uniquiness in TensorFlow. | def tf_name_scope(self):
"""
Auxilary method for composing gpflow's tree name scopes. The Parentable pathname
can be considered as a set of name scopes. This method grabs `pathname` and
returns only name of the node in that path.
Leading node name is always replaced with two part... |
Method used for defining full path name for particular tensor at build time. For example tf. get_variable creates variable w/ o taking into account name scopes and tf_pathname consists of all parts of scope names which were used up to that point - tf. get_variable call. | def tf_pathname(self):
"""
Method used for defining full path name for particular tensor at build time.
For example, `tf.get_variable` creates variable w/o taking into account
name scopes and `tf_pathname` consists of all parts of scope names
which were used up to that point - `t... |
autobuild_decorate ( func caller ) decorates a function using a caller. Allows for an extra autobuild keyword arg. The only difference to decorator. decorate () is to use our custom AutobuildFunctionMaker instead. | def autobuild_decorate(func, caller):
"""
autobuild_decorate(func, caller) decorates a function using a caller.
Allows for an extra `autobuild` keyword arg.
The only difference to decorator.decorate() is to use our custom AutobuildFunctionMaker instead.
"""
evaldict = dict(_call_=caller, _func_=... |
Build a tf expression for the prior by summing all child - parameter priors. | def _build_prior(self, prior_tensors):
"""
Build a tf expression for the prior by summing all child-parameter priors.
"""
# TODO(@awav): What prior must represent empty list of parameters?
if not prior_tensors:
return tf.constant(0, dtype=settings.float_type)
... |
r Apply binary operation op to every pair in tensors a and b.: param op: binary operator on tensors e. g. tf. add tf. substract: param a: tf. Tensor shape [ n_1... n_a ]: param b: tf. Tensor shape [ m_1... m_b ]: return: tf. Tensor shape [ n_1... n_a m_1... m_b ] | def _broadcasting_elementwise_op(op, a, b):
r"""
Apply binary operation `op` to every pair in tensors `a` and `b`.
:param op: binary operator on tensors, e.g. tf.add, tf.substract
:param a: tf.Tensor, shape [n_1, ..., n_a]
:param b: tf.Tensor, shape [m_1, ..., m_b]
:return: tf.Tensor, shape [n_1... |
Returns a class that raises NotImplementedError on instantiation. e. g.: >>> Kern = make_deprecated_class ( Kern Kernel ) | def make_deprecated_class(oldname, NewClass):
"""
Returns a class that raises NotImplementedError on instantiation.
e.g.:
>>> Kern = make_deprecated_class("Kern", Kernel)
"""
msg = ("{module}.{} has been renamed to {module}.{}"
.format(oldname, NewClass.__name__, module=NewClass.__mod... |
Validates the shape of a potentially ARD hyperparameter | def _validate_ard_shape(self, name, value, ARD=None):
"""
Validates the shape of a potentially ARD hyperparameter
:param name: The name of the parameter (used for error messages)
:param value: A scalar or an array.
:param ARD: None, False, or True. If None, infers ARD from shape... |
Checks if the dimensions over which the kernels are specified overlap. Returns True if they are defined on different/ separate dimensions and False otherwise. | def on_separate_dims(self, other_kernel):
"""
Checks if the dimensions, over which the kernels are specified, overlap.
Returns True if they are defined on different/separate dimensions and False otherwise.
"""
if isinstance(self.active_dims, slice) or isinstance(other_kernel.acti... |
Slice the correct dimensions for use in the kernel as indicated by self. active_dims.: param X: Input 1 ( NxD ).: param X2: Input 2 ( MxD ) may be None.: return: Sliced X X2 ( Nxself. input_dim ). | def _slice(self, X, X2):
"""
Slice the correct dimensions for use in the kernel, as indicated by
`self.active_dims`.
:param X: Input 1 (NxD).
:param X2: Input 2 (MxD), may be None.
:return: Sliced X, X2, (Nxself.input_dim).
"""
if isinstance(self.active_di... |
Slice the correct dimensions for use in the kernel as indicated by self. active_dims for covariance matrices. This requires slicing the rows * and * columns. This will also turn flattened diagonal matrices into a tensor of full diagonal matrices.: param cov: Tensor of covariance matrices ( NxDxD or NxD ).: return: N x ... | def _slice_cov(self, cov):
"""
Slice the correct dimensions for use in the kernel, as indicated by
`self.active_dims` for covariance matrices. This requires slicing the
rows *and* columns. This will also turn flattened diagonal
matrices into a tensor of full diagonal matrices.
... |
Returns (( X - X2ᵀ )/ lengthscales ) ². Due to the implementation and floating - point imprecision the result may actually be very slightly negative for entries very close to each other. | def _scaled_square_dist(self, X, X2):
"""
Returns ((X - X2ᵀ)/lengthscales)².
Due to the implementation and floating-point imprecision, the
result may actually be very slightly negative for entries very
close to each other.
This function can deal with leading dimensions i... |
Returns | ( X - X2ᵀ )/ lengthscales| ( L2 - norm ). | def scaled_euclid_dist(self, X, X2): # pragma: no cover
"""
Returns |(X - X2ᵀ)/lengthscales| (L2-norm).
"""
warnings.warn('scaled_euclid_dist is deprecated and will be removed '
'in GPflow version 1.4.0. For stationary kernels, '
'define K_r(r... |
Calculates the kernel matrix K ( X X2 ) ( or K ( X X ) if X2 is None ). Handles the slicing as well as scaling and computes k ( x x ) = k ( r ) where r² = (( x - x )/ lengthscales ) ². | def K(self, X, X2=None, presliced=False):
"""
Calculates the kernel matrix K(X, X2) (or K(X, X) if X2 is None).
Handles the slicing as well as scaling and computes k(x, x') = k(r),
where r² = ((x - x')/lengthscales)².
Internally, this calls self.K_r2(r²), which in turn computes ... |
Returns the kernel evaluated on r2 which is the scaled squared distance. Will call self. K_r ( r = sqrt ( r2 )) or can be overwritten directly ( and should operate element - wise on r2 ). | def K_r2(self, r2):
"""
Returns the kernel evaluated on `r2`, which is the scaled squared distance.
Will call self.K_r(r=sqrt(r2)), or can be overwritten directly (and should operate element-wise on r2).
"""
r = self._clipped_sqrt(r2)
return self.K_r(r) |
Implements the order dependent family of functions defined in equations 4 to 7 in the reference paper. | def _J(self, theta):
"""
Implements the order dependent family of functions defined in equations
4 to 7 in the reference paper.
"""
if self.order == 0:
return np.pi - theta
elif self.order == 1:
return tf.sin(theta) + (np.pi - theta) * tf.cos(theta... |
Checks whether the kernels in the combination act on disjoint subsets of dimensions. Currently it is hard to asses whether two slice objects will overlap so this will always return False.: return: Boolean indicator. | def on_separate_dimensions(self):
"""
Checks whether the kernels in the combination act on disjoint subsets
of dimensions. Currently, it is hard to asses whether two slice objects
will overlap, so this will always return False.
:return: Boolean indicator.
"""
if n... |
r Inverse of the softplus transform:.. math:: | def backward(self, y):
r"""
Inverse of the softplus transform:
.. math::
x = \log( \exp(y) - 1)
The bound for the input y is [self._lower. inf[, self._lower is
subtracted prior to any calculations. The implementation avoids overflow
explicitly by applying the... |
Transforms from the packed to unpacked representations ( numpy ): param x: packed numpy array. Must have shape self. num_matrices x triangular_number: return: Reconstructed numpy array y of shape self. num_matrices x N x N | def forward(self, x):
"""
Transforms from the packed to unpacked representations (numpy)
:param x: packed numpy array. Must have shape `self.num_matrices x triangular_number
:return: Reconstructed numpy array y of shape self.num_matrices x N x N
"""
fwd = np.zero... |
Transforms a series of triangular matrices y to the packed representation x ( numpy ): param y: unpacked numpy array y shape self. num_matrices x N x N: return: packed numpy array x shape self. num_matrices x triangular number | def backward(self, y):
"""
Transforms a series of triangular matrices y to the packed representation x (numpy)
:param y: unpacked numpy array y, shape self.num_matrices x N x N
:return: packed numpy array, x, shape self.num_matrices x triangular number
"""
if sel... |
Transforms from the packed to unpacked representations ( tf. tensors ): param x: packed tensor. Must have shape self. num_matrices x triangular_number: return: Reconstructed tensor y of shape self. num_matrices x N x N | def forward_tensor(self, x):
"""
Transforms from the packed to unpacked representations (tf.tensors)
:param x: packed tensor. Must have shape `self.num_matrices x triangular_number
:return: Reconstructed tensor y of shape self.num_matrices x N x N
"""
fwd = vec_t... |
Transforms a series of triangular matrices y to the packed representation x ( tf. tensors ): param y: unpacked tensor with shape self. num_matrices self. N self. N: return: packed tensor with shape self. num_matrices ( self. N ** 2 + self. N )/ 2 | def backward_tensor(self, y):
"""
Transforms a series of triangular matrices y to the packed representation x (tf.tensors)
:param y: unpacked tensor with shape self.num_matrices, self.N, self.N
:return: packed tensor with shape self.num_matrices, (self.N**2 + self.N) / 2
... |
Extracts from an object existing dictionary with tensors specified by name. If there is no such object then new one will be created. Intenally it appends autoflow prefix to the name and saves it as an attribute. | def get_autoflow(cls, obj, name):
"""
Extracts from an object existing dictionary with tensors specified by name.
If there is no such object then new one will be created. Intenally, it appends
autoflow prefix to the name and saves it as an attribute.
:param obj: target GPflow ob... |
Clear autoflow s tensor storage. | def clear_autoflow(cls, obj, name=None):
"""
Clear autoflow's tensor storage.
:param obj: target GPflow object.
:param name: accepts either string value which is unique part of
an internal attribute name or None value. When None value is passed all
storages will ... |
Before calling the standard compile function check to see if the size of the data has changed and add variational parameters appropriately. | def compile(self, session=None):
"""
Before calling the standard compile function, check to see if the size
of the data has changed and add variational parameters appropriately.
This is necessary because the shape of the parameters depends on the
shape of the data.
"""
... |
r This method computes the variational lower bound on the likelihood which is: | def _build_likelihood(self):
r"""
This method computes the variational lower bound on the likelihood,
which is:
E_{q(F)} [ \log p(Y|F) ] - KL[ q(F) || p(F)]
with
q(\mathbf f) = N(\mathbf f \,|\, \boldsymbol \mu, \boldsymbol \Sigma)
"""
# Get p... |
Before calling the standard compile function check to see if the size of the data has changed and add variational parameters appropriately. | def compile(self, session=None):
"""
Before calling the standard compile function, check to see if the size
of the data has changed and add variational parameters appropriately.
This is necessary because the shape of the parameters depends on the
shape of the data.
"""
... |
r q_alpha q_lambda are variational parameters size N x R This method computes the variational lower bound on the likelihood which is: E_ { q ( F ) } [ \ log p ( Y|F ) ] - KL [ q ( F ) || p ( F ) ] with q ( f ) = N ( f | K alpha + mean [ K^ - 1 + diag ( square ( lambda )) ] ^ - 1 ). | def _build_likelihood(self):
r"""
q_alpha, q_lambda are variational parameters, size N x R
This method computes the variational lower bound on the likelihood,
which is:
E_{q(F)} [ \log p(Y|F) ] - KL[ q(F) || p(F)]
with
q(f) = N(f | K alpha + mean, [K^-1 + ... |
The posterior variance of F is given by q ( f ) = N ( f | K alpha + mean [ K^ - 1 + diag ( lambda ** 2 ) ] ^ - 1 ) Here we project this to F * the values of the GP at Xnew which is given by q ( F * ) = N ( F * | K_ { * F } alpha + mean K_ { ** } - K_ { * f } [ K_ { ff } + diag ( lambda ** - 2 ) ] ^ - 1 K_ { f * } ) | def _build_predict(self, Xnew, full_cov=False):
"""
The posterior variance of F is given by
q(f) = N(f | K alpha + mean, [K^-1 + diag(lambda**2)]^-1)
Here we project this to F*, the values of the GP at Xnew which is given
by
q(F*) = N ( F* | K_{*F} alpha + mean, K_... |
This function computes the optimal density for v q * ( v ) up to a constant | def _build_likelihood(self):
"""
This function computes the optimal density for v, q*(v), up to a constant
"""
# get the (marginals of) q(f): exactly predicting!
fmean, fvar = self._build_predict(self.X, full_cov=False)
return tf.reduce_sum(self.likelihood.variational_exp... |
Very simple config values parser. | def _parse(string):
"""
Very simple config values parser.
"""
if not isinstance(string, str):
raise ValueError('Config value "{0}" expected to be string.'
.format(string))
if string in ['true', 'True']:
return True
elif string in ['false', 'False']:
... |
Make the dictionary into a nested series of named tuples. This is what allows accessing by attribute: settings. numerics. jitter Thank you https:// gist. github. com/ hangtwenty/ 5960435 | def _namedtuplify(mapping):
"""
Make the dictionary into a nested series of named tuples.
This is what allows accessing by attribute: settings.numerics.jitter
Thank you https://gist.github.com/hangtwenty/5960435
"""
if isinstance(mapping, collections.Mapping):
for key, value in list(mapp... |
Reads config file. First look for config file in the current directory then in the user s home directory then in the same directory as this file. Tries to find config file both with and without preceeding dot for hidden files ( prefer non - hidden ). | def _read_config_file(path=None):
"""
Reads config file.
First look for config file in the current directory, then in the
user's home directory, then in the same directory as this file.
Tries to find config file both with and without preceeding 'dot'
for hidden files (prefer non-hidden).
"""... |
Return the evaluation locations xn and weights wn for a multivariate Gauss - Hermite quadrature. | def mvhermgauss(H: int, D: int):
"""
Return the evaluation locations 'xn', and weights 'wn' for a multivariate
Gauss-Hermite quadrature.
The outputs can be used to approximate the following type of integral:
int exp(-x)*f(x) dx ~ sum_i w[i,:]*f(x[i,:])
:param H: Number of Gauss-Hermite evaluat... |
Computes N Gaussian expectation integrals of a single function f using Gauss - Hermite quadrature.: param f: integrand function. Takes one input of shape ?xD.: param means: NxD: param covs: NxDxD: param H: Number of Gauss - Hermite evaluation points.: param Din: Number of input dimensions. Needs to be known at call - t... | def mvnquad(func, means, covs, H: int, Din: int=None, Dout=None):
"""
Computes N Gaussian expectation integrals of a single function 'f'
using Gauss-Hermite quadrature.
:param f: integrand function. Takes one input of shape ?xD.
:param means: NxD
:param covs: NxDxD
:param H: Number of Gauss-... |
Computes N Gaussian expectation integrals of one or more functions using Gauss - Hermite quadrature. The Gaussians must be independent. | def ndiagquad(funcs, H: int, Fmu, Fvar, logspace: bool=False, **Ys):
"""
Computes N Gaussian expectation integrals of one or more functions
using Gauss-Hermite quadrature. The Gaussians must be independent.
:param funcs: the integrand(s):
Callable or Iterable of Callables that operates elementw... |
Computes N Gaussian expectation integrals of one or more functions using Monte Carlo samples. The Gaussians must be independent. | def ndiag_mc(funcs, S: int, Fmu, Fvar, logspace: bool=False, epsilon=None, **Ys):
"""
Computes N Gaussian expectation integrals of one or more functions
using Monte Carlo samples. The Gaussians must be independent.
:param funcs: the integrand(s):
Callable or Iterable of Callables that operates ... |
This decorator wraps a function so that it runs inside a TensorFlow name scope. The name is given by the name option ; if this is None then the name of the function will be used. >>> | def name_scope(name=None):
"""
This decorator wraps a function so that it runs inside a TensorFlow
name scope. The name is given by the `name` option; if this is None,
then the name of the function will be used.
```
>>> @name_scope()
>>> def foo(...):
>>> # now runs inside scope "foo... |
The params_as_tensors decorator converts representation for parameters into their unconstrained tensors and data holders to their data tensors inside wrapped function subject to this function is a member of parameterized object. | def params_as_tensors(method):
"""
The `params_as_tensors` decorator converts representation for parameters into
their unconstrained tensors, and data holders to their data tensors inside
wrapped function, subject to this function is a member of parameterized object.
"""
@functools.wraps(method)... |
Context manager which changes the representation of parameters and data holders for the specific parameterized object ( s ). | def params_as_tensors_for(*objs, convert=True):
"""
Context manager which changes the representation of parameters and data holders
for the specific parameterized object(s).
This can also be used to turn off tensor conversion functions wrapped with
`params_as_tensors`:
```
@gpflow.params_as... |
Compute the KL divergence KL [ q || p ] between | def gauss_kl(q_mu, q_sqrt, K=None, *, K_cholesky=None):
"""
Compute the KL divergence KL[q || p] between
q(x) = N(q_mu, q_sqrt^2)
and
p(x) = N(0, K)
We assume N multiple independent distributions, given by the columns of
q_mu and the last dimension of q_sqrt. Returns the sum of... |
A helpful function for linearly reducing the dimensionality of the data X to Q.: param X: data array of size N ( number of points ) x D ( dimensions ): param Q: Number of latent dimensions Q < D: return: PCA projection array of size N x Q. | def PCA_reduce(X, Q):
"""
A helpful function for linearly reducing the dimensionality of the data X
to Q.
:param X: data array of size N (number of points) x D (dimensions)
:param Q: Number of latent dimensions, Q < D
:return: PCA projection array of size N x Q.
"""
assert Q <= X.shape[1... |
Construct a tensorflow function to compute the bound on the marginal likelihood. | def _build_likelihood(self):
"""
Construct a tensorflow function to compute the bound on the marginal
likelihood.
"""
pX = DiagonalGaussian(self.X_mean, self.X_var)
num_inducing = len(self.feature)
psi0 = tf.reduce_sum(expectation(pX, self.kern))
psi1 = e... |
Compute the mean and variance of the latent function at some new points. Note that this is very similar to the SGPR prediction for which there are notes in the SGPR notebook.: param Xnew: Point to predict at. | def _build_predict(self, Xnew, full_cov=False):
"""
Compute the mean and variance of the latent function at some new points.
Note that this is very similar to the SGPR prediction, for which
there are notes in the SGPR notebook.
:param Xnew: Point to predict at.
"""
... |
Multi - output GP with independent GP priors. Number of latent processes equals the number of outputs ( L = P ). | def _conditional(Xnew, feat, kern, f, *, full_cov=False, full_output_cov=False, q_sqrt=None, white=False):
"""
Multi-output GP with independent GP priors.
Number of latent processes equals the number of outputs (L = P).
The covariance matrices used to calculate the conditional have the following shape:... |
Multi - output GP with fully correlated inducing variables. The inducing variables are shaped in the same way as evaluations of K to allow a default inducing point scheme for multi - output kernels. | def _conditional(Xnew, feat, kern, f, *, full_cov=False, full_output_cov=False, q_sqrt=None, white=False):
"""
Multi-output GP with fully correlated inducing variables.
The inducing variables are shaped in the same way as evaluations of K, to allow a default
inducing point scheme for multi-output kernel... |
Most efficient routine to project L independent latent gps through a mixing matrix W. The mixing matrix is a member of the SeparateMixedMok and has shape P x L. | def _conditional(Xnew, feat, kern, f, *, full_cov=False, full_output_cov=False, q_sqrt=None, white=False):
"""
Most efficient routine to project L independent latent gps through a mixing matrix W.
The mixing matrix is a member of the `SeparateMixedMok` and has shape P x L.
The covariance matrices used ... |
sample_conditional will return a sample from the conditinoal distribution. In most cases this means calculating the conditional mean m and variance v and then returning m + sqrt ( v ) * eps with eps ~ N ( 0 1 ). However for some combinations of Mok and Mof more efficient sampling routines exists. The dispatcher will ma... | def _sample_conditional(Xnew, feat, kern, f, *, full_cov=False, full_output_cov=False, q_sqrt=None, white=False, num_samples=None):
"""
`sample_conditional` will return a sample from the conditinoal distribution.
In most cases this means calculating the conditional mean m and variance v and then
returni... |
The inducing outputs live in the g - space ( R^L ). Interdomain conditional calculation. | def independent_interdomain_conditional(Kmn, Kmm, Knn, f, *, full_cov=False, full_output_cov=False,
q_sqrt=None, white=False):
"""
The inducing outputs live in the g-space (R^L).
Interdomain conditional calculation.
:param Kmn: M x L x N x P
:param Kmm: L x M... |
This function handles conditioning of multi - output GPs in the case where the conditioning points are all fully correlated in both the prior and posterior.: param Kmn: LM x N x P: param Kmm: LM x LM: param Knn: N x P or N x P x N x P: param f: data matrix LM x 1: param q_sqrt: 1 x LM x LM or 1 x ML: param full_cov: ca... | def fully_correlated_conditional(Kmn, Kmm, Knn, f, *, full_cov=False, full_output_cov=False, q_sqrt=None, white=False):
"""
This function handles conditioning of multi-output GPs in the case where the conditioning
points are all fully correlated, in both the prior and posterior.
:param Kmn: LM x N x P
... |
This function handles conditioning of multi - output GPs in the case where the conditioning points are all fully correlated in both the prior and posterior. | def fully_correlated_conditional_repeat(Kmn, Kmm, Knn, f, *, full_cov=False, full_output_cov=False, q_sqrt=None,
white=False):
"""
This function handles conditioning of multi-output GPs in the case where the conditioning
points are all fully correlated, in both the pr... |
r Takes the mean and variance of an uncorrelated L - dimensional latent GP and returns the mean and the variance of the mixed GP f = W g where both f and g are GPs with W having a shape [ P L ] | def _mix_latent_gp(W, g_mu, g_var, full_cov, full_output_cov):
r"""
Takes the mean and variance of an uncorrelated L-dimensional latent GP
and returns the mean and the variance of the mixed GP, `f = W g`,
where both f and g are GPs, with W having a shape [P, L]
:param W: [P, L]
:param g_mu: [..... |
The size of this parameter equivalent to self. value. size | def size(self):
"""The size of this parameter, equivalent to self.value.size"""
return np.multiply.reduce(self.shape, dtype=np.int32) |
Takes out index from the parameter s tensor name. E. g. parameter tensor name is GPR - 0000/ kern/ lengthscales the method for that parameter will return 0000 index. | def tf_compilation_index(self):
"""
Takes out index from the parameter's tensor name. E.g. parameter tensor name is
GPR-0000/kern/lengthscales, the method for that parameter will return '0000' index.
"""
if self.parameter_tensor is None:
return None
name = se... |
Build a tensorflow representation of the prior density. The log Jacobian is included. | def _build_prior(self, unconstrained_tensor, constrained_tensor):
"""
Build a tensorflow representation of the prior density.
The log Jacobian is included.
"""
if not misc.is_tensor(unconstrained_tensor):
raise GPflowError("Unconstrained input must be a tensor.")
... |
Minimize a scalar Tensor. | def minimize(self,
session=None,
feed_dict=None,
fetches=None,
step_callback=None,
loss_callback=None,
**run_kwargs):
"""Minimize a scalar `Tensor`.
Variables subject to optimization are updated in-place at the end of
... |
Wrapper for a particular optimization algorithm implementation. | def _minimize(self, initial_val, loss_grad_func, equality_funcs,
equality_grad_funcs, inequality_funcs, inequality_grad_funcs,
packed_bounds, step_callback, optimizer_kwargs):
"""Wrapper for a particular optimization algorithm implementation.
It would be appropriate for a subcla... |
Pack a list of Tensor s into a single flattened rank - 1 Tensor. | def _pack(cls, tensors):
"""Pack a list of `Tensor`s into a single, flattened, rank-1 `Tensor`."""
if not tensors:
return None
elif len(tensors) == 1:
return array_ops.reshape(tensors[0], [-1])
else:
flattened = [array_ops.reshape(tensor, [-1]) for tensor in tensors]
return array... |
Construct a function that evaluates a Tensor or list of Tensor s. | def _make_eval_func(self, tensors, session, feed_dict, fetches,
callback=None):
"""Construct a function that evaluates a `Tensor` or list of `Tensor`s."""
if not isinstance(tensors, list):
tensors = [tensors]
num_tensors = len(tensors)
def eval_func(x):
"""Function to ... |
Creates the Tensorflow global_step variable ( see MonitorContext. global_step_tensor ).: param session: Tensorflow session the optimiser is running in: return: The variable tensor. | def create_global_step(session: tf.Session) -> tf.Variable:
"""
Creates the Tensorflow 'global_step' variable (see `MonitorContext.global_step_tensor`).
:param session: Tensorflow session the optimiser is running in
:return: The variable tensor.
"""
global_step_tensor = tf.Variable(0, trainable=... |
Restores Tensorflow session from the latest checkpoint.: param session: The TF session: param checkpoint_dir: checkpoint files directory.: param saver: The saver object if not provided a default saver object will be created. | def restore_session(session: tf.Session, checkpoint_dir: str,
saver: Optional[tf.train.Saver] = None) -> None:
"""
Restores Tensorflow session from the latest checkpoint.
:param session: The TF session
:param checkpoint_dir: checkpoint files directory.
:param saver: The saver obj... |
Creates Tensorflow Saver object with 3 recent checkpoints to keep.: param max_to_keep: Maximum number of recent checkpoints to keep defaults to 3 | def get_default_saver(max_to_keep: int=3) -> tf.train.Saver:
"""
Creates Tensorflow Saver object with 3 recent checkpoints to keep.
:param max_to_keep: Maximum number of recent checkpoints to keep, defaults to 3
"""
return tf.train.Saver(max_to_keep=max_to_keep) |
Writes optimiser state into corresponding TensorFlow variables. This may need to be done for optimisers like ScipyOptimiser that work with their own copies of the variables. Normally the source variables would be updated only when the optimiser has finished the minimisation. This function may be called from the callbac... | def update_optimiser(context, *args, **kwargs) -> None:
"""
Writes optimiser state into corresponding TensorFlow variables. This may need to be done
for optimisers like ScipyOptimiser that work with their own copies of the variables.
Normally the source variables would be updated only when the optimiser... |
Evaluates the value of the global step variable if it is set otherwise returns the current iteration number. | def global_step(self) -> int:
"""
Evaluates the value of the global step variable if it is set, otherwise returns the
current iteration number.
"""
if self.session is None or self.global_step_tensor is None:
return self.iteration_no + self.init_global_step
els... |
Sets the task running condition that will be evaluated during the optimisation cycle. | def with_condition(self, condition: Callable[[MonitorContext], bool]) -> 'MonitorTask':
"""
Sets the task running condition that will be evaluated during the optimisation cycle.
"""
self._condition = condition
return self |
Sets the flag indicating that the task should also run after the optimisation is ended. | def with_exit_condition(self, exit_condition: Optional[bool]=True) -> 'MonitorTask':
"""
Sets the flag indicating that the task should also run after the optimisation is ended.
"""
self._exit_condition = exit_condition
return self |
The recommended way of using Monitor is opening it with the with statement. In this case the user doesn t need to call this function explicitly. Otherwise the function should be called before starting the optimiser. | def start_monitoring(self) -> None:
"""
The recommended way of using Monitor is opening it with the `with` statement. In this case
the user doesn't need to call this function explicitly. Otherwise, the function should be
called before starting the optimiser.
The function evaluat... |
The recommended way of using Monitor is opening it with the with statement. In this case the user doesn t need to call this function explicitly. Otherwise the function should be called when the optimisation is done. | def stop_monitoring(self) -> None:
"""
The recommended way of using Monitor is opening it with the `with` statement. In this case
the user doesn't need to call this function explicitly. Otherwise the function should be
called when the optimisation is done.
The function sets the ... |
Prints the tasks timing summary. | def print_summary(self) -> None:
"""
Prints the tasks' timing summary.
"""
print("Tasks execution time summary:")
for mon_task in self._monitor_tasks:
print("%s:\t%.4f (sec)" % (mon_task.task_name, mon_task.total_time)) |
Called at each iteration. | def _on_iteration(self, *args, **kwargs) -> None:
"""
Called at each iteration.
This function does time measurements, updates timing in the monitoring context and calls
all monitoring tasks.
"""
# Update timing and the iteration number in the monitoring context.
... |
Returns an iterator that constructs a sequence of trigger levels with growing intervals. The interval is growing exponentially until it reaches the maximum value. Then the interval stays the same and the sequence becomes linear. | def _growing_step_sequence(interval_growth, max_interval, init_interval, start_level=None):
"""
Returns an iterator that constructs a sequence of trigger levels with growing intervals.
The interval is growing exponentially until it reaches the maximum value. Then the interval
stays the s... |
Attempts to lock the location used by this writer. Will raise an error if the location is already locked by another writer. Will do nothing if the location is already locked by this writer. | def __lock_location(self) -> None:
"""
Attempts to lock the location used by this writer. Will raise an error if the location is
already locked by another writer. Will do nothing if the location is already locked by
this writer.
"""
if not self._is_active:
if ... |
Releases the lock on the location used by this writer. Will do nothing if the lock is already released. | def __release_location(self) -> None:
"""
Releases the lock on the location used by this writer. Will do nothing if the lock is
already released.
"""
if self._is_active:
LogdirWriter._locked_locations.remove(self._location)
self._is_active = False |
Sets the flag indicating that the event file should be flushed at each call. | def with_flush_immediately(self, flush_immediately: Optional[bool]=True)\
-> 'BaseTensorBoardTask':
"""
Sets the flag indicating that the event file should be flushed at each call.
"""
self._flush_immediately = flush_immediately
return self |
Evaluates the summary tensor and writes the result to the event file.: param context: Monitor context: param feed_dict: Input values dictionary to be provided to the session. run when evaluating the summary tensor. | def _eval_summary(self, context: MonitorContext, feed_dict: Optional[Dict]=None) -> None:
"""
Evaluates the summary tensor and writes the result to the event file.
:param context: Monitor context
:param feed_dict: Input values dictionary to be provided to the `session.run`
when e... |
Returns two n - by - n matrices. The first one contains all the x values and the second all the y values of a cartesian product between xx and yy. | def make_grid(xx, yy):
"""
Returns two n-by-n matrices. The first one contains all the x values
and the second all the y values of a cartesian product between `xx` and `yy`.
"""
n = len(xx)
xx, yy = np.meshgrid(xx, yy)
grid = np.array([xx.ravel(), yy.ravel()]).T
x = grid[:, 0].reshape(n... |
Elapsed time [ µs ] between start and stop timestamps. If stop is empty then returned time is difference between start and current timestamp. | def elapsed(self):
"""
Elapsed time [µs] between start and stop timestamps. If stop is empty then
returned time is difference between start and current timestamp.
"""
if self._stop is None:
return timer() - self._start
return self._stop - self._start |
Gives an access to action s watcher. | def watcher(self) -> Watcher:
"""
Gives an access to action's watcher.
:return: Action's watcher instance.
"""
if not hasattr(self, "_watcher"):
self._watcher = Watcher()
return self._watcher |
Set start stop and step loop configuration. | def with_settings(self,
stop: Optional[int] = None,
start: int = 0,
step: int = 1) -> 'Loop':
"""
Set start, stop and step loop configuration.
:param stop: Looop stop iteration integer. If None then loop
becomes infinite.
:para... |
Run performs loop iterations. | def run(self, context: ActionContext):
"""
Run performs loop iterations.
:param context: Action context.
"""
iterator = itertools.count(start=self.start, step=self.step)
for i in iterator:
self.with_iteration(i)
if self.stop is not None and i ... |
Replace optimizer tensor. | def with_optimizer_tensor(self, tensor: Union[tf.Tensor, tf.Operation]) -> 'Optimization':
"""
Replace optimizer tensor.
:param model: Tensorflow tensor.
:return: Optimization instance self reference.
"""
self._optimizer_tensor = tensor
return self |
Replace Tensorflow session run kwargs. Check Tensorflow session run [ documentation ] ( https:// www. tensorflow. org/ api_docs/ python/ tf/ Session ). | def with_run_kwargs(self, **kwargs: Dict[str, Any]) -> 'Optimization':
"""
Replace Tensorflow session run kwargs.
Check Tensorflow session run [documentation](https://www.tensorflow.org/api_docs/python/tf/Session).
:param kwargs: Dictionary of tensors as keys and numpy arrays or
... |
The optimizer_tensor is an attribute for getting optimization s optimizer tensor. | def optimizer_tensor(self) -> Union[tf.Tensor, tf.Operation]:
"""
The `optimizer_tensor` is an attribute for getting optimization's
optimizer tensor.
"""
return _get_attr(self, _optimizer_tensor=None) |
Single - output GP conditional. | def _conditional(Xnew, feat, kern, f, *, full_cov=False, full_output_cov=False, q_sqrt=None, white=False):
"""
Single-output GP conditional.
The covariance matrices used to calculate the conditional have the following shape:
- Kuu: M x M
- Kuf: M x N
- Kff: N or N x N
Further reference
... |
Given f representing the GP at the points X produce the mean and ( co - ) variance of the GP at the points Xnew. | def _conditional(Xnew, X, kern, f, *, full_cov=False, q_sqrt=None, white=False, full_output_cov=None):
"""
Given f, representing the GP at the points X, produce the mean and
(co-)variance of the GP at the points Xnew.
Additionally, there may be Gaussian uncertainty about f as represented by
q_sqrt.... |
sample_conditional will return a sample from the conditional distribution. In most cases this means calculating the conditional mean m and variance v and then returning m + sqrt ( v ) * eps with eps ~ N ( 0 1 ). However for some combinations of Mok and Mof more efficient sampling routines exists. The dispatcher will ma... | def _sample_conditional(Xnew, feat, kern, f, *, full_cov=False, full_output_cov=False, q_sqrt=None, white=False, num_samples=None):
"""
`sample_conditional` will return a sample from the conditional distribution.
In most cases this means calculating the conditional mean m and variance v and then
returni... |
r Given a g1 and g2 and distribution p and q such that p ( g2 ) = N ( g2 ; 0 Kmm ) p ( g1 ) = N ( g1 ; 0 Knn ) p ( g1|g2 ) = N ( g1 ; 0 Knm ) And q ( g2 ) = N ( g2 ; f q_sqrt * q_sqrt^T ) This method computes the mean and ( co ) variance of q ( g1 ) = \ int q ( g2 ) p ( g1|g2 ): param Kmn: M x [... ] x N: param Kmm: M ... | def base_conditional(Kmn, Kmm, Knn, f, *, full_cov=False, q_sqrt=None, white=False):
r"""
Given a g1 and g2, and distribution p and q such that
p(g2) = N(g2;0,Kmm)
p(g1) = N(g1;0,Knn)
p(g1|g2) = N(g1;0,Knm)
And
q(g2) = N(g2;f,q_sqrt*q_sqrt^T)
This method computes the mean and (co... |
Calculates the conditional for uncertain inputs Xnew p ( Xnew ) = N ( Xnew_mu Xnew_var ). See conditional documentation for further reference. | def uncertain_conditional(Xnew_mu, Xnew_var, feat, kern, q_mu, q_sqrt, *,
mean_function=None, full_output_cov=False, full_cov=False, white=False):
"""
Calculates the conditional for uncertain inputs Xnew, p(Xnew) = N(Xnew_mu, Xnew_var).
See ``conditional`` documentation for further... |
Returns a sample from a D - dimensional Multivariate Normal distribution: param mean: [... N D ]: param cov: [... N D ] or [... N D D ]: param cov_structure: diag or full - diag: cov holds the diagonal elements of the covariance matrix - full: cov holds the full covariance matrix ( without jitter ): return: sample from... | def _sample_mvn(mean, cov, cov_structure=None, num_samples=None):
"""
Returns a sample from a D-dimensional Multivariate Normal distribution
:param mean: [..., N, D]
:param cov: [..., N, D] or [..., N, D, D]
:param cov_structure: "diag" or "full"
- "diag": cov holds the diagonal elements of the ... |
Reshapes fvar to the correct shape specified by full_cov and full_output_cov. | def _expand_independent_outputs(fvar, full_cov, full_output_cov):
"""
Reshapes fvar to the correct shape, specified by `full_cov` and `full_output_cov`.
:param fvar: has shape N x P (full_cov = False) or P x N x N (full_cov = True).
:return:
1. full_cov: True and full_output_cov: True
fvar N... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.