Skip to content
Advertisement

Scipy minimze with constrains that have no simple expression

I am trying to find the values that minimize a least squares function. The issue is that a solution may be valid or not in a way that cannot be given as a simple expression of the values. Instead, we can check the validity by calling a function.

What I tried to do was to set the sum of squares to infinity if the solution is not valid, but scipy.optimize.minimize does not like that. What’s a better way to solve this?

A simplified version of my code:

probs = constant
def sse(a_candidate):
        validity = some_function(a_candidate)

        if not validity:
            sum_sq_err = np.inf

        else:
            ym = function_of(a_candidate)
            sum_sq_err = np.sum((ym-probs)**2)

        return sum_sq_err
a_solution = scipy.optimize.minimize(sse,a0)

Advertisement

Answer

You can pass a NonlinearConstraint object to scipy.optimize.minimize.

a_solution = scipy.optimize.minimize(sse, a0, constraints=scipy.optimize.NonlinearConstraint(...))

I cannot provide further details because your question does not provide any detail, and by the same argument I cannot guarantee that imposing a NonLinearConstraint could actually help you.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement