qml.kernels.kernel_matrix¶
- kernel_matrix(X1, X2, kernel)[source]¶
Computes the matrix of pairwise kernel values for two given datasets.
- Parameters:
X1 (list[datapoint]) – List of datapoints (first argument)
X2 (list[datapoint]) – List of datapoints (second argument)
kernel ((datapoint, datapoint) -> float) – Kernel function that maps datapoints to kernel value.
- Returns:
The 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]
With this method we can systematically evaluate the kernel function
kernelon pairs of datapoints, where the points stem from different datasets, like a training and a test dataset.>>> rng = np.random.default_rng(seed=1234) >>> X_train = rng.random((4,2)) >>> X_test = rng.random((3,2)) >>> qml.kernels.kernel_matrix(X_train, X_test, kernel) array([[0.99656842, 0.91774724, 0.93966202], [0.99958227, 0.91468777, 0.91127346], [0.89479886, 0.937256 , 0.80459952], [0.87448042, 0.96924743, 0.84069076]])
As we can see, for \(n\) and \(m\) datapoints in the first and second dataset respectively, the output matrix has the shape \(n\times m\).