Optimization error


#1

when I tried to optimize a quantum circuit using:
params = opt.step(circuit, my_init_params)

I got this error:
TypeError: Grad only applies to real scalar-output functions. Try jacobian or elementwise_grad.

what is wrong??


#2

Hi @EMY91,

For gradient descent optimization, the function you are optimizing must be scalar-valued, that is, it must return only a single real value, for example:

@qml.qnode(dev)
def circuit(params):
    qml.RX(params[0], wires=0)
    qml.RY(params[1], wires=0)
    return qml.expval.PauliZ(0) #single value

my_init_params = [0.1, 0.2]
opt = qml.GradientDescentOptimizer()
params = opt.step(circuit, my_init_params)

If the function to be optimized is instead vector-valued (it returns more than one real value), then you will run into the issue above:

@qml.qnode(dev)
def circuit(params):
    qml.RX(params[0], wires=0)
    qml.RY(params[1], wires=0)
    return qml.expval.PauliZ(0), qml.expval.PauliX(1) #list of values

my_init_params = [0.1, 0.2]
opt = qml.GradientDescentOptimizer()
params = opt.step(circuit, my_init_params)

TypeError: Grad only applies to real scalar-output functions. Try jacobian or elementwise_grad.

So always make sure that the cost function you are optimized is scalar-valued.