1
$\begingroup$

I have a problem with my code. I would like to try multiple embeddings in my kernel (I'm using the adjoint method). My idea is to pass them to the function and use them depending on what I pass. Unfortunately, it doesn't work as I think, or I can't program it. Help would be nice :)

Code:


from pennylane.templates import SqueezingEmbedding,QAOAEmbedding,IQPEmbedding,DisplacementEmbedding,AngleEmbedding, StronglyEntanglingLayers,BasisEmbedding,AmplitudeEmbedding,DisplacementEmbedding

def kernel_matrix(A, B):
    """Compute the matrix whose entries are the kernel
       evaluated on pairwise data from sets A and B."""
    
    kernel = np.array([[kernel(a, b) for b in B] for a in A]) #how can I pass on the method?
    return kernel


def Quantum_Kernel_pennylane(train_X, test_X, train_y, test_y, method):
   
    n_qubits = len(train_X[0])
    
    dev_kernel = qml.device('lightning.qubit', wires=n_qubits)
        
    projector = np.zeros((2**n_qubits, 2**n_qubits))
    projector[0, 0] = 1

    @qml.qnode(dev_kernel, interface="autograd")
    def kernel(x1, x2):
        """The quantum kernel.
           We use the adjoint method.
        """ 
        if method == qml.templates.embeddings.AmplitudeEmbedding:
            method(x1, wires=range(n_qubits), pad_with=0.4)  
            qml.adjoint(method)(x2, wires=range(n_qubits), pad_with=0.4)   
            return qml.expval(qml.Hermitian(projector, wires=range(n_qubits)))
        
        method(x1, wires=range(n_qubits))
        qml.adjoint(method)(x2, wires=range(n_qubits))   
        return qml.expval(qml.Hermitian(projector, wires=range(n_qubits)))
    
    svm = SVC(kernel=kernel_matrix).fit(train_X, train_y) # here is the problem how can I pass on the method?
    predictions = svm.predict(test_X)
    print(accuracy_score(predictions, test_y))





def main():
 methods = [IQPEmbedding,
           AngleEmbedding,
           AmplitudeEmbedding
          ]

 for method in methods:
    print(method)
    Quantum_Kernel_pennylane(train_X, test_X, train_y, test_y, method)# I want to pass on the Method
$\endgroup$
1
  • $\begingroup$ I'm not sure this is a question about PennyLane, really? As you want the contents within the Quantum_Kernel_pennylane function to take the method into account when computing the kernel matrix, maybe you can define kernel_matrix in there? Maybe it can be useful to look at the PennyLane qml.kernels module, where helper functions for kernel matrices etc are defined already? There also are associated code examples. $\endgroup$ Nov 25, 2023 at 19:07

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.