Scipy最小化:如何将args传递给目标和约束 [英] Scipy minimize: How to pass args to both the objective and the constraint

查看:92
本文介绍了Scipy最小化:如何将args传递给目标和约束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的MWE如下

def obj(e, p):
    S = f(e) + g(p)
    return S

我想仅在e上最小化此函数,并将p作为参数传递给该函数.但是,我也想要一个依赖于pe的约束,其形式为p + e < 1

I would like to minimize this function over only e and pass p as an argument to the function. However, I also would like a constraint that depends on p and e that is of the form p + e < 1

我尝试了

cons = {'type': 'ineq',
       'fun': lambda e, p: -e -p + 1,
       'args': (p)}

然后,对于p = 0.5

minimize(obj, initial_guess, method = 'SLSQP', args = 0.5, constraints = cons)

但这是行不通的.在定义cons的行中出现错误name 'p' is not defined.如何将参数p传递给目标函数和约束?

but this doesn't work. I get the error name 'p' is not defined in the line where I define cons. How do I pass the argument p to both the objective function and the constraint?

下面的完整代码

from scipy.optimize import minimize
from scipy.stats import entropy
import numpy as np

#Create a probability vector
def p_vector(x):
    v = np.array([x, 1-x])
    return v


#Write the objective function 
def obj(e, p):
    S = -1*entropy(p_vector(p + e), base = 2) 
    return S

##Constraints
cons = {'type': 'ineq',
       'fun': lambda e: -p - e + 1,
       'args': (p,)
       }

initial_guess = 0

result = minimize(obj, initial_guess, method = 'SLSQP', args = (0.5, ), constraints = cons)
print(result)

推荐答案

好吧,我认为这是语法错误以及如何传递参数的混合体.对于可能有相同问题的人,我将在此处发布答案.

Okay, I figured that it's a mix of syntax errors on my part and how arguments should be passed. For those who may have the same question, I will post an answer here.

目标函数是obj(e, p).我们只想最小化e,所以我们创建其他参数arguments = (0.5,)的元组.即,设置特定值p=0.5.接下来定义约束函数

The objective function is obj(e, p). We only want to minimize e so we create a tuple of the other arguments arguments = (0.5,). That is, a specific value of p=0.5 is set. Next define the constraint function

def prob_bound(e, p):
    return -e - p + 1

现在将约束字典写为

cons = ({'type': 'ineq',
       'fun': prob_bound,
       'args': arguments       
       })

最后,有人叫最小化器

result = minimize(obj, initial_guess, method = 'SLSQP', args = arguments, constraints = cons)

这篇关于Scipy最小化:如何将args传递给目标和约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆