SVC usage in quantum circuits

Hi everyone, I really donot understand how this line svm = SVC(kernel= kernel_matrix).fit(X_train, y_train) exactly works in the below code? I donot understand how this line executes? How exactly kernel_marix function is called? Please explain me these things if possible.

@qml.qnode(dev_kernel, interface = "autograd")
def kernel(x1, x2):
    AngleEmbedding(x1, wires= range(n_qubits))
    qml.adjoint(AngleEmbedding)(x2, wires= range(n_qubits))
    return qml.expval(qml.Hermitian(projector, wires= range(n_qubits)))

# A good Sanity check is whether evaluating the kernel of a data point and itself returns 1:
print(kernel(X_train[0], X_train[0]))

def kernel_matrix(A, B):
    '''Compute the matrix whose entries are the kernel evaluated on pairwise data from sets A and B.'''
    return np.array([[kernel(a,b) for b in B] for a in A])


svm = SVC(kernel= kernel_matrix).fit(X_train, y_train)

I tried editing the last line as below:


matrix = kernel_matrix(X_train, X_train)

svm = SVC(kernel = matrix).fit(X_train, y_train)

This replacement gives error. I am not sure why?

Hi @Manu_Chaudhary,

Great question. svm = SVC(kernel= kernel_matrix).fit(X_train, y_train) is doing two things. First it’s creating a support vector classifier (a model) using SVC, and then it’s fitting this model to the data (X_train, y_train) using fit. This allows the model to make good predictions for your specific data.

Notice that SVC is part of a package external to PennyLane, which is sklearn. You can learn more about Support Vector Classification (SVC) in the sklearn documentation.

As you can see there, the kernel that you input to SVC must be {‘linear’, ‘poly’, ‘rbf’, ‘sigmoid’, ‘precomputed’} or callable. However when you make the above change your matrix is an array, which is not callable. This is why you’re getting an error. My recommendation would be to keep this part of the code as it is.

Is there a reason why you wanted to make the above change?

By the way, we have a new PennyLane survey. Let us know your thoughts about PennyLane in order to keep bringing you amazing features :sparkles:.

Thank you @CatalinaAlbornoz for the response. I want to make those changes to understand the quantum support vector machines and the pennylane APIs properly. I’m relatively new to Pennylane, but I believe it’s an excellent framework for conducting research in the field of quantum computing.

2 Likes

Thank you very much for your kind words @Manu_Chaudhary !

If you would like to learn more about PennyLane and quantum computing I would recommend the Xanadu Quantum Codebook. It’s an amazing resource to learn the theory and practice side by side.

Thank you @CatalinaAlbornoz for the great help.

1 Like

I’m glad I could help @Manu_Chaudhary !

Enjoy using PennyLane!