优化有限制

0

的问题

我想到解决约束的优化问题。

max{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)

不幸的是,我的代码不打印的任何解决方案。 你可以帮我找出为什么?

mathematical-optimization python scipy
2021-11-17 08:52:35
1

最好的答案

1

你的代码产生一个类型错误因为 np.dot 希望两个参数,请参阅的定义 utils 功能。 因此,使用

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

代替。

2021-11-17 21:09:35

其他语言

此页面有其他语言版本

Русский
..................................................................................................................
Italiano
..................................................................................................................
Polski
..................................................................................................................
Română
..................................................................................................................
한국어
..................................................................................................................
हिन्दी
..................................................................................................................
Français
..................................................................................................................
Türk
..................................................................................................................
Česk
..................................................................................................................
Português
..................................................................................................................
ไทย
..................................................................................................................
Español
..................................................................................................................
Slovenský
..................................................................................................................