anyoptimization / pymoo

NSGA2, NSGA3, R-NSGA3, MOEAD, Genetic Algorithms (GA), Differential Evolution (DE), CMAES, PSO
https://pymoo.org
Apache License 2.0
2.29k stars 391 forks source link

Support for Checking Self-Defined Statistics Between Generations #645

Open SiqiKe opened 1 month ago

SiqiKe commented 1 month ago

Hi,

I have a question regarding the ability to check some self-defined statistics between generations during the optimization run. Specifically, I would like to know if there is a way to compute and track custom statistics as the generations evolve.

Is there a built-in feature that allows me to calculate and compare some statistics between generations?

If not, could you suggest how I might modify the source code to enable this functionality?

Any guidance or example implementations would be greatly appreciated!

Thank you for your help!

peacemo commented 2 weeks ago

Hi, @SiqiKe:

You can access the fitting history by setting save_history=True in the minimize function. This flag would save every generation in the fitting progress. And then you can extract what you need for a statistical analyzation.

Here is the example:

  1. Run a NSGA-II fitting:
problem = get_problem("zdt1")

algorithm = NSGA2(pop_size=100)

res = minimize(problem,
               algorithm,
               ('n_gen', 200),
               seed=42,
               save_history=True,  # setting save_history=True
               verbose=False)
  1. After fitting, get the fitting history:
his = res.history  # a list contains this status of every generation
  1. Get the data you need:
first_gen_pop = his[0].pop  # the first generation's whole population
first_gen_opt = his[0].opt  # pareto front in first generation

first_gen_pop.get('X')  # the solutions
first_gen_pop.get('F')  # the objective spaces values

first_gen_opt.get('X')  
first_gen_opt.get('F')
  1. Let's draw the objective space of the first generation:
plot = Scatter()
plot.add(first_gen_pop.get('F'), facecolor="blue", edgecolor="blue")
plot.add(first_gen_opt.get('F'), facecolor="red", edgecolor="red")
plot.show()

output


As for your self-defined statistics, you can define your own functions and run the function after fitting for all generations!