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:
JavaScript
x
14
14
1
probs = constant
2
def sse(a_candidate):
3
validity = some_function(a_candidate)
4
5
if not validity:
6
sum_sq_err = np.inf
7
8
else:
9
ym = function_of(a_candidate)
10
sum_sq_err = np.sum((ym-probs)**2)
11
12
return sum_sq_err
13
a_solution = scipy.optimize.minimize(sse,a0)
14
Advertisement
Answer
You can pass a NonlinearConstraint object to scipy.optimize.minimize
.
JavaScript
1
2
1
a_solution = scipy.optimize.minimize(sse, a0, constraints=scipy.optimize.NonlinearConstraint( ))
2
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.