使用 scipy.minimize 迭代约束
我正在尝试最小化具有 2 个变量 x[0],x[1] 的函数。 A、B 和 C 是尺寸为 10x10 的数据框。当我不使用约束时,优化会按预期进行,但我也关心约束情况。对于受限的情况,我想要
A.iloc[i,j]*x[0]*B.iloc[i,j]*x[1]*C.iloc[i,j]
等于或大于零j。为了实现这一点,我通过以下方式定义了约束:
cons=[]
def f(a):
def g(x):
return A.iloc[i,j]*x[0]*B.iloc[i,j]*x[1]*C.iloc[i,j]
return g
for i in range (10):
for j in range(10):
cons.append({'type':'ineq', 'fun': f(t)})
虽然我得到了正确数量的约束(即 len(cons) = 100),但优化结果不满足我想要的约束,这意味着它会导致x[0]、x[1] 和 x[2] 的值,其中
A.iloc[i,j]*x[0]*B.iloc[i,j]*x[1]*C.iloc[i,j]
小于零。我已经确定result.success = True,因此可以排除优化突然停止的潜在问题。在寻找此问题的解决方案时,我发现 在这种情况下,有人试图在 scipy 中迭代约束,但他们只迭代一个范围而不是两个范围,我无法修改他们的解决方案以使其工作对于我的情况。
I am trying to minimize a function with 2 variables x[0],x[1]. A, B, and C are dataframes with dimensions 10x10. The optimization works as intended when I don't use constraints, however I also care for the constrainted case. For the constrainted case, I want
A.iloc[i,j]*x[0]*B.iloc[i,j]*x[1]*C.iloc[i,j]
to be equal to or greater than zero for all combinations of i and j. To achieve this, I have defined constraints in the following way:
cons=[]
def f(a):
def g(x):
return A.iloc[i,j]*x[0]*B.iloc[i,j]*x[1]*C.iloc[i,j]
return g
for i in range (10):
for j in range(10):
cons.append({'type':'ineq', 'fun': f(t)})
While I am getting the right number of constraints (i.e. len(cons) = 100), the optimization results do not satisfy the constraints that I had in mind, meaning it results in values for x[0], x[1] and x[2] for which
A.iloc[i,j]*x[0]*B.iloc[i,j]*x[1]*C.iloc[i,j]
is smaller than zero for many j,i. I have ascertained that result.success = True, so the optimization suddenly stopping can be ruled out as a potential problem. While looking for a solution to this problem, I have found this case of someone trying to iterate constraints in scipy aswell, but they only iterated over one range rather than over two and I was not able to modify their solution to work for my case.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的函数
f
没有任何意义,因为函数g
不依赖于a
。如果您确实希望f
根据索引i
和t
返回一个新函数,则f
应该是两个索引的函数:另请注意,借助 lambda 表达式,您可以轻松地动态定义约束函数:
Your function
f
doesn't make any sense since the functiong
doesn't depend ona
. If you really wantf
to return a new function depending on the indicesi
andt
,f
should be a function of the two indices:Note also that you could easily define the constraint functions on the fly thanks to lambda expressions: