Qml.kernels.closest_psd_matrix

Hi everyone, I am trying to understand the documentation of qml.kernels.
I am currently trying to understand what exactly closest_psd_matrix function do what is its exact use? For example, I tried creating a small example reading your documentation:

import numpy as np

K = np.array([[7, 3],[3, -1]])
eigen_values = np.linalg.eigvalsh(K)
import pennylane as qml
K_psd = qml.kernels.closest_psd_matrix(K)   # not sure what exactly this line doing?

Result: 
tensor([[7.2, 2.4],
        [2.4, 0.8]], requires_grad=True)
K_psd = qml.kernels.closest_psd_matrix(K, fix_diagonal=True)
K_psd

Also, when I tried running above lines from the documentation, I am getting the error as below:

---------------------------------------------------------------------------
ModuleNotFoundError                       Traceback (most recent call last)
File ~/anaconda3/envs/pennylane_study/lib/python3.11/site-packages/pennylane/kernels/postprocessing.py:221, in closest_psd_matrix(K, fix_diagonal, solver, **kwargs)
    220 try:
--> 221     import cvxpy as cp  # pylint: disable=import-outside-toplevel
    223     if solver is None:

ModuleNotFoundError: No module named 'cvxpy'

The above exception was the direct cause of the following exception:

ImportError                               Traceback (most recent call last)
Cell In[14], line 2
      1 # However, for quantum kernel matrices, we may want to restore the value 1 on the diagonal
----> 2 K_psd = qml.kernels.closest_psd_matrix(K, fix_diagonal=True)
      3 K_psd

File ~/anaconda3/envs/pennylane_study/lib/python3.11/site-packages/pennylane/kernels/postprocessing.py:226, in closest_psd_matrix(K, fix_diagonal, solver, **kwargs)
    224         solver = cp.CVXOPT
    225 except ImportError as e:
--> 226     raise ImportError("CVXPY is required for this post-processing method.") from e
    228 X = cp.Variable(K.shape, PSD=True)
    229 constraint = [cp.diag(X) == 1.0] if fix_diagonal else []

ImportError: CVXPY is required for this post-processing method.

Thank you.

Hey @Manu_Chaudhary , there are a couple of different things going on here. :slight_smile:

First, if you’re using fix_diagonal=True, you should have cvxpy installed (pip install cvxpy) — you can see the comments on that in the docs page of qml.kernels.closest_psd_matrix.

And second, finding the closest semi-definite matrix to the kernel matrix is part of the method described in this paper: [2105.02276] Training Quantum Embedding Kernels on Near-Term Quantum Computers
Depending on how deep you want to dive into this topic, you could instead look at the very short description here, and see if that helps: qml.kernels — PennyLane 0.31.1 documentation

I hope that’s already useful to you! :smiley:

Thank you @Ivana_at_Xanadu for the great help. I will study all the links provided by you thoroughly.