SkilVaultSign inStart free

Catalogue / python-multiobjective-optimization

python-multiobjective-optimization

MITSignedExpert guidance for multiobjective optimization in Python - Pareto optimality, evolutionary algorithms (NSGA-II, NSGA-III, MOEA/D), scalarization methods, Pareto front analysis, and implementation with pymoo, platypus, and DEAP
---
name: python-multiobjective-optimization
description: Expert guidance for multiobjective optimization in Python - Pareto optimality, evolutionary algorithms (NSGA-II, NSGA-III, MOEA/D), scalarization methods, Pareto front analysis, and implementation with pymoo, platypus, and DEAP
allowed-tools: ["*"]
---

Python Multiobjective Optimization

Overview

Master multiobjective optimization where you must simultaneously optimize multiple conflicting objectives. Unlike single-objective optimization that finds one optimal solution, multiobjective optimization discovers a Pareto front - a set of trade-off solutions where improving one objective worsens another.

Core value: Find optimal trade-offs between competing objectives (cost vs. performance, risk vs. return, speed vs. accuracy) and enable informed decision-making across the Pareto frontier.

When to Use

Use multiobjective optimization when:

  • Optimizing multiple conflicting objectives simultaneously
  • Need trade-off analysis between competing goals
  • Decision-makers must choose from Pareto-optimal alternatives
  • No single "best" solution exists without preference information

Examples:

  • Portfolio optimization: maximize return, minimize risk
  • Engineering design: minimize cost, maximize performance, minimize weight
  • Manufacturing: maximize throughput, minimize defects, minimize energy
  • Drug design: maximize efficacy, minimize toxicity, maximize bioavailability
  • Vehicle routing: minimize distance, minimize time, minimize vehicles

Don't use when:

  • Only one objective exists (use single-objective optimization)
  • Objectives can be combined into single metric with known weights
  • One objective is vastly more important than others

Key Concepts

Pareto Dominance

Solution x dominates solution y if:

  1. x is no worse than y in all objectives
  2. x is strictly better than y in at least one objective
def dominates(obj_x, obj_y, minimize=True):
    """
    Check if obj_x dominates obj_y (for minimization).

    Returns True if obj_x dominates obj_y.
    """
    if minimize:
        # For minimization: x dominates y if all x_i <= y_i and at least one x_i < y_i
        better_or_equal = all(x <= y for x, y in zip(obj_x, obj_y))
        strictly_better = any(x < y for x, y in zip(obj_x, obj_y))
    else:
        # For maximization: x dominates y if all x_i >= y_i and at least one x_i > y_i
        better_or_equal = all(x >= y for x, y in zip(obj_x, obj_y))
        strictly_better = any(x > y for x, y in zip(obj_x, obj_y))

    return better_or_equal and strictly_better

Pareto Front (Pareto Frontier)

The Pareto front is the set of all non-dominated solutions - solutions where you cannot improve one objective without worsening another.

Properties:

  • All points on the Pareto front are equally "optimal" from mathematical perspective
  • Choosing among Pareto solutions requires preference information
  • Moving along the front trades one objective for another

Utopia and Nadir Points

  • Utopia point: Best possible value for each objective (usually infeasible)
  • Nadir point: Worst value among Pareto-optimal solutions for each objective

Methods Overview

Scalarization Approaches

Convert multiobjective problem to series of single-objective problems.

1. Weighted Sum

  • Combine objectives with weights: minimize w₁f₁(x) + w₂f₂(x)
  • Pros: Simple, uses any single-objective solver
  • Cons: Cannot find non-convex Pareto fronts, sensitive to scaling

2. Weighted Metrics (Lp-norm)

  • Minimize ||f(x) - ideal||ₚ with weights
  • Pros: Can find non-convex fronts (p=∞)
  • Cons: Requires ideal point estimation

3. ε-Constraint Method

  • Minimize one objective, constrain others: min f₁(x) s.t. f₂(x) ≤ ε
  • Pros: Finds entire Pareto front including non-convex regions
  • Cons: Many single-objective solves, requires constraint bounds

4. Goal Programming

  • Minimize deviation from target goals
  • Pros: Intuitive when targets known
  • Cons: Requires setting goals

Evolutionary Algorithms

Population-based metaheuristics that evolve Pareto front approximations.

1. NSGA-II (Non-dominated Sorting Genetic Algorithm II)

  • Most popular multiobjective evolutionary algorithm
  • Fast non-dominated sorting + crowding distance
  • Pros: Robust, well-tested, handles 2-3 objectives well
  • Cons: Degrades with many objectives (>3)

2. NSGA-III

  • Extension of NSGA-II for many objectives (4+)
  • Reference point-based selection
  • Pros: Scales to many objectives
  • Cons: More complex parameter tuning

3. MOEA/D (Multiobjective Evolutionary Algorithm based on Decomposition)

  • Decomposes problem into scalar subproblems
  • Pros: Efficient, good for many objectives
  • Cons: Requires careful decomposition setup

4. Other Algorithms

  • SPEA2, PAES, GDE3, SMS-EMOA, etc.

Comparison

| Method | Objectives | Pareto Front Type | Pros | Cons | |--------|-----------|-------------------|------|------| | Weighted Sum | 2-3 | Convex only | Simple, fast | Misses non-convex regions | | ε-Constraint | 2-3 | Any | Complete coverage | Many solves needed | | NSGA-II | 2-3 | Any | Robust, popular | Poor for many objectives | | NSGA-III | 4+ | Any | Handles many objectives | Complex tuning | | MOEA/D | 4+ | Any | Efficient | Decomposition setup |

Library Selection

pymoo - Recommended

Use when:

  • Need modern, comprehensive multiobjective optimization
  • Want evolutionary algorithms (NSGA-II, NSGA-III, MOEA/D)
  • Need built-in performance indicators
  • Want clean, object-oriented API

Strengths:

  • Actively maintained
  • Extensive algorithm library
  • Built-in test problems
  • Performance indicators (hypervolume, etc.)
  • Good documentation

Installation:

pip install pymoo

platypus

Use when:

  • Need pure Python implementation
  • Want simple API
  • Lightweight dependency footprint

Strengths:

  • Pure Python (no compilation)
  • Simple interface
  • Multiple algorithms

Installation:

pip install platypus-opt

DEAP

Use when:

  • Need general evolutionary computation framework
  • Want customization flexibility
  • Already using DEAP for other tasks

Strengths:

  • Highly flexible
  • Large community
  • General-purpose evolutionary algorithms

Cons:

  • More complex API
  • Less specialized for multiobjective

Installation:

pip install deap

scipy.optimize

Use when:

  • Only need scalarization approaches
  • Want minimal dependencies
  • Already using scipy

Limitations:

  • No built-in evolutionary algorithms
  • Manual Pareto front construction
  • Limited multiobjective-specific tools

Implementation Patterns

Pattern 1: NSGA-II with pymoo

import numpy as np
from pymoo.algorithms.moo.nsga2 import NSGA2
from pymoo.core.problem import Problem
from pymoo.optimize import minimize
from pymoo.visualization.scatter import Scatter

# Define problem
class MyProblem(Problem):
    def __init__(self):
        super().__init__(
            n_var=2,           # Number of decision variables
            n_obj=2,           # Number of objectives
            n_ieq_constr=0,    # Number of inequality constraints
            xl=np.array([0, 0]),    # Lower bounds
            xu=np.array([1, 1])     # Upper bounds
        )

    def _evaluate(self, x, out, *args, **kwargs):
        """
        Evaluate objectives for population x.

        x: array of shape (pop_size, n_var)
        out["F"]: objectives of shape (pop_size, n_obj)
        out["G"]: constraints of shape (pop_size, n_constr) [optional]
        """
        # Objective 1: minimize (x1 - 0.5)^2 + (x2 - 0.5)^2
        f1 = (x[:, 0] - 0.5)**2 + (x[:, 1] - 0.5)**2

        # Objective 2: minimize (x1 - 0.2)^2 + (x2 - 0.8)^2
        f2 = (x[:, 0] - 0.2)**2 + (x[:, 1] - 0.8)**2

        out["F"] = np.column_stack([f1, f2])

# Create problem instance
problem = MyProblem()

# Configure algorithm
algorithm = NSGA2(
    pop_size=100,           # Population size
    eliminate_duplicates=True
)

# Solve
res = minimize(
    problem,
    algorithm,
    ('n_gen', 200),         # Termination: 200 generations
    seed=1,
    verbose=True
)

# Results
print(f"Number of Pareto solutions: {len(res.F)}")
print(f"Objective values (first 5):\n{res.F[:5]}")
print(f"Decision variables (first 5):\n{res.X[:5]}")

# Visualize Pareto front
plot = Scatter()
plot.add(res.F, label="Pareto Front")
plot.show()

Pattern 2: NSGA-III for Many Objectives

from pymoo.algorithms.moo.nsga3 import NSGA3
from pymoo.util.ref_dirs import get_reference_directions

# Problem with many objectives (e.g., 4)
class ManyObjectiveProblem(Problem):
    def __init__(self):
        super().__init__(
            n_var=10,
            n_obj=4,           # 4 objectives
            xl=-5,
            xu=5
        )

    def _evaluate(self, x, out, *args, **kwargs):
        # Define 4 conflicting objectives
        f1 = np.sum(x[:, :5]**2, axis=1)
        f2 = np.sum((x[:, :5] - 1)**2, axis=1)
        f3 = np.sum(x[:, 5:]**2, axis=1)
        f4 = np.sum((x[:, 5:] - 2)**2, axis=1)

        out["F"] = np.column_stack([f1, f2, f3, f4])

# Create reference directions for 4 objectives
ref_dirs = get_reference_directions("das-dennis", 4, n_partitions=12)

# NSGA-III algorithm
algorithm = NSGA3(
    ref_dirs=ref_dirs,
    pop_size=92  # Must match reference directions
)

# Solve
problem = ManyObjectiveProblem()
res = minimize(
    problem,
    algorithm,
    ('n_gen', 300),
    seed=1,
    verbose=True
)

print(f"Number of Pareto solutions: {len(res.F)}")

Pattern 3: With Constraints

class ConstrainedProblem(Problem):
    def __init__(self):
        super().__init__(
            n_var=2,
            n_obj=2,
            n_ieq_constr=2,    # 2 inequality constraints
            xl=np.array([0, 0]),
            xu=np.array([5, 5])
        )

    def _evaluate(self, x, out, *args, **kwargs):
        # Objectives
        f1 = x[:, 0]**2 + x[:, 1]**2
        f2 = (x[:, 0] - 3)**2 + (x[:, 1] - 3)**2

        # Inequality constraints: g(x) <= 0
        g1 = x[:, 0] + x[:, 1] - 5      # x1 + x2 <= 5
        g2 = -(x[:, 0] + 2*x[:, 1] - 6)  # x1 + 2*x2 >= 6

        out["F"] = np.column_stack([f1, f2])
        out["G"] = np.column_stack([g1, g2])

# Solve with NSGA-II (handles constraints automatically)
problem = ConstrainedProblem()
algorithm = NSGA2(pop_size=100)
res = minimize(problem, algorithm, ('n_gen', 200), seed=1)

# Check constraint violations
print(f"Max constraint violation: {np.max(res.CV)}")  # Should be ~0

Pattern 4: Weighted Sum (Scalarization)

from scipy.optimize import minimize as scipy_minimize

def objectives(x):
    """Return tuple of objectives"""
    f1 = x[0]**2 + x[1]**2
    f2 = (x[0] - 1)**2 + (x[1] - 1)**2
    return f1, f2

def scalarized_objective(x, weights):
    """Weighted sum of objectives"""
    f1, f2 = objectives(x)
    return weights[0] * f1 + weights[1] * f2

# Generate Pareto front by varying weights
weights_list = np.linspace(0, 1, 11)
pareto_front = []

for w in weights_list:
    weights = [w, 1 - w]

    result = scipy_minimize(
        scalarized_objective,
        x0=[0.5, 0.5],
        args=(weights,),
        method='SLSQP',
        bounds=[(0, 2), (0, 2)]
    )

    if result.success:
        f1, f2 = objectives(result.x)
        pareto_front.append({
            'x': result.x,
            'f1': f1,
            'f2': f2,
            'weights': weights
        })

# Convert to arrays
F = np.array([[p['f1'], p['f2']] for p in pareto_front])
X = np.array([p['x'] for p in pareto_front])

print(f"Found {len(pareto_front)} Pareto solutions")

Pattern 5: ε-Constraint Method

from scipy.optimize import minimize as scipy_minimize

def objective1(x):
    return x[0]**2 + x[1]**2

def objective2(x):
    return (x[0] - 1)**2 + (x[1] - 1)**2

# ε-constraint: minimize f1, subject to f2 <= epsilon

Preview shortened. The full SKILL.md is in the pack.