cannot reshape array error for a simple 2-objective problem with pymoo

139 views Asked by At

This is simple 2-objective and 5-integer problem with NSGA-II algorithm, the notebook code:

import numpy as np
from pymoo.core.problem import ElementwiseProblem
from pymoo.algorithms.moo.nsga2 import NSGA2
# from pymoo.factory import get_sampling, get_crossover, get_mutation
from pymoo.optimize import minimize
from pymoo.operators.sampling.rnd import IntegerRandomSampling
from pymoo.operators.crossover.sbx import SBX
from pymoo.operators.mutation.pm import PM
from pymoo.visualization.scatter import Scatter

# Custom 2-objective, 5-integer optimization problem
class MyProblem(Problem):
    def __init__(self):
        super().__init__(
            n_var=5,
            n_obj=2,
            n_ieq_constr=0,
            xl=np.array([0,0,0,0,0]),  # Lower bounds for variables
            xu=np.array([10,10,10,10,10]),  # Upper bounds for variables
            vtype=int
        )

    def _evaluate(self, x, out, *args, **kwargs):
        # Objective functions
        f1 = np.sum(x ** 2)  # Minimize the sum of squares
        f2 = np.sum((x - 5) ** 2)  # Minimize the sum of squared deviations from 5

        # Assign objectives to the output
        out["F"] = [f1, f2]

# Instantiate the custom problem
problem = MyProblem()

# NSGA-II algorithm setup
algorithm = NSGA2(
    pop_size=100,
    n_offsprings=50,
    sampling=IntegerRandomSampling(),
    crossover=SBX(prob=1.0, eta=3.0),
    mutation=PM(prob=1.0, eta=3.0)
)

# Optimize the problem using NSGA-II
res = minimize(
    problem, 
    algorithm, 
    termination=('n_gen', 100), 
    seed=1,
    save_history=True,
    verbose=True
)

# Visualize the Pareto front
plot = Scatter()
plot.add(problem.pareto_front(), plot_type="line", color="black", alpha=0.7)
plot.add(res.F, color="red", s=30, label="NSGA-II")
plot.show()

I am not sure why the shape error. The 100 is population size, what should I modify here? Can anyone shed some light on this error?

Exception: ('Problem Error: F can not be set, expected shape (100, 2) but provided (1, 2)', ValueError('cannot reshape array of size 2 into shape (100,2)'))

Note this question is similar, but still I have this error.

Expected: No error and then I can review the result.

1

There are 1 answers

0
Dino Hsu On

Now it works, the only mistake is Problem should be ElementwiseProblem. Thanks a lot.