An error occurred replacing NesterovMomentumOptimizer with QNGOptimizer. How do I do this?

@qml.qnode(dev)    
def circuit(weights, angles):
    statepreparation(angles)

    for W in weights:
        layer(W)

    return qml.expval(qml.PauliZ(0))

def variational_classifier(weights, bias, angles):
    return circuit(weights, angles) + bias

def cost(weights, bias, features, labels):
    predictions = [variational_classifier(weights, bias, f) for f in features]
    return square_loss(labels, predictions)

num_qubits = qbits
num_layers = 6

weights_init = 0.01 * np.random.randn(num_layers, num_qubits, 3, requires_grad=True)
bias_init = np.array(0.0, requires_grad=True)
opt = qml.QNGOptimizer(0.02)
batch_size = 5

# train the variational classifier
weights = weights_init
bias = bias_init
his_acc_val = []
his_acc_train = []
his_cost = []
#cost(weights, bias, features, labels)
for it in range(60):
    
    metric_fn = lambda p: qml.metric_tensor(cost, approx="block-diag")(p, bias, feats_train_batch, Y_train_batch)
    
    # Update the weights by one optimizer step
    batch_index = np.random.randint(0, num_train, (batch_size,))
    feats_train_batch = feats_train[batch_index]
    Y_train_batch = Y_train[batch_index]
    weights, bias, _, _ = opt.step(cost, weights, metric_tensor_fn=metric_fn, bias, feats_train_batch, Y_train_batch)

    # Compute predictions on train and validation set
    predictions_train = [np.sign(variational_classifier(weights, bias, f)) for f in feats_train]
    predictions_val = [np.sign(variational_classifier(weights, bias, f)) for f in feats_val]

    # Compute accuracy on train and validation set
    acc_train = accuracy(Y_train, predictions_train)
    
    acc_val = accuracy(Y_val, predictions_val)
    
    his_acc_val.append(acc_val)
    his_acc_train.append(acc_train)
    his_cost.append(cost(weights, bias, features, Y))
    print(
        "Iter: {:5d} | Cost: {:0.7f} | Acc train: {:0.7f} | Acc validation: {:0.7f} "
        "".format(it + 1, cost(weights, bias, features, Y), acc_train, acc_val)
    )
print(his_acc_val, his_acc_train)

Input In [155]
weights, bias, _, _ = opt.step(cost, weights, metric_tensor_fn=metric_fn, bias, feats_train_batch, Y_train_batch)
^
SyntaxError: positional argument follows keyword argument

Hi @RX1,

What your error is saying is that if you have an argument which you call like “arg=…” (a keyword argument) then you cannot have other arguments after that, which are not defined with an ‘equals’ sign (positional arguments).

In fact if you look at the documentation for the step method of the QNGOptimizer you will notice that only keyword arguments can follow after you specify the metric_tensor_fn.

step ( qnode , *args , grad_fn=None , recompute_tensor=True , metric_tensor_fn=None , **kwargs )

Please let me know if this helps!