# Choosing a different optimizer when running QAOA in qiskit

I am trying to reproduce the QAOA example from https://qiskit.org/textbook/ch-applications/qaoa.html and learn how to opt for a different optimizer.

The relevant block in the example is (towards the end of the example):

from scipy.optimize import minimize

expectation = get_expectation(G, p=1)

res = minimize(expectation,
[1.0, 1.0],
method='COBYLA')
res


This effectively calls for COBYLA from scipy. However, in qiskit.algorithms.optimizers we can see a lot of other options: https://qiskit.org/documentation/stubs/qiskit.algorithms.optimizers.html

At the moment, for the block of code given above I cannot figure out how to change my optimizer. Say I want to apply ADAM or GradientDescent or SPSA. It is not clear to me how I can do that since just passing the argument 'ADAM' (for example) as below

res = minimize(expectation,
[1.0, 1.0],


give a ValueError: Unknown solver ADAM error. I get the corresponding error when I try other optimizers too.

How can I deal with this?

The optimizers in Qiskit need to be instantiated then you can call their minimize() method. e.g.

from qiskit.algorithms.optimizers import SPSA

opt = SPSA(maxiter=300)
res = opt.minimize(expectation, [1.0, 1.0])


So instead of the optimizer internally being created via a name passed to the method argument of scipy (where name is one of the optimizers available via scipy) here you create an instance and configure it via the constructor parameters, and use the minimize method on that instance.

• Ok, thanks. The precise code is this though: spsa = SPSA(maxiter=n) result = spsa.optimize("no of qubits", "expectation/loss", "initial point") Commented May 26, 2022 at 23:04
• The minimize() method is is newer versions of Qiskit >= 0.19 and optimize() is deprecated since version 0.19 and will be removed shortly. Your code will work in current versions, but in 0.19 and above would emit a deprecation warning telling you to use the minimize method instead github.com/Qiskit/qiskit-terra/blob/… Commented May 27, 2022 at 13:02
• Hmmm... looking over SPSA it overrides optimize and does not itself emit a deprecation warning - the intent is to remove optimize() entirely so using minimize which mimics the scipy interface, is recommended for Qiskit >= 0.19. If you are using an older version then only optimize exists so beware when you upgrade as if you skip through versions when upgrading you may miss deprecation messages such as this. Commented May 27, 2022 at 13:09
• changing from SPSA to ADAM does not work. Why is that? Is there not a "unified" way to try out different optimizers without changing the code? Commented Jun 6, 2022 at 9:20
• @Marion Note that some algorithms like Gradient Descent or ADAM, if I remember correctly, may require gradient information, which you must provide to them Commented Oct 4, 2022 at 11:04