[Python] platypus NSGA-II, Optimal input variable printing issue

Discussão em 'Python' iniciado por Stack, Setembro 16, 2025.

  1. Stack

    Stack Membro Participativo

    I am running into a problem when trying to print the "best" decision variable values based on a certain case (that the one objective is less than 1). I am using the NSGA-II algorithm from platypus.

    The output for the best decision variables print as: [[False, True, False, True, False]] instead of as an integer value.

    Here is my code (my actual problem is much more complex than this, but this simple example showcases the same issue wrt the printing of the best decision variable value):

    import streamlit as st
    import matplotlib.pyplot as plt
    from platypus import NSGAII, Problem, Integer

    st.title("Pareto Front using NSGA-II (Platypus)")

    # Define problem
    problem = Problem(1, 2)
    problem.types[0] = Integer(-10, 10)
    problem.function = lambda x: [x[0]**2, (x[0]-2)**2]

    # Run NSGA-II
    algorithm = NSGAII(problem)
    algorithm.run(10000)

    # Extract solutions
    solutions = algorithm.result
    f1 = [s.objectives[0] for s in solutions]
    f2 = [s.objectives[1] for s in solutions]

    # Filter: objective2 < 1
    filtered = [s for s in solutions if s.objectives[1] < 1]

    if filtered:
    # Find solution with lowest objective1
    best = min(filtered, key=lambda s: s.objectives[0])
    st.subheader("Best solution with f2 < 1")
    st.write(f"Decision variables: {best.variables}")
    st.write(f"Objectives: f1={best.objectives[0]:.4f}, f2={best.objectives[1]:.4f}")

    # Plot
    fig, ax = plt.subplots()
    ax.scatter(f1, f2, c="blue", s=10, alpha=0.5, label="All Solutions")
    ax.scatter(
    [best.objectives[0]], [best.objectives[1]],
    c="red", s=80, label="Best (f2 < 1)"
    )
    ax.set_xlabel("Objective 1 (x^2)")
    ax.set_ylabel("Objective 2 ((x-2)^2)")
    ax.set_title("Pareto Front (NSGA-II)")
    ax.legend()
    ax.grid(True)

    st.pyplot(fig)

    else:
    st.warning("No solutions found with f2 < 1")


    I tried prompting an LLM, but could not get this to work. Is there something simple that I am missing?

    Continue reading...

Compartilhe esta Página