提问人:vp_050 提问时间:12/10/2020 最后编辑:vp_050 更新时间:5/22/2023 访问量:1204
如何在 pymoo 中求解 NSGA 2 时将主导解决方案集保存到数据帧中?
How to save the set of dominated solutions while solving NSGA 2 in pymoo into a dataframe?
问:
我正在尝试使用 NSGA 2 求解具有 3 个目标和 2 个决策变量的多目标优化问题。NSGA2 算法的 pymoo 代码和终止标准如下。我的pop_size是 100,n_offspring是 100。该算法迭代了 100 多代。我想将所有 100 代中每一代考虑的所有 100 个决策变量值存储在一个数据帧中。
pymoo 代码中的 NSGA2 实现:
from pymoo.algorithms.nsga2 import NSGA2
from pymoo.factory import get_sampling, get_crossover, get_mutation
algorithm = NSGA2(
pop_size=20,
n_offsprings=10,
sampling=get_sampling("real_random"),
crossover=get_crossover("real_sbx", prob=0.9, eta=15),
mutation=get_mutation("real_pm", prob=0.01,eta=20),
eliminate_duplicates=True
)
from pymoo.factory import get_termination
termination = get_termination("n_gen", 100)
from pymoo.optimize import minimize
res = minimize(MyProblem(),
algorithm,
termination,
seed=1,
save_history=True,
verbose=True)
我尝试过什么(我的参考:stackoverflow 问题):
import pandas as pd
df2 = pd.DataFrame (algorithm.pop)
df2.head(10)
上面代码的结果是空白的,并且在传递时
print(df2)
我明白了
Empty DataFrame
Columns: []
Index: []
答:
4赞
Julian
12/14/2020
#1
很高兴您打算使用 pymoo 进行研究。您已正确启用该选项,这意味着您可以访问算法对象。
要获得运行中的所有解决方案,您可以组合每一代的后代 ()。别忘了对象包含目标。使用该方法,您可以获取 and 或其他值。请参阅下面的代码。save_history
algorithm.off
Population
Individual
get
X
F
import pandas as pd
from pymoo.algorithms.nsga2 import NSGA2 from pymoo.factory import get_sampling, get_crossover, get_mutation, ZDT1 from pymoo.factory import get_termination from pymoo.model.population import Population from pymoo.optimize import minimize
problem = ZDT1()
algorithm = NSGA2(
pop_size=20,
n_offsprings=10,
sampling=get_sampling("real_random"),
crossover=get_crossover("real_sbx", prob=0.9, eta=15),
mutation=get_mutation("real_pm", prob=0.01,eta=20),
eliminate_duplicates=True )
termination = get_termination("n_gen", 10)
res = minimize(problem,
algorithm,
termination,
seed=1,
save_history=True,
verbose=True)
all_pop = Population()
for algorithm in res.history:
all_pop = Population.merge(all_pop, algorithm.off)
df = pd.DataFrame(all_pop.get("X"), columns=[f"X{i+1}" for i in range(problem.n_var)])
print(df)
另一种方法是使用回调并填充每一代的数据帧。与此处类似:https://pymoo.org/interface/callback.html
评论
0赞
Colton Campbell
5/19/2023
这给了我ModuleNotFoundError:没有名为“pymoo.model”的模块
1赞
Julian
5/22/2023
请在上面找到新版本的答案。
2赞
Julian
5/22/2023
#2
更新了 pymoo==0.6.0.1 的答案
import pandas as pd
from pymoo.termination import get_termination
from pymoo.core.population import Population
from pymoo.optimize import minimize
from pymoo.algorithms.moo.nsga2 import NSGA2
from pymoo.problems.multi import ZDT1
problem = ZDT1()
algorithm = NSGA2(
pop_size=20,
n_offsprings=10)
res = minimize(problem,
algorithm,
termination=get_termination("n_gen", 10),
seed=1,
save_history=True,
verbose=True)
all_pop = Population()
for algorithm in res.history:
all_pop = Population.merge(all_pop, algorithm.off)
df = pd.DataFrame(all_pop.get("X"), columns=[f"X{i+1}" for i in range(problem.n_var)])
print(df)
评论