问题描述
我知道这个问题应该在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
你的约束(如果多个 dicts 列表):
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)
这篇关于scipy 最小化约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!