Python scipy 最小化约束
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20075714/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
scipy minimize with constraints
提问by wa4557
I know that this question should be handled in the manual of scipy.optimize, but I don't understand it well enough. Maybe you can help
我知道这个问题应该在scipy.optimize的手册中处理,但我对它的理解不够好。也许你可以帮忙
I have a function (this is just an example, not the real function, but I need to understand it at this level):
我有一个函数(这只是一个例子,不是真正的函数,但我需要在这个层面上理解它):
Edit (better example):
编辑(更好的例子):
Let's suppose I have a matrix
假设我有一个矩阵
arr = array([[0.8, 0.2],[-0.1, 0.14]])
with a target function
有目标函数
def matr_t(t):
return array([[t[0], 0],[t[2]+complex(0,1)*t[3], t[1]]]
def target(t):
arr2 = matr_t(t)
ret = 0
for i, v1 in enumerate(arr):
for j, v2 in enumerate(v1):
ret += abs(arr[i][j]-arr2[i][j])**2
return ret
now I want to minimize this target function under the assumption that the t[i] are real numbers, and something like t[0]+t[1]=1
现在我想在 t[i] 是实数的假设下最小化这个目标函数,比如 t[0]+t[1]=1
采纳答案by askewchan
This constraint
这个约束
t[0] + t[1] = 1
would be an equality (type='eq') constraint, where you make a function that must equal zero:
将是一个等式 ( type='eq') 约束,您可以在其中创建一个必须等于零的函数:
def con(t):
return t[0] + t[1] - 1
Then you make a dictof your constraint (list of dicts if more than one):
然后你做一个dict你的约束(如果超过一个,则为字典列表):
cons = {'type':'eq', 'fun': con}
I've never tried it, but I believe that to keep treal, you could use:
我从未尝试过,但我相信要保持t真实,您可以使用:
con_real(t):
return np.sum(np.iscomplex(t))
And make your consinclude both constraints:
并使您cons包含两个约束:
cons = [{'type':'eq', 'fun': con},
{'type':'eq', 'fun': con_real}]
Then you feed consinto minimizeas:
然后你cons输入minimize为:
scipy.optimize.minimize(func, x0, constraints=cons)

