快速开始#

在这个笔记本中,我们将通过一个简单的例子帮助您熟悉EvoX。

要开始,请确保您已经安装了EvoX。

# install EvoX, skip it if you have already installed EvoX
from importlib.util import find_spec

if find_spec("evox") is None:
    %pip install evox
# the dependent packages or functions in this example
import time

import torch

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

EvoX中的基本运行过程#

作为一个分布式GPU加速框架,用于可扩展的演化计算,EvoX可以用于进行多种计算,因此我们说“EvoX是你所需要的一切”。尽管许多类型的计算或多或少有所不同,但在EvoX中,我们标准化了基本的运行过程:

Initiate an algorithm and a problem -- Set an monitor -- Initiate a workflow -- Run the workflow

初始化一个算法和一个问题#

EvoX 提供了一个全面的套件,包括50多个演化算法(EAs)和100多个基准问题/环境,所有这些都受益于分布式GPU加速。

有关更多详细信息,请参阅我们的API文档:List of AlgorithmsList of Problems

在这里,我们将创建一个 PSO 算法和一个 Ackley 函数问题。

# Initiate an algorithm
algorithm = PSO(
    pop_size=1000,
    lb=torch.tensor([-10.0]),
    ub=torch.tensor([10.0]),
)

# Initiate a problem
problem = Ackley()

请注意,算法和问题本身并不包含步骤的监控,因此仅依靠它们我们不会得到任何反馈。事实证明,我们需要一个monitor

设置一个monitor#

Monitor 是 EvoX 中的一个标准类,用于监视优化过程中的中间值。像适应度或种群这样的信息可以通过 Monitor 轻松获取。

做比说更好,所以让我们创建一个“Evaluation monitor”:

# Set an monitor
monitor = EvalMonitor()

启动一个工作流#

一个工作流概述了完成任务或项目所需的一系列步骤。在 EvoX 中,工作流代表了演化计算的整体过程,将算法、问题和监控器结合在一起。

如果我们想运行算法来解决带有监视器的问题,我们需要创建一个Workflow类的工作流。

# Initiate an workflow
workflow = StdWorkflow()
workflow.setup(
    algorithm=algorithm,
    problem=problem,
    monitor=monitor,
)

运行工作流#

现在,我们可以运行工作流:

start = time.time()

# Run the workflow
for i in range(100):
    workflow.step()
    if (i + 1) % 10 == 0:
        run_time = time.time() - start
        top_fitness = workflow.get_submodule("monitor").topk_fitness
        print(f"The top fitness is {top_fitness} in {run_time:.4f} seconds at the {i+1}th generation.")
The top fitness is tensor([0.0010]) in 0.1065 seconds at the 10th generation.
The top fitness is tensor([4.7684e-06]) in 0.1087 seconds at the 20th generation.
The top fitness is tensor([9.5367e-07]) in 0.1102 seconds at the 30th generation.
The top fitness is tensor([9.5367e-07]) in 0.1115 seconds at the 40th generation.
The top fitness is tensor([9.5367e-07]) in 0.1128 seconds at the 50th generation.
The top fitness is tensor([9.5367e-07]) in 0.1140 seconds at the 60th generation.
The top fitness is tensor([9.5367e-07]) in 0.1152 seconds at the 70th generation.
The top fitness is tensor([9.5367e-07]) in 0.1166 seconds at the 80th generation.
The top fitness is tensor([9.5367e-07]) in 0.1179 seconds at the 90th generation.
The top fitness is tensor([9.5367e-07]) in 0.1191 seconds at the 100th generation.
workflow.get_submodule("monitor").plot()