编写具有多个目标的用户定义问题#
在本章中,我们将展示如何编写一个具有多个目标的无约束用户定义问题(UDP)。 我们假设问题的数学公式如下:
\[\begin{split}\begin{array}{ll}
\mbox{minimize: } & f_{1}(x) = x^{2} \\
& f_{2}(x) = (x-2)^{2} \\
\mbox{subject to:} & 0 \le x \le 2
\end{array}\end{split}\]
这是一个用于多目标优化的测试函数,由 Schaffer, J. David (1984). 一些使用向量评估遗传算法的机器学习实验(人工智能、优化、适应、模式识别)(博士论文)。范德比尔特大学。 引入并在 这里 进行了说明。
UDP的实现可以如下所示:
>>> class Schaffer:
... # Define objectives
... def fitness(self, x):
... f1 = x[0]**2
... f2 = (x[0]-2)**2
... return [f1, f2]
...
... # Return number of objectives
... def get_nobj(self):
... return 2
...
... # Return bounds of decision variables
... def get_bounds(self):
... return ([0]*1, [2]*1)
...
... # Return function name
... def get_name(self):
... return "Schaffer function N.1"
请注意,单目标和多目标问题之间的唯一区别在于目标的数量。
现在让我们从新的UDP类创建一个对象,并将其传递给pygmo 问题
。
>>> import pygmo as pg
>>> # create UDP
>>> prob = pg.problem(Schaffer())
在下一步中,可以使用algorithm
类中的NSGA2算法直接解决问题:
>>> # create population
>>> pop = pg.population(prob, size=20)
>>> # select algorithm
>>> algo = pg.algorithm(pg.nsga2(gen=40))
>>> # run optimization
>>> pop = algo.evolve(pop)
>>> # extract results
>>> fits, vectors = pop.get_f(), pop.get_x()
>>> # extract and print non-dominated fronts
>>> ndf, dl, dc, ndr = pg.fast_non_dominated_sorting(fits)
>>> print(ndf)
[array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19], dtype=uint64)]
我们已经完成了!