pymoo
Latest Version: pymoo==0.3.2

Callback FunctionΒΆ

Moreover, the callback function can be used to execute a function each generation. This can be useful to print custom output or perform generational post-processing.

For instance, to overwrite the custom print each generation:

[1]:
from pymoo.algorithms.nsga2 import NSGA2
from pymoo.factory import get_problem
from pymoo.optimize import minimize


def my_callback(algorithm):
    disp = algorithm.func_display_attrs(algorithm.problem, algorithm.evaluator, algorithm, algorithm.pf)
    print("My Custom Output: ", end='')
    algorithm._display(disp)


problem = get_problem("zdt2")

algorithm = NSGA2(pop_size=100, elimate_duplicates=True, callback=my_callback)

res = minimize(problem,
               algorithm,
               ('n_gen', 10),
               seed=1,
               verbose=False)


My Custom Output: 1     | 100     | 3.4068938395 | 4.4904152796 | 0.0000000000
My Custom Output: 2     | 200     | 3.4068938395 | 4.1121617389 | 0.0000000000
My Custom Output: 3     | 300     | 3.3159589611 | 3.8537078661 | 0.0000000000
My Custom Output: 4     | 400     | 3.2146794649 | 3.5878158468 | 0.0000000000
My Custom Output: 5     | 500     | 2.9864175509 | 3.3905357110 | 0.0000000000
My Custom Output: 6     | 600     | 2.7945273953 | 3.2972062538 | 0.0000000000
My Custom Output: 7     | 700     | 2.7945273953 | 3.2104683100 | 0.0000000000
My Custom Output: 8     | 800     | 2.7263366816 | 2.9436474598 | 0.0000000000
My Custom Output: 9     | 900     | 2.5060995727 | 2.7295135760 | 0.0000000000
My Custom Output: 10    | 1000    | 2.2650145244 | 2.6078074972 | 0.0000000000

Analogously, custom plots each generation or an animation can be created.