严格限制 [英] scipy minimize with constraints
问题描述
我知道这个问题应该在scipy.optimize手册中处理,但我不太了解.也许你可以帮忙
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
我有一个函数(这只是一个示例,不是真正的函数,但是我需要在这个级别上理解它):
I have a function (this is just an example, not the real function, but I need to understand it at this level):
编辑(更好的示例):
假设我有一个矩阵
arr = array([[0.8, 0.2],[-0.1, 0.14]])
具有目标功能
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
现在我想在t [i]是实数且类似t[0]+t[1]=1
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[0] + t[1] = 1
将是一个等式(type='eq'
)约束,在该约束中,您创建的函数必须等于零:
would be an equality (type='eq'
) constraint, where you make a function that must equal zero:
def con(t):
return t[0] + t[1] - 1
然后您对约束进行dict
(如果有多个字典,则为字典列表):
Then you make a dict
of your constraint (list of dicts if more than one):
cons = {'type':'eq', 'fun': con}
我从未尝试过,但是我相信要使t
真实,可以使用:
I've never tried it, but I believe that to keep t
real, you could use:
con_real(t):
return np.sum(np.iscomplex(t))
并使您的cons
包括两个约束:
And make your cons
include both constraints:
cons = [{'type':'eq', 'fun': con},
{'type':'eq', 'fun': con_real}]
然后将cons
作为以下内容输入到minimize
中:
Then you feed cons
into minimize
as:
scipy.optimize.minimize(func, x0, constraints=cons)
这篇关于严格限制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!