qiskit/releasenotes/notes/0.19/SPSA-termination-callback-a...

44 lines
1.6 KiB
YAML

---
features:
- |
Added the ``termination_checker`` argument to the :class:`~qiskit.algorithms.optimizers.SPSA` optimizer.
This allows the user to implement a custom termination criterion.
.. code-block:: python
import numpy as np
from qiskit.algorithms.optimizers import SPSA
def objective(x):
return np.linalg.norm(x) + .04*np.random.rand(1)
class TerminationChecker:
def __init__(self, N : int):
"""
Callback to terminate optimization when the average decrease over
the last N data points is smaller than the specified tolerance.
"""
self.N = N
self.values = []
def __call__(self, nfev, parameters, value, stepsize, accepted) -> bool:
"""
Returns:
True if the optimization loop should be terminated.
"""
self.values.append(value)
if len(self.values) > self.N:
last_values = self.values[-self.N:]
pp = np.polyfit(range(self.N), last_values, 1)
slope = pp[0] / self.N
if slope > 0:
return True
return False
maxiter = 400
spsa = SPSA(maxiter=maxiter, termination_checker=TerminationChecker(10))
parameters, value, niter = spsa.optimize(2, objective, initial_point=np.array([0.5, 0.5]))