Search code examples
optimizationscipyleast-squaresscipy-optimize

How can I constrain a coefficient to an integer value in the least_squares function in SciPy optimization?


I am using the 'least_squares' function from the SciPy library in Python for optimization. I want to constrain a coefficient to always be an integer value within a bound. However, the least_squares function does not seem to have a built-in option to include constraints - only bounds. Is there any way to introduce constraints in the least_sqaures function?

I have this code:

def objective_function(params, target):
    # ... implementation of the objective function ...

def constraint(params):
    coeff = params[0]

    if not isinstance(coeff, int):
        return False

    return True

# Input parameters
coeff_initial_guess = 2
# ... other parameters ...

# Bounds for optimization
bounds = ([1], [4])  # Bounds for coeff

# Set up the optimization problem
result = least_squares(objective_function, [coeff_initial_guess], bounds=bounds)

Is there a way to incorporate the constraint function into the least_squares optimization process to enforce that the coefficient remains an integer? Alternatively, are there any alternative optimization functions in SciPy that can handle such constraints?

Any help or suggestions would be greatly appreciated. Thank you!


Solution

  • Please use optimize.differential_evolution, that function has an integrality keyword to allow you to specify which parameters need to be integers. You will have to reformulate your least_squares objective into a scalar function (e.g. fun = np.sum(objective_function(pars)**2))