I have a QNN script working with a 3rd party optimiser but when I try to use PLs inbuilt optimisers, it fails for various reasons.
I have created a small script to try and debug the problem. Please see code below which fails for a different reason to being with.
Thanks for your help.
import pennylane as qml
from pennylane import numpy as np
from sklearn.metrics import mean_squared_error, accuracy_score
n_qubits = 2
n_samples = 5
n_params = 2
n_features = 2 #features per sample
epochs = 5
np.random.seed(11)
dev = qml.device("default.qubit", wires= n_qubits)
@qml.qnode(dev)
def circuit(data: np.ndarray, params: np.ndarray) -> float:
qml.RX(data[0], 0)
qml.RY(data[1], 1)
qml.RX(params[0], 0)
qml.RY(params[1], 1)
qml.CZ((0, 1))
return qml.expval(qml.PauliZ(1))
cap = dev.capabilities()
cap["supports_broadcasting"]
def qnn(data, params):
return circuit(data, params)
def cost_acc(params, data, y):
exp_vals = qnn(data, params)
cost = mean_squared_error(y, exp_vals)
yhat = 2*(exp_vals >=0) -1
return cost, accuracy_score(y, yhat, normalize=True)
x = np.random.rand(n_features, n_samples)
y = np.random.choice([-1, 1], size=n_samples)
weights = np.random.rand(n_params, requires_grad = True)
optimizer = qml.GradientDescentOptimizer(stepsize=0.1)
for k in range(epochs):
optimizer.step(cost_acc, params = weights, data = x, y = y)
/local/zchandani/pennylane/qnns/lib/python3.8/site-packages/pennylane/_grad.py:107: UserWarning: Attempted to differentiate a function with no trainable parameters. If this is unintended, please add trainable parameters via the 'requires_grad' attribute or 'argnum' keyword.
warnings.warn(