Operator must be unitary

I was going to run your example about quantum kernel, but i encountered this error: "ValueError: Operator must be unitary".

@qml.qnode(dev_kernel)
def kernel(x1, x2):
    """The quantum kernel."""
    AngleEmbedding(x1, wires=range(n_qubits))
    qml.inv(AngleEmbedding(x2, wires=range(n_qubits)))
    return qml.expval(qml.Hermitian(projector, wires=range(n_qubits)))

print(kernel(X_train[0], X_train[0]))

Hi @sassan_moradi!

What is your projector variable in this case?

Here is projector variable:
projector = np.zeros((pow(2,n_qubits), pow(2,n_qubits)))
projector[0, 0] = 1

Hi @sassan_moradi,

Perhaps you could share a complete (non-)working example of your code? I ran your code above (with some guesses about missing lines) and was not able to reproduce the error (it gave an output without error).

The code is one of pennylane examples:

import numpy as np

from sklearn.svm import SVC
from sklearn.datasets import load_iris
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score

import pennylane as qml
from pennylane.templates import AngleEmbedding


X, y = load_iris(return_X_y=True) 


X = X[:100]
y = y[:100]


scaler = StandardScaler().fit(X)
X_scaled = scaler.transform(X)


y_scaled = 2 * (y - 0.5)

X_train, X_test, y_train, y_test = train_test_split(X_scaled, y_scaled)


######################################################################
# We use the `angle-embedding
# template <https://pennylane.readthedocs.io/en/stable/code/api/pennylane.templates.embeddings.AngleEmbedding.html>`__
# which needs as many qubits as there are features:
#

n_qubits = len(X_train[0])

dev_kernel = qml.device("default.qubit", wires=n_qubits)

projector = np.zeros((2**n_qubits, 2**n_qubits))
projector[0, 0] = 1

@qml.qnode(dev_kernel)
def kernel(x1, x2):
    """The quantum kernel."""
    AngleEmbedding(x1, wires=range(n_qubits))
    qml.inv(AngleEmbedding(x2, wires=range(n_qubits)))
    return qml.expval(qml.Hermitian(projector, wires=range(n_qubits)))

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)


######################################################################
# Let’s compute the accuracy on the test set.
#

predictions = svm.predict(X_test)

problem solved. After upgrading pennylane, i could run it without error.

Glad you got it working @sassan_moradi :slight_smile: