INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Roll the tensor A forward num_rolls times
def _rollaxis_right(A, num_rolls): """ Roll the tensor `A` forward `num_rolls` times """ assert num_rolls > 0 rank = tf.rank(A) perm = tf.concat([rank - num_rolls + tf.range(num_rolls), tf.range(rank - num_rolls)], 0) return tf.transpose(A, perm)
Models which used to take only Z can now pass feat and Z to this method. This method will check for consistency and return the correct feature. This allows backwards compatibility in for the methods.
def inducingpoint_wrapper(feat, Z): """ Models which used to take only Z can now pass `feat` and `Z` to this method. This method will check for consistency and return the correct feature. This allows backwards compatibility in for the methods. """ if feat is not None and Z is not None: r...
Custom version of _square_dist that allows sc to provide per - datapoint length scales. sc: N x M x D.
def _cust_square_dist(A, B, sc): """ Custom version of _square_dist that allows sc to provide per-datapoint length scales. sc: N x M x D. """ return tf.reduce_sum(tf.square((tf.expand_dims(A, 1) - tf.expand_dims(B, 0)) / sc), 2)
Construct a tensorflow function to compute the bound on the marginal likelihood. For a derivation of the terms in here see the associated SGPR notebook.
def _build_likelihood(self): """ Construct a tensorflow function to compute the bound on the marginal likelihood. For a derivation of the terms in here, see the associated SGPR notebook. """ num_inducing = len(self.feature) num_data = tf.cast(tf.shape(self.Y)[0],...
Compute the mean and variance of the latent function at some new points Xnew. For a derivation of the terms in here see the associated SGPR notebook.
def _build_predict(self, Xnew, full_cov=False): """ Compute the mean and variance of the latent function at some new points Xnew. For a derivation of the terms in here, see the associated SGPR notebook. """ num_inducing = len(self.feature) err = self.Y - self.mea...
Computes the mean and variance of q ( u ) the variational distribution on inducing outputs. SVGP with this q ( u ) should predict identically to SGPR.: return: mu A
def compute_qu(self): """ Computes the mean and variance of q(u), the variational distribution on inducing outputs. SVGP with this q(u) should predict identically to SGPR. :return: mu, A """ Kuf = features.Kuf(self.feature, self.kern, self.X) Kuu = feature...
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. """ # FITC approximation to the log marginal likelihood is # log ( normal( y | mean, K_fitc ) ) # where K_fitc = Qff + diag( \nu ) # where Qf...
Compute the mean and variance of the latent function at some new points Xnew.
def _build_predict(self, Xnew, full_cov=False): """ Compute the mean and variance of the latent function at some new points Xnew. """ _, _, Luu, L, _, _, gamma = self._build_common_terms() Kus = features.Kuf(self.feature, self.kern, Xnew) # size M x Xnew w = tf...
Transposes tensors with leading dimensions. Leading dimensions in permutation list represented via ellipsis....
def leading_transpose(tensor: tf.Tensor, perm: List[Union[int, type(...)]]) -> tf.Tensor: """ Transposes tensors with leading dimensions. Leading dimensions in permutation list represented via ellipsis `...`. When leading dimensions are found, `transpose` method considers them as a single grouped e...
Work out what a sensible type for the array is. if the default type is float32 downcast 64bit float to float32. For ints assume int32
def normalize_num_type(num_type): """ Work out what a sensible type for the array is. if the default type is float32, downcast 64bit float to float32. For ints, assume int32 """ if isinstance(num_type, tf.DType): num_type = num_type.as_numpy_dtype.type if num_type in [np.float32, np.flo...
Takes a D x M tensor vectors and maps it to a D x matrix_size X matrix_sizetensor where the where the lower triangle of each matrix_size x matrix_size matrix is constructed by unpacking each M - vector.
def vec_to_tri(vectors, N): """ Takes a D x M tensor `vectors' and maps it to a D x matrix_size X matrix_sizetensor where the where the lower triangle of each matrix_size x matrix_size matrix is constructed by unpacking each M-vector. Native TensorFlow version of Custom Op by Mark van der Wilk. ...
Converts between GPflow indexing and tensorflow indexing method is a function that broadcasts over the first dimension ( i. e. like all tensorflow matrix ops ): method inputs DN1 DNN method outputs DN1 DNN: return: Function that broadcasts over the final dimension ( i. e. compatible with GPflow ): inputs: ND DNN output...
def swap_dimensions(method): """ Converts between GPflow indexing and tensorflow indexing `method` is a function that broadcasts over the first dimension (i.e. like all tensorflow matrix ops): `method` inputs DN1, DNN `method` outputs DN1, DNN :return: Function that broadcasts over the f...
Take inverse of lower triangular ( e. g. Cholesky ) matrix. This function broadcasts over the first index.
def _inverse_lower_triangular(M): """ Take inverse of lower triangular (e.g. Cholesky) matrix. This function broadcasts over the first index. :param M: Tensor with lower triangular structure of shape DxNxN :return: The inverse of the Cholesky decomposition. Same shape as input. """ if M.get...
Make Tensorflow optimization tensor. This method builds natural gradients optimization tensor and initializes all necessary variables created by the optimizer.
def make_optimize_tensor(self, model, session=None, var_list=None): """ Make Tensorflow optimization tensor. This method builds natural gradients optimization tensor and initializes all necessary variables created by the optimizer. :param model: GPflow model. :pa...
Forward - mode pushforward analogous to the pullback defined by tf. gradients. With tf. gradients grad_ys is the vector being pulled back and here d_xs is the vector being pushed forward i. e. this computes ( ∂ys/ ∂xs ) ^T ∂xs.
def _forward_gradients(ys, xs, d_xs): """ Forward-mode pushforward analogous to the pullback defined by tf.gradients. With tf.gradients, grad_ys is the vector being pulled back, and here d_xs is the vector being pushed forward, i.e. this computes (∂ys / ∂xs)^T ∂xs. This is adapt...
Implements equation 10 from
def _build_natgrad_step_op(self, model, q_mu_param, q_sqrt_param, xi_transform): """ Implements equation 10 from @inproceedings{salimbeni18, title={Natural Gradients in Practice: Non-Conjugate Variational Inference in Gaussian Process Models}, author={Salimbeni, Hugh an...
: 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 to session run method.: param maxiter: Number of run interation.: param ini...
def minimize(self, model, session=None, var_list=None, feed_dict=None, maxiter=1000, initialize=True, anchor=True, step_callback=None, **kwargs): """ :param model: GPflow model with objective tensor. :param session: Session where optimization will be run. :param var_list...
Store compilation flag at specified index in context s shared data.
def _check_index_in_compilations(context: BaseContext, index: str): """Store compilation flag at specified index in context's shared data.""" compilations = 'compilations' if compilations not in context.shared_data: return False return index in context.shared_data[compilations]
Build structured numpy array.
def struct(cls, type_name: int, data: np.ndarray, data_dtype: np.dtype = None, shape: Tuple = None): """Build structured numpy array. :param int type_name: StructType enum converted to integer. :param data: encoded data as a numpy array or a structured numpy array. :param data_dtype: nu...
Takes snapshot of the object and replaces _parent property value on None to avoid infitinite recursion in GPflow tree traversing.
def _take_values(self, item: Node) -> DictBasicType: """Takes snapshot of the object and replaces _parent property value on None to avoid infitinite recursion in GPflow tree traversing. :param item: GPflow node object. :return: dictionary snapshot of the node object.""" values ...
Uses super (). _take_values () method but replaces content of the cached value to the value assossiated with context s session.
def _take_values(self, item: Parameter) -> DictBasicType: """Uses super()._take_values() method, but replaces content of the cached value to the value assossiated with context's session. :param item: GPflow parameter. :return: dictionary snapshot of the parameter object.""" ses...
Return either this GPflow objects requires compilation at decoding time.
def _take_extras(self, item: Parameter) -> Optional[bool]: """Return either this GPflow objects requires compilation at decoding time. :param item: GPflow parameter. :return: None or True value. """ index = item.tf_compilation_index() if index is not None: i...
Uses super (). _take_values () method and removes autoflow cache in - place.
def _take_values(self, item: Parameterized) -> DictBasicType: """Uses super()._take_values() method and removes autoflow cache in-place. :param item: GPflow parameterized object. :return: dictionary snapshot of the parameter object.""" values = super()._take_values(item) values...
List of default supported coders. First coder in the list has higher priority.
def coders(self): """List of default supported coders. First coder in the list has higher priority.""" return (PrimitiveTypeCoder, TensorFlowCoder, FunctionCoder, ListCoder, DictCoder, SliceCoder, ParameterCo...
Path name is a recursive representation parent path name plus the name which was assigned to this object by its parent. In other words it is stack of parent name where top is always parent s original name: parent. pathname + parent. childname and stop condition is root s name.
def pathname(self): """ Path name is a recursive representation parent path name plus the name which was assigned to this object by its parent. In other words, it is stack of parent name where top is always parent's original name: `parent.pathname + parent.childname` and stop con...
Scans full list of node descendants.
def _descendants(self): """ Scans full list of node descendants. :return: Generator of nodes. """ children = self._children if children is not None: for child in children.values(): yield from child._descendants yield child
Set child.
def _set_child(self, name, child): """ Set child. :param name: Child name. :param child: Parentable object. """ if not isinstance(child, Parentable): raise ValueError('Parentable child object expected, not {child}'.format(child=child)) child._set_pare...
Untie child from parent.
def _unset_child(self, name, child): """ Untie child from parent. :param name: Child name. :param child: Parentable object. """ if name not in self._children or self._children[name] is not child: msg = 'Child {child} with name "{name}" is not found' ...
Set parent.
def _set_parent(self, parent=None): """ Set parent. :param parent: Parentable object. :raises ValueError: Self-reference object passed. :raises ValueError: Non-Parentable object passed. """ if parent is not None: if not isinstance(parent, Parentable):...
Produce samples from the posterior latent function ( s ) at the points Xnew.
def predict_f_samples(self, Xnew, num_samples): """ Produce samples from the posterior latent function(s) at the points Xnew. """ mu, var = self._build_predict(Xnew, full_cov=True) # N x P, # P x N x N jitter = tf.eye(tf.shape(mu)[0], dtype=settings.float_type) * setting...
Compute the mean and variance of held - out data at the points Xnew
def predict_y(self, Xnew): """ Compute the mean and variance of held-out data at the points Xnew """ pred_f_mean, pred_f_var = self._build_predict(Xnew) return self.likelihood.predict_mean_and_var(pred_f_mean, pred_f_var)
Compute the ( log ) density of the data Ynew at the points Xnew
def predict_density(self, Xnew, Ynew): """ Compute the (log) density of the data Ynew at the points Xnew Note that this computes the log density of the data individually, ignoring correlations between them. The result is a matrix the same shape as Ynew containing the log densiti...
r Construct a tensorflow function to compute the likelihood.
def _build_likelihood(self): r""" Construct a tensorflow function to compute the likelihood. \log p(Y | theta). """ K = self.kern.K(self.X) + tf.eye(tf.shape(self.X)[0], dtype=settings.float_type) * self.likelihood.variance L = tf.cholesky(K) m = self.mean_f...
Xnew is a data matrix the points at which we want to predict.
def _build_predict(self, Xnew, full_cov=False): """ Xnew is a data matrix, the points at which we want to predict. This method computes p(F* | Y) where F* are points on the GP at Xnew, Y are noisy observations at X. """ y = self.Y - self.mean_function(self...
Compute the expectation <obj1 ( x ) obj2 ( x ) > _p ( x ) Uses Gauss - Hermite quadrature for approximate integration.
def quadrature_expectation(p, obj1, obj2=None, num_gauss_hermite_points=None): """ Compute the expectation <obj1(x) obj2(x)>_p(x) Uses Gauss-Hermite quadrature for approximate integration. :type p: (mu, cov) tuple or a `ProbabilityDistribution` object :type obj1: kernel, mean function, (kernel, fea...
Return the function of interest ( kernel or mean ) for the expectation depending on the type of: obj: and whether any features are given
def get_eval_func(obj, feature, slice=np.s_[...]): """ Return the function of interest (kernel or mean) for the expectation depending on the type of :obj: and whether any features are given """ if feature is not None: # kernel + feature combination if not isinstance(feature, Inducing...
General handling of quadrature expectations for Gaussians and DiagonalGaussians Fallback method for missing analytic expectations
def _quadrature_expectation(p, obj1, feature1, obj2, feature2, num_gauss_hermite_points): """ General handling of quadrature expectations for Gaussians and DiagonalGaussians Fallback method for missing analytic expectations """ num_gauss_hermite_points = 100 if num_gauss_hermite_points is None else ...
Handling of quadrature expectations for Markov Gaussians ( useful for time series ) Fallback method for missing analytic expectations wrt Markov Gaussians Nota Bene: obj1 is always associated with x_n whereas obj2 always with x_ { n + 1 } if one requires e. g. <x_ { n + 1 } K_ { x_n Z } > _p ( x_ { n: n + 1 } ) compute...
def _quadrature_expectation(p, obj1, feature1, obj2, feature2, num_gauss_hermite_points): """ Handling of quadrature expectations for Markov Gaussians (useful for time series) Fallback method for missing analytic expectations wrt Markov Gaussians Nota Bene: obj1 is always associated with x_n, whereas ob...
Compute the expectation <obj1 ( x ) obj2 ( x ) > _p ( x ) Uses multiple - dispatch to select an analytical implementation if one is available. If not it falls back to quadrature.
def expectation(p, obj1, obj2=None, nghp=None): """ Compute the expectation <obj1(x) obj2(x)>_p(x) Uses multiple-dispatch to select an analytical implementation, if one is available. If not, it falls back to quadrature. :type p: (mu, cov) tuple or a `ProbabilityDistribution` object :type obj1: ...
Compute the expectation: <diag ( K_ { X X } ) > _p ( X ) - K_ {.. }:: RBF kernel
def _expectation(p, kern, none1, none2, none3, nghp=None): """ Compute the expectation: <diag(K_{X, X})>_p(X) - K_{.,.} :: RBF kernel :return: N """ return kern.Kdiag(p.mu)
Compute the expectation: <K_ { X Z } > _p ( X ) - K_ {.. }:: RBF kernel
def _expectation(p, kern, feat, none1, none2, nghp=None): """ Compute the expectation: <K_{X, Z}>_p(X) - K_{.,.} :: RBF kernel :return: NxM """ with params_as_tensors_for(kern, feat): # use only active dimensions Xcov = kern._slice_cov(p.cov) Z, Xmu = kern._slice...
Compute the expectation: expectation [ n ] = <x_n K_ { x_n Z } > _p ( x_n ) - K_ {.. }:: RBF kernel
def _expectation(p, mean, none, kern, feat, nghp=None): """ Compute the expectation: expectation[n] = <x_n K_{x_n, Z}>_p(x_n) - K_{.,.} :: RBF kernel :return: NxDxM """ Xmu, Xcov = p.mu, p.cov with tf.control_dependencies([tf.assert_equal( tf.shape(Xmu)[1], tf.constant(...
Compute the expectation: expectation [ n ] = <Ka_ { Z1 x_n } Kb_ { x_n Z2 } > _p ( x_n ) - Ka_ {.. } Kb_ {.. }:: RBF kernels Ka and Kb as well as Z1 and Z2 can differ from each other.
def _expectation(p, kern1, feat1, kern2, feat2, nghp=None): """ Compute the expectation: expectation[n] = <Ka_{Z1, x_n} Kb_{x_n, Z2}>_p(x_n) - Ka_{.,.}, Kb_{.,.} :: RBF kernels Ka and Kb as well as Z1 and Z2 can differ from each other. :return: N x dim(Z1) x dim(Z2) """ if kern1.on...
Compute the expectation: <diag ( K_ { X X } ) > _p ( X ) - K_ {.. }:: Linear kernel
def _expectation(p, kern, none1, none2, none3, nghp=None): """ Compute the expectation: <diag(K_{X, X})>_p(X) - K_{.,.} :: Linear kernel :return: N """ with params_as_tensors_for(kern): # use only active dimensions Xmu, _ = kern._slice(p.mu, None) Xcov = kern._sl...
Compute the expectation: <K_ { X Z } > _p ( X ) - K_ {.. }:: Linear kernel
def _expectation(p, kern, feat, none1, none2, nghp=None): """ Compute the expectation: <K_{X, Z}>_p(X) - K_{.,.} :: Linear kernel :return: NxM """ with params_as_tensors_for(kern, feat): # use only active dimensions Z, Xmu = kern._slice(feat.Z, p.mu) return tf.m...
Compute the expectation: expectation [ n ] = <K_ { Z x_n } x_ { n + 1 } ^T > _p ( x_ { n: n + 1 } ) - K_ {.. }:: Linear kernel - p:: MarkovGaussian distribution ( p. cov 2x ( N + 1 ) xDxD )
def _expectation(p, kern, feat, mean, none, nghp=None): """ Compute the expectation: expectation[n] = <K_{Z, x_n} x_{n+1}^T>_p(x_{n:n+1}) - K_{.,.} :: Linear kernel - p :: MarkovGaussian distribution (p.cov 2x(N+1)xDxD) :return: NxMxD """ Xmu, Xcov = p.mu, p.cov with ...
Compute the expectation: expectation [ n ] = <Ka_ { Z1 x_n } Kb_ { x_n Z2 } > _p ( x_n ) - Ka_ {.. } Kb_ {.. }:: Linear kernels Ka and Kb as well as Z1 and Z2 can differ from each other but this is supported only if the Gaussian p is Diagonal ( p. cov NxD ) and Ka Kb have disjoint active_dims in which case the joint ex...
def _expectation(p, kern1, feat1, kern2, feat2, nghp=None): """ Compute the expectation: expectation[n] = <Ka_{Z1, x_n} Kb_{x_n, Z2}>_p(x_n) - Ka_{.,.}, Kb_{.,.} :: Linear kernels Ka and Kb as well as Z1 and Z2 can differ from each other, but this is supported only if the Gaussian p is Diago...
Compute the expectation: expectation [ n ] = <x_n K_ { x_n Z } > _p ( x_n ) - K_ {. }:: Linear kernel or the equivalent for MarkovGaussian
def _expectation(p, mean, none, kern, feat, nghp=None): """ Compute the expectation: expectation[n] = <x_n K_{x_n, Z}>_p(x_n) - K_{.,} :: Linear kernel or the equivalent for MarkovGaussian :return: NxDxM """ return tf.matrix_transpose(expectation(p, (kern, feat), mean))
Compute the expectation: expectation [ n ] = <m ( x_n ) ^T K_ { x_n Z } > _p ( x_n ) - m ( x_i ) = c:: Constant function - K_ {.. }:: Kernel function
def _expectation(p, constant_mean, none, kern, feat, nghp=None): """ Compute the expectation: expectation[n] = <m(x_n)^T K_{x_n, Z}>_p(x_n) - m(x_i) = c :: Constant function - K_{.,.} :: Kernel function :return: NxQxM """ with params_as_tensors_for(constant_mean): c =...
Compute the expectation: expectation [ n ] = <m ( x_n ) ^T K_ { x_n Z } > _p ( x_n ) - m ( x_i ) = A x_i + b:: Linear mean function - K_ {.. }:: Kernel function
def _expectation(p, linear_mean, none, kern, feat, nghp=None): """ Compute the expectation: expectation[n] = <m(x_n)^T K_{x_n, Z}>_p(x_n) - m(x_i) = A x_i + b :: Linear mean function - K_{.,.} :: Kernel function :return: NxQxM """ with params_as_tensors_for(linear_mea...
Compute the expectation: <m ( X ) > _p ( X ) - m ( x ):: Linear Identity or Constant mean function
def _expectation(p, mean, none1, none2, none3, nghp=None): """ Compute the expectation: <m(X)>_p(X) - m(x) :: Linear, Identity or Constant mean function :return: NxQ """ return mean(p.mu)
Compute the expectation: expectation [ n ] = <m1 ( x_n ) ^T m2 ( x_n ) > _p ( x_n ) - m1 (. ) m2 (. ):: Constant mean functions
def _expectation(p, mean1, none1, mean2, none2, nghp=None): """ Compute the expectation: expectation[n] = <m1(x_n)^T m2(x_n)>_p(x_n) - m1(.), m2(.) :: Constant mean functions :return: NxQ1xQ2 """ return mean1(p.mu)[:, :, None] * mean2(p.mu)[:, None, :]
Compute the expectation: expectation [ n ] = <m1 ( x_n ) ^T m2 ( x_n ) > _p ( x_n ) - m1 (. ):: Identity mean function - m2 (. ):: Linear mean function
def _expectation(p, mean1, none1, mean2, none2, nghp=None): """ Compute the expectation: expectation[n] = <m1(x_n)^T m2(x_n)>_p(x_n) - m1(.) :: Identity mean function - m2(.) :: Linear mean function :return: NxDxQ """ with params_as_tensors_for(mean2): N = tf.shape(p.mu)...
Compute the expectation: expectation [ n ] = <m1 ( x_n ) ^T m2 ( x_n ) > _p ( x_n ) - m1 (. ):: Linear mean function - m2 (. ):: Identity mean function
def _expectation(p, mean1, none1, mean2, none2, nghp=None): """ Compute the expectation: expectation[n] = <m1(x_n)^T m2(x_n)>_p(x_n) - m1(.) :: Linear mean function - m2(.) :: Identity mean function :return: NxQxD """ with params_as_tensors_for(mean1): N = tf.shape(p.mu)...
Compute the expectation: expectation [ n ] = <m1 ( x_n ) ^T m2 ( x_n ) > _p ( x_n ) - m1 (. ) m2 (. ):: Linear mean functions
def _expectation(p, mean1, none1, mean2, none2, nghp=None): """ Compute the expectation: expectation[n] = <m1(x_n)^T m2(x_n)>_p(x_n) - m1(.), m2(.) :: Linear mean functions :return: NxQ1xQ2 """ with params_as_tensors_for(mean1, mean2): e_xxt = p.cov + (p.mu[:, :, None] * p.mu[:,...
r Compute the expectation: < \ Sum_i Ki_ { X Z } > _p ( X ) - \ Sum_i Ki_ {.. }:: Sum kernel
def _expectation(p, kern, feat, none2, none3, nghp=None): r""" Compute the expectation: <\Sum_i Ki_{X, Z}>_p(X) - \Sum_i Ki_{.,.} :: Sum kernel :return: NxM """ return functools.reduce(tf.add, [ expectation(p, (k, feat), nghp=nghp) for k in kern.kernels])
r Compute the expectation: expectation [ n ] = <m ( x_n ) ^T ( \ Sum_i Ki_ { x_n Z } ) > _p ( x_n ) - \ Sum_i Ki_ {.. }:: Sum kernel
def _expectation(p, mean, none, kern, feat, nghp=None): r""" Compute the expectation: expectation[n] = <m(x_n)^T (\Sum_i Ki_{x_n, Z})>_p(x_n) - \Sum_i Ki_{.,.} :: Sum kernel :return: NxQxM """ return functools.reduce(tf.add, [ expectation(p, mean, (k, feat), nghp=nghp) for k in ...
r Compute the expectation: expectation [ n ] = < ( \ Sum_i K1_i_ { Z1 x_n } ) ( \ Sum_j K2_j_ { x_n Z2 } ) > _p ( x_n ) - \ Sum_i K1_i_ {.. } \ Sum_j K2_j_ {.. }:: Sum kernels
def _expectation(p, kern1, feat1, kern2, feat2, nghp=None): r""" Compute the expectation: expectation[n] = <(\Sum_i K1_i_{Z1, x_n}) (\Sum_j K2_j_{x_n, Z2})>_p(x_n) - \Sum_i K1_i_{.,.}, \Sum_j K2_j_{.,.} :: Sum kernels :return: NxM1xM2 """ crossexps = [] if kern1 == kern2 and feat1 ...
Compute the expectation: expectation [ n ] = <Ka_ { Z1 x_n } Kb_ { x_n Z2 } > _p ( x_n ) - K_lin_ {.. }:: RBF kernel - K_rbf_ {.. }:: Linear kernel Different Z1 and Z2 are handled if p is diagonal and K_lin and K_rbf have disjoint active_dims in which case the joint expectations simplify into a product of expectations
def _expectation(p, rbf_kern, feat1, lin_kern, feat2, nghp=None): """ Compute the expectation: expectation[n] = <Ka_{Z1, x_n} Kb_{x_n, Z2}>_p(x_n) - K_lin_{.,.} :: RBF kernel - K_rbf_{.,.} :: Linear kernel Different Z1 and Z2 are handled if p is diagonal and K_lin and K_rbf have disjoint...
Compute the expectation: expectation [ n ] = <Ka_ { Z1 x_n } Kb_ { x_n Z2 } > _p ( x_n ) - K_lin_ {.. }:: Linear kernel - K_rbf_ {.. }:: RBF kernel Different Z1 and Z2 are handled if p is diagonal and K_lin and K_rbf have disjoint active_dims in which case the joint expectations simplify into a product of expectations
def _expectation(p, lin_kern, feat1, rbf_kern, feat2, nghp=None): """ Compute the expectation: expectation[n] = <Ka_{Z1, x_n} Kb_{x_n, Z2}>_p(x_n) - K_lin_{.,.} :: Linear kernel - K_rbf_{.,.} :: RBF kernel Different Z1 and Z2 are handled if p is diagonal and K_lin and K_rbf have disjoint...
r Compute the expectation: < \ HadamardProd_i diag ( Ki_ { X [: active_dims_i ] X [: active_dims_i ] } ) > _p ( X ) - \ HadamardProd_i Ki_ {.. }:: Product kernel - p:: DiagonalGaussian distribution ( p. cov NxD )
def _expectation(p, kern, none1, none2, none3, nghp=None): r""" Compute the expectation: <\HadamardProd_i diag(Ki_{X[:, active_dims_i], X[:, active_dims_i]})>_p(X) - \HadamardProd_i Ki_{.,.} :: Product kernel - p :: DiagonalGaussian distribution (p.cov NxD) :retur...
r Compute the expectation: expectation [ n ] = < prodK_ { Z x_n } prodK_ { x_n Z } > _p ( x_n ) = < ( \ HadamardProd_i Ki_ { Z [: active_dims_i ] x [ n active_dims_i ] } ) < -- Mx1 1xM -- > ( \ HadamardProd_j Kj_ { x [ n active_dims_j ] Z [: active_dims_j ] } ) > _p ( x_n ) ( MxM )
def _expectation(p, kern1, feat1, kern2, feat2, nghp=None): r""" Compute the expectation: expectation[n] = < prodK_{Z, x_n} prodK_{x_n, Z} >_p(x_n) = < (\HadamardProd_i Ki_{Z[:, active_dims_i], x[n, active_dims_i]}) <-- Mx1 1xM --> (\HadamardProd_j Kj_{x[n, active_dims_j]...
Nota Bene: if only one object is passed obj1 is associated with x_n whereas obj2 with x_ { n + 1 }
def _expectation(p, obj1, feat1, obj2, feat2, nghp=None): """ Nota Bene: if only one object is passed, obj1 is associated with x_n, whereas obj2 with x_{n+1} """ if obj2 is None: gaussian = Gaussian(p.mu[:-1], p.cov[0, :-1]) return expectation(gaussian, (obj1, feat1), nghp=nghp) ...
A straight - forward HMC implementation. The mass matrix is assumed to be the identity.
def sample(self, model, num_samples, epsilon, lmin=1, lmax=1, thin=1, burn=0, session=None, initialize=True, anchor=True, logprobs=True): """ A straight-forward HMC implementation. The mass matrix is assumed to be the identity. The gpflow mod...
r Given a Normal distribution for the latent function return the mean of Y
def predict_mean_and_var(self, Fmu, Fvar): r""" Given a Normal distribution for the latent function, return the mean of Y if q(f) = N(Fmu, Fvar) and this object represents p(y|f) then this method computes the predictive mean \int\in...
r Given a Normal distribution for the latent function and a datum Y compute the log predictive density of Y.
def predict_density(self, Fmu, Fvar, Y): r""" Given a Normal distribution for the latent function, and a datum Y, compute the log predictive density of Y. i.e. if q(f) = N(Fmu, Fvar) and this object represents p(y|f) then this method computes t...
r Compute the expected log density of the data given a Gaussian distribution for the function values.
def variational_expectations(self, Fmu, Fvar, Y): r""" Compute the expected log density of the data, given a Gaussian distribution for the function values. if q(f) = N(Fmu, Fvar) and this object represents p(y|f) then this method computes ...
args is a list of tensors to be passed to self. likelihoods. <func_name >
def _partition_and_stitch(self, args, func_name): """ args is a list of tensors, to be passed to self.likelihoods.<func_name> args[-1] is the 'Y' argument, which contains the indexes to self.likelihoods. This function splits up the args using dynamic_partition, calls the releva...
A helper function for making predictions. Constructs a probability matrix where each row output the probability of the corresponding label and the rows match the entries of F.
def _make_phi(self, F): """ A helper function for making predictions. Constructs a probability matrix where each row output the probability of the corresponding label, and the rows match the entries of F. Note that a matrix of F values is flattened. """ scaled_bi...
r Given a Normal distribution for the latent function return the mean of Y
def predict_mean_and_var(self, Fmu, Fvar, epsilon=None): r""" Given a Normal distribution for the latent function, return the mean of Y if q(f) = N(Fmu, Fvar) and this object represents p(y|f) then this method computes the predictive mean ...
r Given a Normal distribution for the latent function and a datum Y compute the log predictive density of Y.
def predict_density(self, Fmu, Fvar, Y, epsilon=None): r""" Given a Normal distribution for the latent function, and a datum Y, compute the log predictive density of Y. i.e. if q(f) = N(Fmu, Fvar) and this object represents p(y|f) then this met...
r Compute the expected log density of the data given a Gaussian distribution for the function values.
def variational_expectations(self, Fmu, Fvar, Y, epsilon=None): r""" Compute the expected log density of the data, given a Gaussian distribution for the function values. if q(f) = N(Fmu, Fvar) - Fmu: N x D Fvar: N x D and this object represents p(y|f)...
Absorbs a Z^t gate into a W ( a ) flip.
def _absorb_z_into_w(moment_index: int, op: ops.Operation, state: _OptimizerState) -> None: """Absorbs a Z^t gate into a W(a) flip. [Where W(a) is shorthand for PhasedX(phase_exponent=a).] Uses the following identity: ───W(a)───Z^t─── ≡ ───W(a)────...
Grabs or cancels a held W gate against an existing W gate.
def _potential_cross_whole_w(moment_index: int, op: ops.Operation, tolerance: float, state: _OptimizerState) -> None: """Grabs or cancels a held W gate against an existing W gate. [Where W(a) is shorthand for PhasedX(phase_e...
Cross the held W over a partial W gate.
def _potential_cross_partial_w(moment_index: int, op: ops.Operation, state: _OptimizerState) -> None: """Cross the held W over a partial W gate. [Where W(a) is shorthand for PhasedX(phase_exponent=a).] Uses the following identity: ───W(...
Crosses exactly one W flip over a partial CZ.
def _single_cross_over_cz(moment_index: int, op: ops.Operation, qubit_with_w: ops.Qid, state: _OptimizerState) -> None: """Crosses exactly one W flip over a partial CZ. [Where W(a) is shorthand for PhasedX(phase_exponent=a).] Us...
Crosses two W flips over a partial CZ.
def _double_cross_over_cz(op: ops.Operation, state: _OptimizerState) -> None: """Crosses two W flips over a partial CZ. [Where W(a) is shorthand for PhasedX(phase_exponent=a).] Uses the following identity: ───W(a)───@───── │ ───W(b)───@^t─── ...
Validates that a probability is between 0 and 1 inclusively.
def validate_probability(p: float, p_str: str) -> float: """Validates that a probability is between 0 and 1 inclusively. Args: p: The value to validate. p_str: What to call the probability in error messages. Returns: The probability p if the probability if valid. Raises: ...
Returns a phased version of the effect.
def phase_by(val: Any, phase_turns: float, qubit_index: int, default: TDefault = RaiseTypeErrorIfNotProvided): """Returns a phased version of the effect. For example, an X gate phased by 90 degrees would be a Y gate. This works by calling `val`'s _phase_by_ method and returning the result....
Returns a list of operations apply this gate to each of the targets.
def on_each(self, *targets: raw_types.Qid) -> op_tree.OP_TREE: """Returns a list of operations apply this gate to each of the targets. Args: *targets: The qubits to apply this gate to. Returns: Operations applying this gate to the target qubits. Raises: ...
Returns an Engine instance configured using environment variables.
def engine_from_environment() -> Engine: """Returns an Engine instance configured using environment variables. If the environment variables are set, but incorrect, an authentication failure will occur when attempting to run jobs on the engine. Required Environment Variables: QUANTUM_ENGINE_PRO...
Plot the state histogram from a single result with repetitions.
def plot_state_histogram(result: trial_result.TrialResult) -> np.ndarray: """Plot the state histogram from a single result with repetitions. States is a bitstring representation of all the qubit states in a single result. Currently this function assumes each measurement gate applies to only a singl...
Converts sweep into an equivalent protobuf representation.
def sweep_to_proto_dict(sweep: Sweep, repetitions: int=1) -> Dict: """Converts sweep into an equivalent protobuf representation.""" msg = {} # type: Dict if not sweep == UnitSweep: sweep = _to_zip_product(sweep) msg['sweep'] = { 'factors': [_sweep_zip_to_proto_dict(cast(Zip, fac...
Converts sweep to a product of zips of single sweeps if possible.
def _to_zip_product(sweep: Sweep) -> Product: """Converts sweep to a product of zips of single sweeps, if possible.""" if not isinstance(sweep, Product): sweep = Product(sweep) if not all(isinstance(f, Zip) for f in sweep.factors): factors = [f if isinstance(f, Zip) else Zip(f) for f in swee...
Implementation of SupportsApproximateEquality protocol.
def _approx_eq_(self, other: Any, atol: float) -> bool: """Implementation of `SupportsApproximateEquality` protocol.""" if not isinstance(other, type(self)): return NotImplemented #self.value = value % period in __init__() creates a Mod if isinstance(other.value, sympy.Mod):...
Removes redundant acquaintance opportunities.
def remove_redundant_acquaintance_opportunities( strategy: circuits.Circuit) -> int: """Removes redundant acquaintance opportunities.""" if not is_acquaintance_strategy(strategy): raise TypeError('not is_acquaintance_strategy(circuit)') qubits = sorted(strategy.all_qubits()) mapping = {...
Runs the supplied Circuit or Schedule mimicking quantum hardware.
def run_sweep( self, program: Union[circuits.Circuit, schedules.Schedule], params: study.Sweepable, repetitions: int = 1, ) -> List[study.TrialResult]: """Runs the supplied Circuit or Schedule, mimicking quantum hardware. In contrast to run, this allows for sweeping ...
Run a simulation mimicking quantum hardware.
def _run( self, circuit: circuits.Circuit, param_resolver: study.ParamResolver, repetitions: int ) -> Dict[str, np.ndarray]: """Run a simulation, mimicking quantum hardware. Args: circuit: The circuit to simulate. param_resolver: Parameters to...
Computes SamplesDisplays in the supplied Circuit or Schedule.
def compute_samples_displays( self, program: Union[circuits.Circuit, schedules.Schedule], param_resolver: 'study.ParamResolverOrSimilarType' = None, ) -> study.ComputeDisplaysResult: """Computes SamplesDisplays in the supplied Circuit or Schedule. Args: ...
Computes SamplesDisplays in the supplied Circuit or Schedule.
def compute_samples_displays_sweep( self, program: Union[circuits.Circuit, schedules.Schedule], params: Optional[study.Sweepable] = None ) -> List[study.ComputeDisplaysResult]: """Computes SamplesDisplays in the supplied Circuit or Schedule. In contrast to `compu...
Simulates the supplied Circuit or Schedule.
def simulate( self, program: Union[circuits.Circuit, schedules.Schedule], param_resolver: 'study.ParamResolverOrSimilarType' = None, qubit_order: ops.QubitOrderOrList = ops.QubitOrder.DEFAULT, initial_state: Any = None, ) -> 'SimulationTrialResult': """Simulates the s...
Simulates the supplied Circuit or Schedule.
def simulate_sweep( self, program: Union[circuits.Circuit, schedules.Schedule], params: study.Sweepable, qubit_order: ops.QubitOrderOrList = ops.QubitOrder.DEFAULT, initial_state: Any = None, ) -> List['SimulationTrialResult']: """Simulates the supplied Circuit or Sch...
Simulates the supplied Circuit or Schedule.
def simulate_sweep( self, program: Union[circuits.Circuit, schedules.Schedule], params: study.Sweepable, qubit_order: ops.QubitOrderOrList = ops.QubitOrder.DEFAULT, initial_state: Any = None, ) -> List['SimulationTrialResult']: """Simulates the supplied Circuit or Sch...
Returns an iterator of StepResults for each moment simulated.
def simulate_moment_steps( self, circuit: circuits.Circuit, param_resolver: 'study.ParamResolverOrSimilarType' = None, qubit_order: ops.QubitOrderOrList = ops.QubitOrder.DEFAULT, initial_state: Any = None ) -> Iterator: """Returns an iterator of StepResults for each m...
Iterator over StepResult from Moments of a Circuit.
def _simulator_iterator( self, circuit: circuits.Circuit, param_resolver: study.ParamResolver, qubit_order: ops.QubitOrderOrList, initial_state: Any, ) -> Iterator: """Iterator over StepResult from Moments of a Circuit. Args: circuit: The circuit ...
This method can be overridden to creation of a trial result.
def _create_simulator_trial_result(self, params: study.ParamResolver, measurements: Dict[str, np.ndarray], final_simulator_state: Any) \ -> 'SimulationTrialResult': """This method can be overridden to creation of a trial result. Args: params: The ParamResolve...
Samples from the system at this point in the computation.
def sample(self, qubits: List[ops.Qid], repetitions: int = 1) -> np.ndarray: """Samples from the system at this point in the computation. Note that this does not collapse the wave function. Args: qubits: The qubits to be sampled in an order that influe...
Samples from the system at this point in the computation.
def sample_measurement_ops( self, measurement_ops: List[ops.GateOperation], repetitions: int = 1) -> Dict[str, np.ndarray]: """Samples from the system at this point in the computation. Note that this does not collapse the wave function. In contrast to `sampl...
Decomposition ignores connectivity.
def xor_nonlocal_decompose(qubits: Iterable[raw_types.Qid], onto_qubit: raw_types.Qid ) -> Iterable[raw_types.Operation]: """Decomposition ignores connectivity.""" for qubit in qubits: if qubit != onto_qubit: yield common_gates.CNOT(qubit,...
Overrides sympy and numpy returning repr strings that don t parse.
def proper_repr(value: Any) -> str: """Overrides sympy and numpy returning repr strings that don't parse.""" if isinstance(value, sympy.Basic): result = sympy.srepr(value) # HACK: work around https://github.com/sympy/sympy/issues/16074 # (only handles a few cases) fixed_tokens ...