Scipy Optimization Not Running when I try to set constraints using a for loop

后端 未结 1 486
感情败类
感情败类 2020-12-07 05:24

I was trying to minimize the objective function while using a for loop to set the constraints such that x1 = x2 = ... xn. However, the optimization doesn\'t seem to work. I.

1条回答
  •  天命终不由人
    2020-12-07 05:51

    (Note: while the details are different, this question is about the same problem as Scipy.optimize.minimize SLSQP with linear constraints fails.)

    Your loop is

    for i in range(0,x0.size-1):
        con = {'type': 'eq', 'fun': lambda x:  x[i] - x[i+1]}    
        cons = np.append(cons, con)
    

    The problem is the use of i in the lambda expression. Python closures are "late binding". That means value of i that is used when the function is called is not the same as the value of i when the function was created. After the loop, the value of i is 2, so the expression evaluated by all the functions created in the loop is x[2] - x[3]. (That also explains the "singular matrix C" referred to in the error message.)

    One way to fix this is to make i an argument of the lambda expression whose default value is the current i:

        con = {'type': 'eq', 'fun': lambda x, i=i:  x[i] - x[i+1]}
    

    0 讨论(0)
提交回复
热议问题