带约束的优化

Optimization with constrain

我想解决一个约束优化问题。

最大{ln (c1) + ln (c2)}

s.t。 4(c1) + 6(c2) ≤ 40

我写了这段代码:

import numpy as np
from scipy import optimize

def main():
    """
    solving a regular constrained optimization problem    
    max ln(cons[0]) + ln(cons[1]) 
    st. prices[0]*cons[0] + prices[1]*cons[1] <= I         
    """    
   
    prices = np.array([4.0, 6.0])
    I = 40.0
   
    util = lambda cons: np.dot( np.log(cons))  #define utility function
    budget = lambda cons: I - np.dot(prices, cons)   #define the budget constraint
    
    initval = 40.0*np.ones(2)    #set the initial guess for the algorithm
    
    res = optimize.minimize(lambda x: -util(x), initval, method='slsqp', 
                            constraints={'type':'ineq', 'fun':budget}, 
                            tol=1e-9)
    assert res['success'] == True
           
    
    print(res)

不幸的是,我的代码没有打印任何解决方案。你能帮我弄清楚为什么吗?

您的代码会产生类型错误,因为 np.dot 需要两个参数,请参阅您的 utils 函数的定义。因此,使用

# is the same as np.dot(np.ones(2), np.log(cons))
utils = lambda cons: np.sum(np.log(cons))

相反。