Hello! I am trying to create a QCNN defined with pennylane to classify quantum states. However, I have some problems during the training: I have never really had to do with ML, so I would like some advice. In fact, during the training phase my loss and accuracy are constant.
I have already checked that my quantum circuit does depend on the parameters.
I am sharing with you the code about it. I am not sure that the code about data generation and the qcnn can be helpful here, so I am not posting them.
x_train = np.array(x_train, requires_grad=False)
y_train = np.array(y_train, requires_grad=False)
# Initialize the parameters
np.random.seed(42)
params = np.random.rand(40, requires_grad=True)
iterations = 50
# Cost function
def cost(parameters, x, y):
predictions = [np.sign(qcnn(parameters, xi)) for xi in x]
return np.mean((predictions - y) ** 2)
# Accuracy
def accuracy(labels, predictions):
loss = 0
for l, p in zip(labels, predictions):
if abs(l - p) < 1e-5:
loss = loss + 1
loss = loss / len(labels)
return loss
# Parameters optimization
opt = qml.NesterovMomentumOptimizer(0.5)
for epoch in tqdm(range(iterations)):
params, _, _ = opt.step(cost, params, x_train, y_train)
if epoch % 10 == 0:
# Compute accuracy
predictions = [np.sign(qcnn(params, xi)) for xi in x_train]
acc = accuracy(y_train, predictions)
# Compute loss
loss = cost(params, x_train, y_train)
print(f"Epoch {epoch}, Loss: {loss}, Accuracy: {acc}")
I don’t have any error. But the code prints out:
2%|▏ | 1/50 [00:02<02:03, 2.53s/it]
Epoch 0, Loss: 2.6666666666666665, Accuracy: 0.3333333333333333
22%|██▏ | 11/50 [00:10<00:41, 1.06s/it]
Epoch 10, Loss: 2.6666666666666665, Accuracy: 0.3333333333333333
42%|████▏ | 21/50 [00:18<00:27, 1.04it/s]
Epoch 20, Loss: 2.6666666666666665, Accuracy: 0.3333333333333333
62%|██████▏ | 31/50 [00:26<00:19, 1.00s/it]
Epoch 30, Loss: 2.6666666666666665, Accuracy: 0.3333333333333333
82%|████████▏ | 41/50 [00:34<00:09, 1.02s/it]
Epoch 40, Loss: 2.6666666666666665, Accuracy: 0.3333333333333333
100%|██████████| 50/50 [00:41<00:00, 1.21it/s]
Thank you.