数值优化

数值优化#

本笔记本提供了一个逐步教程,指导如何使用EvoX通过粒子群优化(PSO)算法来优化Ackley函数。PSO算法和Ackley优化问题都作为内置组件集成在EvoX框架中。

首先,我们应该导入所有必要的模块,包括 PSO(算法)、Ackley(问题)以及 StdWorkflowEvalMonitor(工作流)。

import torch

from evox.algorithms.pso_variants import PSO
from evox.problems.numerical import Ackley
from evox.workflows import StdWorkflow, EvalMonitor

在这里,我们实例化了PSO算法。我们指定了以下设置:

  • pop_size: 粒子群(种群)的大小。

  • lbub: 搜索空间中每个维度的下限和上限。

  • 其他参数都是默认的。请参考详细的API。

# Define the algorithm
algorithm = PSO(pop_size=100, lb=-32 * torch.ones(10), ub=32 * torch.ones(10))

接下来,我们选择 EvoX 的数值问题中的 Ackley 函数。

# Define the problem
problem = Ackley()

我们创建一个EvalMonitor实例,以跟踪优化过程中的必要信息。

# Define the monitor
monitor = EvalMonitor()

StdWorkflow 类提供了一个标准化的过程来整合算法、问题和监控器。

# Define the workflow
workflow = StdWorkflow()

调用 setup() 初始化组件,使工作流准备好执行优化步骤。

# Set up the workflow with the defined algorithm, problem and monitor
workflow.setup(algorithm=algorithm, problem=problem, monitor=monitor)

我们运行优化过程一定次数的迭代(在这个例子中是100次)。在每次迭代中,step() 方法更新PSO算法,在Ackley函数上评估新的候选解,并通过监视器跟踪它们的适应度。

# Perform the Ackley function optimization procedure
for _ in range(100):
    workflow.step()

最后,我们从工作流中检索 monitor 子模块,以访问迄今为止找到的最佳解决方案 (topk_solutions) 及其对应的目标值 (topk_fitness)。然后,我们打印出最佳结果及其相关的解决方案。

# Get the best solution and its fitness
monitor = workflow.get_submodule("monitor")
population = monitor.topk_solutions
fitness = monitor.topk_fitness
print(f"The best solution is:\n{population},\nwith the minimum value:\n{fitness}")
The best solution is:
tensor([[ 2.8948e-05, -9.1801e-05,  3.9575e-05,  2.3795e-05,  6.1906e-05,
         -1.1700e-04,  4.0033e-05,  4.3422e-05, -1.1519e-05, -2.7218e-05]]),
with the minimum value:
tensor([0.0002])
monitor.plot()