qml.kernels.square_kernel_matrix

square_kernel_matrix(X, kernel, assume_normalized_kernel=False)[source]

Computes the square matrix of pairwise kernel values for a given dataset.

Parameters
  • X (list[datapoint]) – List of datapoints

  • kernel ((datapoint, datapoint) -> float) – Kernel function that maps datapoints to kernel value.

  • assume_normalized_kernel (bool, optional) – Assume that the kernel is normalized, in which case the diagonal of the kernel matrix is set to 1, avoiding unnecessary computations.

Returns

The square matrix of kernel values.

Return type

array[float]

Example:

Consider a simple kernel function based on AngleEmbedding:

dev = qml.device('default.qubit', wires=2)
@qml.qnode(dev)
def circuit(x1, x2):
    qml.templates.AngleEmbedding(x1, wires=dev.wires)
    qml.adjoint(qml.templates.AngleEmbedding)(x2, wires=dev.wires)
    return qml.probs(wires=dev.wires)

kernel = lambda x1, x2: circuit(x1, x2)[0]

We can then compute the kernel matrix on a set of 4 (random) feature vectors X via

>>> X = np.random.random((4, 2))
>>> qml.kernels.square_kernel_matrix(X, kernel)
tensor([[1.        , 0.9532702 , 0.96864001, 0.90932897],
        [0.9532702 , 1.        , 0.99727485, 0.95685561],
        [0.96864001, 0.99727485, 1.        , 0.96605621],
        [0.90932897, 0.95685561, 0.96605621, 1.        ]], requires_grad=True)