I want to show the progress of differential evolution and store the objective funtion values as it runs. My MWE is:
def de_optimise():
def build_show_de(MIN=None):
if MIN is None:
MIN = [0]
def fn(xk, convergence):
obj_val = opt(xk)
if obj_val < MIN[-1]:
print("DE", [round(x, 2) for x in xk], obj_val)
MIN.append(opt(xk))
return fn
bounds = [(0,1)]*3
# Define the linear constraints
A = [[-1, 1, 0], [0, -1, 1]]
lb = [0.3, 0.4]
ub = [np.inf, np.inf]
constraints = LinearConstraint(A, lb, ub)
progress_f = [0]
c = build_show_de(progress_f)
print("Optimizing using differential evolution")
res = differential_evolution(
opt,
bounds=bounds,
constraints=constraints,
callback=c,
disp=True
)
print(f"external way of keeping track of MINF: {progress_f}")
de_optimise()
It works but in the function fn
I have to recompute opt(xk)
which must have already been computed. I have to do this as the callback function of differential_evolution is documented as follows:
callback: callable, callback(xk, convergence=val), optional A function to follow the progress of the minimization. xk is the best solution found so far. val represents the fractional value of the population convergence. When val is greater than one the function halts. If callback returns True, then the minimization is halted (any polishing is still carried out).
As this is slow it slows down the optimization a lot. How can I avoid having to do this?