I tried to save all the intermediate values of the parameters when running the built-in VQE in qiskit. The callback function can save the mean values and counts, however it seems only save the very last set of parameters. Please see the codes below, which is really taken from the link here https://github.com/qiskit-community/qiskit-community-tutorials/blob/master/aqua/vqe_convergence.ipynb.
import numpy as np
import pylab
from qiskit import BasicAer
from qiskit.aqua.operators import WeightedPauliOperator
from qiskit.aqua import QuantumInstance, aqua_globals
from qiskit.aqua.algorithms import VQE, NumPyMinimumEigensolver
from qiskit.aqua.components.initial_states import Zero
from qiskit.aqua.components.optimizers import COBYLA, L_BFGS_B, SLSQP
from qiskit.circuit.library import TwoLocal
pauli_dict = {
'paulis': [{"coeff": {"imag": 0.0, "real": -1.052373245772859}, "label": "II"},
{"coeff": {"imag": 0.0, "real": 0.39793742484318045}, "label": "ZI"},
{"coeff": {"imag": 0.0, "real": -0.39793742484318045}, "label": "IZ"},
{"coeff": {"imag": 0.0, "real": -0.01128010425623538}, "label": "ZZ"},
{"coeff": {"imag": 0.0, "real": 0.18093119978423156}, "label": "XX"}
]
}
qubit_op = WeightedPauliOperator.from_dict(pauli_dict)
num_qubits = qubit_op.num_qubits
init_state = Zero(num_qubits)
var_form = TwoLocal(num_qubits, 'ry', 'cz', initial_state=init_state)
counts = []
values = []
para = []
def store_intermediate_result(eval_count, parameters, mean, std):
counts.append(eval_count)
values.append(mean)
para.append( parameters )
algo = VQE(qubit_op, var_form, COBYLA(), callback=store_intermediate_result)
backend = BasicAer.get_backend('statevector_simulator')
quantum_instance = QuantumInstance(backend=backend)
algo_result = algo.run(quantum_instance)
counts = np.asarray(counts)
values = np.asarray(values)
para = np.asarray( para )
# print( 'counts' , counts )
# print( 'values' , values )
print( para)
This is in fact exactly the same code as in this answer VQE restart from a previous computation (I have also browsed other answers with keyword "callback"), and I can get the intermediate values of the cost function. However, for the parameters, what I got is the following (just copy the first few lines), which seems to be the very last set of parameters. Any ideas which part went wrong here?
[[ 1.82181708 -4.4450779 6.76132624 2.43831885 1.15624184 7.51034512
6.81040957 3.23410408]
[ 1.82181708 -4.4450779 6.76132624 2.43831885 1.15624184 7.51034512
6.81040957 3.23410408]
[ 1.82181708 -4.4450779 6.76132624 2.43831885 1.15624184 7.51034512
6.81040957 3.23410408]
[ 1.82181708 -4.4450779 6.76132624 2.43831885 1.15624184 7.51034512
6.81040957 3.23410408]
[ 1.82181708 -4.4450779 6.76132624 2.43831885 1.15624184 7.51034512
6.81040957 3.23410408] ...