text
stringlengths
81
112k
回传数据 https://wximg.qq.com/wxp/pdftool/get.html?id=rkalQXDBM&pa=39 :param actions: 用户行为源类型 :param version: 版本号 v1.0 def add_user_actions(self, actions=(), version='v1.0'): """ 回传数据 https://wximg.qq.com/wxp/pdftool/get.html?id=rkalQXDBM&pa=39 :param actions: 用户...
获取朋友圈销售线索数据接口 :param start_date: 开始日期 默认今天 :param end_date: 结束日期 默认今天 :param filtering: 过滤条件 [{field: 过滤字段, operator: 操作符, values: 字段取值}] :param page: 页码,获取指定页数据 :param page_size: 一页获取的数据条数(1-100) :param version: 版本号 v1.0 def get_ad_leads(self, start_date=None, end_date...
统一下单接口 :param trade_type: 交易类型,取值如下:JSAPI,NATIVE,APP,WAP, MWEB :param body: 商品描述 :param total_fee: 总金额,单位分 :param notify_url: 接收微信支付异步通知回调地址 :param client_ip: 可选,APP和网页支付提交用户端ip,Native支付填调用微信支付API的机器IP :param user_id: 可选,用户在商户appid下的唯一标识。trade_type=JSAPI和appid已设定,此参数必传 ...
关闭订单 :param out_trade_no: 商户系统内部的订单号 :return: 返回的结果数据 def close(self, out_trade_no): """ 关闭订单 :param out_trade_no: 商户系统内部的订单号 :return: 返回的结果数据 """ data = { 'appid': self.appid, 'out_trade_no': out_trade_no, } retu...
获取 APP 支付参数 :param prepay_id: 统一下单接口返回的 prepay_id 参数值 :param timestamp: 可选,时间戳,默认为当前时间戳 :param nonce_str: 可选,随机字符串,默认自动生成 :return: 签名 def get_appapi_params(self, prepay_id, timestamp=None, nonce_str=None): """ 获取 APP 支付参数 :param prepay_id: 统一下单接口返回的 prepay_id 参...
撤销订单 :param transaction_id: 可选,微信的订单号,优先使用 :param out_trade_no: 可选,商户系统内部的订单号, transaction_id、out_trade_no二选一, 如果同时存在优先级:transaction_id> out_trade_no :return: 返回的结果数据 def reverse(self, transaction_id=None, out_trade_no=None): """ ...
获取用户基本信息(包括UnionID机制) 详情请参考 https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140839 :param user_id: 普通用户的标识,对当前公众号唯一 :param lang: 返回国家地区语言版本,zh_CN 简体,zh_TW 繁体,en 英语 :return: 返回的 JSON 数据包 使用示例:: from wechatpy import WeChatClient client...
获取一页用户列表(当关注用户过多的情况下,这个接口只会返回一部分用户) 详情请参考 https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140840 :param first_user_id: 可选。第一个拉取的 OPENID,不填默认从头开始拉取 :return: 返回的 JSON 数据包 使用示例:: from wechatpy import WeChatClient client = WeChatClient('appid',...
获取所有的用户openid列表 详情请参考 https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140840 :return: 返回一个迭代器,可以用for进行循环,得到openid 使用示例:: from wechatpy import WeChatClient client = WeChatClient('appid', 'secret') for openid in client.user.iter_followers...
获取用户所在分组 ID 详情请参考 http://mp.weixin.qq.com/wiki/0/56d992c605a97245eb7e617854b169fc.html :param user_id: 用户 ID :return: 用户所在分组 ID 使用示例:: from wechatpy import WeChatClient client = WeChatClient('appid', 'secret') group_id = client.user.get_gr...
批量获取用户基本信息 开发者可通过该接口来批量获取用户基本信息。最多支持一次拉取100条。 详情请参考 https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140839 :param user_list: user_list,支持“使用示例”中两种输入格式 :return: 用户信息的 list 使用示例:: from wechatpy import WeChatClient client = WeChatClien...
微信公众号主体变更迁移用户 openid 详情请参考 http://kf.qq.com/faq/170221aUnmmU170221eUZJNf.html :param from_appid: 原公众号的 appid :param openid_list: 需要转换的openid,这些必须是旧账号目前关注的才行,否则会出错;一次最多100个 :return: 转换后的 openid 信息列表 def change_openid(self, from_appid, openid_list): '''微信公众号主体变更迁移用户 open...
通用的消息发送接口。msg 内需要指定 msgtype 和对应类型消息必须的字段。 如果部分接收人无权限或不存在,发送仍然执行,但会返回无效的部分(即invaliduser或invalidparty或invalidtag),常见的原因是接收人不在应用的可见范围内。 user_ids、party_ids、tag_ids 不能同时为空,后面不再强调。 :param agent_id: 必填,企业应用的id,整型。可在应用的设置页面查看。 :param user_ids: 成员ID列表。 :param party_ids: 部门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" :...
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...
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...
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...
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...
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 ...
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): """ ...
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.outpu...
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....
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 ...
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 stand...
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 =...
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 predic...
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...
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...
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...
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...
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 nod...
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. d...
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 ...
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: ...
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...
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...
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...
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 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_te...
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_el...
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) ...
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 ...
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 ...
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 ker...
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...
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...
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 k...
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...
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 ca...
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: retu...
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 kern...
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: .. ...
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 un...
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 tr...
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 ...
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): """ Transf...
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...
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 ...
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 calli...
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 com...
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 calli...
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 _bui...
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...
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, f...
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 ...
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...
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 ...
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...
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...
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...
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 ...
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...
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 c...
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...
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...
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 ...
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 = l...
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 ...
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 ----------------- ...
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 ...
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 ...
`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...
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...
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...
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 ...
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, .....
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-0...
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(unc...
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`. ...
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_...
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 = [arra...
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] n...
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 `Monit...
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, ...
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: Maxi...
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...
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.sessi...
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 = c...
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_conditi...