INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
通用的消息发送接口。msg 内需要指定 msgtype 和对应类型消息必须的字段。 如果部分接收人无权限或不存在,发送仍然执行,但会返回无效的部分(即invaliduser或invalidparty或invalidtag),常见的原因是接收人不在应用的可见范围内。 user_ids、party_ids、tag_ids 不能同时为空,后面不再强调。 :param agent_id: 必填,企业应用的id,整型。可在应用的设置页面查看。 :param user_ids: 成员ID列表。 :param party_ids: 部门ID列表。 :...
def send(self, agent_id, user_ids, party_ids='', tag_ids='', msg=None): """ 通用的消息发送接口。msg 内需要指定 msgtype 和对应类型消息必须的字段。 如果部分接收人无权限或不存在,发送仍然执行,但会返回无效的部分(即invaliduser或invalidparty或invalidtag),常见的原因是接收人不在应用的可见范围内。 user_ids、party_ids、tag_ids 不能同时为空,后面不再强调。 :param agent_id...
文本卡片消息 https://work.weixin.qq.com/api/doc#90000/90135/90236/文本卡片消息 请求示例: { "touser" : "UserID1|UserID2|UserID3", "toparty" : "PartyID1 | PartyID2", "totag" : "TagID1 | TagID2", "msgtype" : "textcard", "agentid" : 1, "textcard" :...
def send_text_card(self, agent_id, user_ids, title, description, url, btntxt='详情', party_ids='', tag_ids=''): """ 文本卡片消息 https://work.weixin.qq.com/api/doc#90000/90135/90236/文本卡片消息 请求示例: { "touser" : "UserID1|UserID2|UserID3", "toparty" : "P...
markdown消息 https://work.weixin.qq.com/api/doc#90000/90135/90236/markdown%E6%B6%88%E6%81%AF > 目前仅支持markdown语法的子集 > 微工作台(原企业号)不支持展示markdown消息 :param agent_id: 企业应用的id,整型。可在应用的设置页面查看 :type agent_id: string :param content: markdown内容,最长不超过2048个字节,必须是utf8编码 :type co...
def send_markdown(self, agent_id, user_ids, content, party_ids='', tag_ids=''): """markdown消息 https://work.weixin.qq.com/api/doc#90000/90135/90236/markdown%E6%B6%88%E6%81%AF > 目前仅支持markdown语法的子集 > 微工作台(原企业号)不支持展示markdown消息 :param agent_id: 企业应用的id,整型。可在应用的设置页面查看 :type ...
Computes the log-density of a multivariate normal. :param x : Dx1 or DxN sample(s) for which we want the density :param mu : Dx1 or DxN mean(s) of the normal distribution :param L : DxD Cholesky decomposition of the covariance matrix :return p : (1,) or (N,) vector of log densities for each of the N x...
def multivariate_normal(x, mu, L): """ Computes the log-density of a multivariate normal. :param x : Dx1 or DxN sample(s) for which we want the density :param mu : Dx1 or DxN mean(s) of the normal distribution :param L : DxD Cholesky decomposition of the covariance matrix :return p : (1,) or (...
Make Tensorflow optimization tensor. This method builds optimization tensor and initializes all necessary variables created by optimizer. :param model: GPflow model. :param session: Tensorflow session. :param var_list: List of variables for training. :par...
def make_optimize_tensor(self, model, session=None, var_list=None, **kwargs): """ Make Tensorflow optimization tensor. This method builds optimization tensor and initializes all necessary variables created by optimizer. :param model: GPflow model. :param session:...
Build Optimization action task with Tensorflow optimizer. :param model: GPflow model. :param session: Tensorflow session. :param var_list: List of Tensorflow variables to train. :param feed_dict: Tensorflow feed_dict dictionary. :param kwargs: Extra parameter...
def make_optimize_action(self, model, session=None, var_list=None, **kwargs): """ Build Optimization action task with Tensorflow optimizer. :param model: GPflow model. :param session: Tensorflow session. :param var_list: List of Tensorflow variables to train. ...
Minimizes objective function of the model. :param model: GPflow model with objective tensor. :param session: Session where optimization will be run. :param var_list: List of extra variables which should be trained during optimization. :param feed_dict: Feed dictionary of tensors passed ...
def minimize(self, model, session=None, var_list=None, feed_dict=None, maxiter=1000, initialize=False, anchor=True, step_callback=None, **kwargs): """ Minimizes objective function of the model. :param model: GPflow model with objective tensor. :param session: Session wh...
Pass session configuration options
def get_session(*args, **kwargs): """ Pass session configuration options """ if 'config' not in kwargs: kwargs['config'] = tf.ConfigProto(**settings.session) if settings.profiling.dump_timeline: def fill_kwargs(key, value): """ Internal function for filling de...
Creates trace filename.
def _trace_filename(self): """ Creates trace filename. """ dir_stub = '' if self.output_directory is not None: dir_stub = self.output_directory if self.each_time: filename = '{0}_{1}.json'.format( self.output_file_name, self.counter...
Make SciPy optimization tensor. The `make_optimize_tensor` method builds optimization tensor and initializes all necessary variables created by optimizer. :param model: GPflow model. :param session: Tensorflow session. :param var_list: List of variables for training....
def make_optimize_tensor(self, model, session=None, var_list=None, **kwargs): """ Make SciPy optimization tensor. The `make_optimize_tensor` method builds optimization tensor and initializes all necessary variables created by optimizer. :param model: GPflow model. ...
Minimizes objective function of the model. :param model: GPflow model with objective tensor. :param session: Session where optimization will be run. :param var_list: List of extra variables which should be trained during optimization. :param feed_dict: Feed dictionary of tensors passed ...
def minimize(self, model, session=None, var_list=None, feed_dict=None, maxiter=1000, disp=False, initialize=False, anchor=True, step_callback=None, **kwargs): """ Minimizes objective function of the model. :param model: GPflow model with objective tensor. :param session...
Before calling the standard compile function, check to see if the size of the data has changed and add parameters appropriately. This is necessary because the shape of the parameters depends on the shape of the data.
def compile(self, session=None): """ Before calling the standard compile function, check to see if the size of the data has changed and add parameters appropriately. This is necessary because the shape of the parameters depends on the shape of the data. """ if no...
r""" Construct a tf function to compute the likelihood of a general GP model. \log p(Y, V | theta).
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 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.
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, th...
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. :param session: TensorFlow session used for initializing. If the node is built the session's graph...
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. :param session: TensorFlow session used for initializing. In case when session i...
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. :raises: GPflowError exception when parent of the node is built.
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. :param graph: TensorFlow graph or None. Default is None. :return: TensorFlow graph.
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 ...
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`. :return: `Build` status. :raises GPflowError: Valid passed TensorFlow graph is different from used graph in node.
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. :raises GPflowError: Node's parts were built with different graph and differ from default T...
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 uniquin...
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 :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 of value. :return: Tuple (value, ARD), where _value_ is a scalar ...
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...
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. This function can deal with leading dimensions in X and X2. In the sample case, where X and X2 ar...
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)². Internally, this calls self.K_r2(r²), which in turn computes the square-root and calls self.K_r(r). Classes impleme...
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:: 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 log sum exp trick: .. ...
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. :param obj: target GPflow object. :param name: unique part of autoflow att...
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...
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.
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. """ ...
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 be cleared, in other words it clears everything with common ...
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 ...
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)
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. This is necessary because the shape of the parameters depends on the shape of the data.
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} + di...
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. 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 evaluation points. :param D: Number of input dim...
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 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. :param funcs: the integrand(s): Callable or Iterable of Callables that operates elementwise, on the following arguments: - `Din` positional arguments to match Fm...
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. :param funcs: the integrand(s): Callable or Iterable of Callables that operates elementwise :param S: number of Monte Carlo sampling points :param Fmu: array/tensor ...
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. ``` >>> @name_scope() >>> def foo(...): >>> # now runs inside scope "foo" >>> @name_scope('bar') >>> de...
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). This can also be used to turn off tensor conversion functions wrapped with `params_as_tensors`: ``` @gpflow.params_as_tensors def compute_something(self): # self is paramet...
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 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 the divergences. q_mu is a matrix [M, L], each column contains...
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). The covariance matrices used to calculate the conditional have the following shape: - Kuu: P x M x M - Kuf: P x M x N - Kff: P x N or P x N x N Further reference ----------------- ...
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. The covariance matrices used to calculate the conditional have the following shape: - Kuu: M x L x M x L ...
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. The covariance matrices used to calculate the conditional have the following shape: - Kuu: L x M x M - Kuf: L x M x N - Kff: L x N or 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 dis...
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. :param Kmn: M x L x N x P :param Kmm: L x M x M :param Knn: N x P or N x N or P x N x N or N x P x N x P :param f: data matrix, M x L :param q_sqrt: L x M x M or M x L :param full_cov: calculate cov...
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...
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. Note: This conditional can handle 'repetitions' R, given in `f` and `q_sqrt`. :param Kmn: LM x N x P :param Kmm: LM x LM :param Knn: N x P or ...
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] :param W: [P, L] :param g_mu: [..., N, L] :param g_var: [..., N, L] (full_cov = False) or [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`. Variables subject to optimization are updated in-place at the end of optimization. Note that this method does *not* just return a minimization `Op`, unlike `Optimizer.minimize()`; instead it actually performs minimization by executing commands to control a `Session`. ...
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. It would be appropriate for a subclass implementation of this method to raise `NotImplementedError` if unsupported arguments are passed: e.g. if an algorithm does not support constraints but `len(equality_funcs) > 0`. Args: initial_...
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 ...
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 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=...
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...
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. The function evaluates the global_step variable in order to get its initial ...
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. The function sets the optimisation completed flag in the monitoring context a...
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. This function does time measurements, updates timing in the monitoring context and calls all monitoring tasks.
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. An optional starting level `start_level` defaults to the initial i...
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...
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. :return: Action's watcher instance.
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. :param stop: Looop stop iteration integer. If None then loop becomes infinite. :param start: Loop iteration start integer. :param step: Loop iteration interval integer. :return: Loop itself.
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...