# tfp.math.psd_kernels.AutoCompositeTensorPsdKernel

Stay organized with collections Save and categorize content based on your preferences.

Abstract base class for positive semi-definite kernel functions.

#### Background

For any set `S`, a real- (or complex-valued) function `k` on the Cartesian product `S x S` is called positive semi-definite if we have

``````sum_i sum_j (c[i]*) c[j] k(x[i], x[j]) >= 0
``````

for any finite collections `{x[1], ..., x[N]}` in S and `{c[1], ..., c[N]}` in the reals (or the complex plane). '*' denotes the complex conjugate, in the complex case.

• `S` is R, and `k(s, t) = (s - a) (t - b)`, where a, b are in R. This corresponds to a linear kernel.
• `S` is R^+ U {0}, and `k(s, t) = min(s, t)`. This corresponds to a kernel for a Wiener process.
• `S` is the set of strings over an alphabet `A = {c1, ... cC}`, and `k(s, t)` is defined via some similarity metric over strings.

We model positive semi-definite functions (kernels, in common machine learning parlance) as classes with 3 primary public methods: `apply`, `matrix`, and `tensor`.

`apply` computes the value of the kernel function at a pair of (batches of) input locations. It is the more "low-level" operation: `matrix` and `tensor` are implemented in terms of `apply`.

`matrix` computes the value of the kernel pairwise on two (batches of) lists of input examples. When the two collections are the same the result is called the Gram (or Gramian) matrix (https://en.wikipedia.org/wiki/Gramian_matrix).

`tensor` generalizes `matrix`, taking rank `k1` and `k2` collections of input examples to a rank `k1 + k2` collection of kernel values.

#### Kernel Parameter Shape Semantics

PositiveSemidefiniteKernel implementations support batching of kernel parameters and broadcasting of these parameters across batches of inputs. This allows, for example, creating a single kernel object which acts like a collection of kernels with different parameters. This might be useful for, e.g., for exploring multiple random initializations in parallel during a kernel parameter optimization procedure.

The interaction between kernel parameter shapes and input shapes (see below) is somewhat subtle. The semantics are designed to make the most common use cases easy, while not ruling out more intricate control. The overarching principle is that kernel parameter batch shapes must be broadcastable with input batch shapes (see below). Examples are provided in the method-level documentation.

#### Input Shape Semantics

PositiveSemidefiniteKernel methods each support a notion of batching inputs; see the method-level documentation for full details; here we describe the overall semantics of input shapes. Inputs to PositiveSemidefiniteKernel methods partition into 3 pieces:

``````[b1, ..., bB, e1, ..., eE, f1, ..., fF]
'----------'  '---------'  '---------'
|             |            '-- Feature dimensions
|             '-- Example dimensions
'-- Batch dimensions
``````
• Feature dimensions correspond to the space over which the kernel is defined; in typical applications inputs are vectors and this part of the shape is rank-1. For example, if our kernel is defined over R^2 x R^2, each input is a 2-D vector (a rank-1 tensor of shape `[2,]`) so that `F = 1, [f1, ..., fF] = [2]`. If we defined a kernel over DxD matrices, its domain would be R^(DxD) x R^(DxD), we would have `F = 2` and `[f1, ..., fF] = [D, D]`. Feature shapes of inputs should be the same, but no exception will be raised unless they are broadcast-incompatible.
• Batch dimensions describe collections of inputs which in some sense have nothing to do with each other, but may be coupled to batches of kernel parameters. It's required that batch dimensions of inputs broadcast with each other, and with the kernel's overall batch shape.
• Example dimensions are shape elements which represent a collection of inputs that in some sense "go together" (whereas batches are "independent"). The exact semantics are different for the `apply`, `matrix` and `tensor` methods (see method-level doc strings for more details). `apply` combines examples together pairwise, much like the python built-in `zip`. `matrix` combines examples pairwise for all pairs of elements from two rank-1 input collections (lists), ie, it applies the kernel to all elements in the cross-product of two lists of examples. `tensor` further generalizes `matrix` to higher rank collections of inputs. Only `matrix` strictly requires example dimensions to be present (and to be exactly rank 1), although the typical usage of `apply` (eg, building a matrix diagonal) will also have `example_ndims` 1.

Inputs may also be nested structures, in which case the batch and example dimensions of all elements must broadcast. The number of feature dimensions of each element must be equal to the corresponding element of the `feature_ndims` structure.

##### Examples
``````  import tensorflow_probability as tfp

# Suppose `SomeKernel` acts on vectors (rank-1 tensors), ie number of
# feature dimensions is 1.
scalar_kernel = tfp.math.psd_kernels.SomeKernel(param=.5)
scalar_kernel.batch_shape
# ==> []

# `x` and `y` are batches of five 3-D vectors:
x = np.ones([5, 3], np.float32)
y = np.ones([5, 3], np.float32)
scalar_kernel.apply(x, y).shape
# ==> [5]

scalar_kernel.matrix(x, y).shape
# ==> [5, 5]
``````

Now we can consider a kernel with batched parameters:

``````  batch_kernel = tfp.math.psd_kernels.SomeKernel(param=[.2, .5])
batch_kernel.batch_shape
# ==> [2]

# `x` and `y` are batches of five 3-D vectors:
x = np.ones([5, 3], np.float32)
y = np.ones([5, 3], np.float32)

batch_kernel.apply(x, y).shape
# ==> Error! [2] and [5] can't broadcast.
# We could solve this by telling `apply` to treat the 5 as an example dim:

batch_kernel.apply(x, y, example_ndims=1).shape
# ==> [2, 5]

# Note that example_ndims is implicitly 1 for a call to `matrix`, so the
# following just works:
batch_kernel.matrix(x, y).shape
# ==> [2, 5, 5]
``````

`feature_ndims` Python `integer`, or nested structure of integers, indicating the number of dims (the rank) of the feature space this kernel acts on.
`dtype` `DType` on which this kernel operates. Must have the same nested structure as `feature_ndims`.
`name` Python `str` name prefixed to Ops created by this class. Default: subclass name.
`validate_args` Python `bool`, default `False`. When `True` kernel parameters are checked for validity despite possibly degrading runtime performance. When `False` invalid inputs may silently render incorrect outputs.
`parameters` Python `dict` of constructor arguments.

`ValueError` if `feature_ndims` (or any element, if nested) is not an integer greater than 0.

`batch_shape` Shape of a single sample from a single event index as a `TensorShape`.

May be partially defined or unknown.

The batch dimensions are indexes into independent, non-identical parameterizations of this `PositiveSemidefiniteKernel`.

`dtype` (Nested) dype over which the kernel operates.
`feature_ndims` The number of feature dimensions.

Kernel functions generally act on pairs of inputs from some space like

``````R^(d1 x ... x dD)
``````

or, in words: rank-`D` real-valued tensors of shape `[d1, ..., dD]`. Inputs can be vectors in some `R^N`, but are not restricted to be. Indeed, one might consider kernels over matrices, tensors, or even more general spaces, like strings or graphs. Inputs may also be nested structures, in which case `feature_ndims` is a parallel nested structure containing the feature rank of each component.

`name` Name prepended to all ops created by this class.
`name_scope` Returns a `tf.name_scope` instance for this class.
`non_trainable_variables` Sequence of non-trainable variables owned by this module and its submodules.

`parameters` Dictionary of parameters used to instantiate this `PSDKernel`.
`submodules` Sequence of all sub-modules.

Submodules are modules which are properties of this module, or found as properties of modules which are properties of this module (and so on).

````a = tf.Module()`
`b = tf.Module()`
`c = tf.Module()`
`a.b = b`
`b.c = c`
`list(a.submodules) == [b, c]`
`True`
`list(b.submodules) == [c]`
`True`
`list(c.submodules) == []`
`True`
```

`trainable_variables` Sequence of trainable variables owned by this module and its submodules.

`validate_args` Python `bool` indicating possibly expensive checks are enabled.
`variables` Sequence of variables owned by this module and its submodules.

## Methods

### `apply`

View source

Apply the kernel function pairs of inputs.

Args
`x1` (Nested) `Tensor` input to the kernel, of shape `B1 + E1 + F`, where `B1` and `E1` may be empty (ie, no batch/example dims, resp.). If nested, `B1` and `E1` must broadcast across elements of the structure. `F` (the feature shape) must have rank equal to the kernel's `feature_ndims` property, or to the corresponding element of the `feature_ndims` nested structure. Batch shape must broadcast with the batch shape of `x2` and with the kernel's batch shape. Example shape must broadcast with example shape of `x2`. `x1` and `x2` must have the same number of example dims (ie, same rank).
`x2` (Nested) `Tensor` input to the kernel, of shape `B2 + E2 + F`, where `B2` and `E2` may be empty (ie, no batch/example dims, resp.). If nested, `B1` and `E1` must broadcast across elements of the structure. `F` (the feature shape) must have rank equal to the kernel's `feature_ndims` property, or to the corresponding element of the `feature_ndims` nested structure. Batch shape must broadcast with the batch shape of `x2` and with the kernel's batch shape. Example shape must broadcast with example shape of `x2`. `x1` and `x2` must have the same number of example dims (ie, same rank).
`example_ndims` A python integer, the number of example dims in the inputs. In essence, this parameter controls how broadcasting of the kernel's batch shape with input batch shapes works. The kernel batch shape will be broadcast against everything to the left of the combined example and feature dimensions in the input shapes.
`name` name to give to the op

Returns
`Tensor` containing the results of applying the kernel function to inputs `x1` and `x2`. If the kernel parameters' batch shape is `Bk` then the shape of the `Tensor` resulting from this method call is `broadcast(Bk, B1, B2) + broadcast(E1, E2)`.

Given an index set `S`, a kernel function is mathematically defined as a real- or complex-valued function on `S` satisfying the positive semi-definiteness constraint:

``````sum_i sum_j (c[i]*) c[j] k(x[i], x[j]) >= 0
``````

for any finite collections `{x[1], ..., x[N]}` in `S` and `{c[1], ..., c[N]}` in the reals (or the complex plane). '*' is the complex conjugate, in the complex case.

This method most closely resembles the function described in the mathematical definition of a kernel. Given a PositiveSemidefiniteKernel `k` with scalar parameters and inputs `x` and `y` in `S`, `apply(x, y)` yields a single scalar value.

#### Examples

``````import tensorflow_probability as tfp

# Suppose `SomeKernel` acts on vectors (rank-1 tensors)
scalar_kernel = tfp.math.psd_kernels.SomeKernel(param=.5)
scalar_kernel.batch_shape
# ==> []

# `x` and `y` are batches of five 3-D vectors:
x = np.ones([5, 3], np.float32)
y = np.ones([5, 3], np.float32)
scalar_kernel.apply(x, y).shape
# ==> [5]
``````

The above output is the result of vectorized computation of the five values

``````[k(x[0], y[0]), k(x[1], y[1]), ..., k(x[4], y[4])]
``````

Now we can consider a kernel with batched parameters:

``````batch_kernel = tfp.math.psd_kernels.SomeKernel(param=[.2, .5])
batch_kernel.batch_shape
# ==> [2]
batch_kernel.apply(x, y).shape
# ==> Error! [2] and [5] can't broadcast.
``````

The parameter batch shape of `[2]` and the input batch shape of `[5]` can't be broadcast together. We can fix this in either of two ways:

##### Fix #1

Give the parameter a shape of `[2, 1]` which will correctly broadcast with `[5]` to yield `[2, 5]`:

``````batch_kernel = tfp.math.psd_kernels.SomeKernel(
param=[[.2], [.5]])
batch_kernel.batch_shape
# ==> [2, 1]
batch_kernel.apply(x, y).shape
# ==> [2, 5]
``````
##### Fix #2

By specifying `example_ndims`, which tells the kernel to treat the `5` in the input shape as part of the "example shape", and "pushing" the kernel batch shape to the left:

``````batch_kernel = tfp.math.psd_kernels.SomeKernel(param=[.2, .5])
batch_kernel.batch_shape
# ==> [2]
batch_kernel.apply(x, y, example_ndims=1).shape
# ==> [2, 5]
``````

### `batch_shape_tensor`

View source

Shape of a single sample from a single event index as a 1-D `Tensor`.

The batch dimensions are indexes into independent, non-identical parameterizations of this `PositiveSemidefiniteKernel`.

Args
`name` name to give to the op

Returns
`batch_shape` `Tensor`.

### `copy`

View source

Creates a copy of the kernel.

Args
`**override_parameters_kwargs` String/value dictionary of initialization arguments to override with new values.

Returns
`copied_kernel` A new instance of `type(self)` initialized from the union of self.parameters and override_parameters_kwargs, i.e., `dict(self.parameters, **override_parameters_kwargs)`.

### `matrix`

View source

Construct (batched) matrices from (batches of) collections of inputs.

Args
`x1` (Nested) `Tensor` input to the first positional parameter of the kernel, of shape `B1 + [e1] + F`, where `B1` may be empty (ie, no batch dims, resp.), `e1` is a single integer (ie, `x1` has example ndims exactly 1), and `F` (the feature shape) must have rank equal to the kernel's `feature_ndims` property (or to the corresponding element of `feature_ndims`, if nested). Batch shape must broadcast with the batch shape of `x2` and with the kernel's batch shape.
`x2` (Nested) `Tensor` input to the second positional parameter of the kernel, shape `B2 + [e2] + F`, where `B2` may be empty (ie, no batch dims, resp.), `e2` is a single integer (ie, `x2` has example ndims exactly 1), and `F` (the feature shape) must have rank equal to the kernel's `feature_ndims` property (or to the corresponding element of `feature_ndims`, if nested). Batch shape must broadcast with the batch shape of `x1` and with the kernel's batch shape.
`name` name to give to the op

Returns
`Tensor` containing the matrix (possibly batched) of kernel applications to pairs from inputs `x1` and `x2`. If the kernel parameters' batch shape is `Bk` then the shape of the `Tensor` resulting from this method call is `broadcast(Bk, B1, B2) + [e1, e2]` (note this differs from