1

我正在使用 COBYLA 对具有约束的线性目标函数进行成本最小化。我通过为每个包含一个约束来实现下限和上限。

import numpy as np
import scipy.optimize

def linear_cost(factor_prices):
    def cost_fn(x):
        return np.dot(factor_prices, x)
    return cost_fn


def cobb_douglas(factor_elasticities):
    def tech_fn(x):
        return np.product(np.power(x, factor_elasticities), axis=1)
    return tech_fn

def mincost(targets, cost_fn, tech_fn, bounds):

    n = len(bounds)
    m = len(targets)

    x0 = np.ones(n)  # Do not use np.zeros.

    cons = []

    for factor in range(n):
        lower, upper = bounds[factor]
        l = {'type': 'ineq',
             'fun': lambda x: x[factor] - lower}
        u = {'type': 'ineq',
             'fun': lambda x: upper - x[factor]}
        cons.append(l)
        cons.append(u)

    for output in range(m):
        t = {'type': 'ineq',
             'fun': lambda x: tech_fn(x)[output] - targets[output]}
        cons.append(t)

    res = scipy.optimize.minimize(cost_fn, x0,
                                  constraints=cons,
                                  method='COBYLA')

    return res

COBYLA 不尊重上限或下限约束,但确实尊重技术约束。

>>> p = np.array([5., 20.])
>>> cost_fn = linear_cost(p)

>>> fe = np.array([[0.5, 0.5]])
>>> tech_fn = cobb_douglas(fe)

>>> bounds = [[0.0, 15.0], [0.0, float('inf')]]

>>> mincost(np.array([12.0]), cost_fn, tech_fn, bounds)
       x: array([ 24.00010147,   5.99997463])
 message: 'Optimization terminated successfully.'
   maxcv: 1.9607782064667845e-10
    nfev: 75
  status: 1
 success: True
     fun: 239.99999999822359

为什么COBYLA 不尊重第一个因素约束(即上限@ 15)?

4

1 回答 1

5

COBYLA实际上尊重您给予的所有限制。

问题在于cons列表的构建。也就是说,lambda 中的变量和 Python(和 Javascript)中的其他内部作用域函数的绑定是词法的,并且不会以您假设的方式运行:http: //eev.ee/blog/2011/04/24/gotcha- python-scoping-closures/循环结束后,变量lowerupper有值0inf,变量factor有值1,这些值随后被所有 lambda 函数使用。

一种解决方法是将变量的特定值显式绑定到虚拟关键字参数:

for factor in range(n):
    lower, upper = bounds[factor]
    l = {'type': 'ineq',
         'fun': lambda x, a=lower, i=factor: x[i] - a}
    u = {'type': 'ineq',
         'fun': lambda x, b=upper, i=factor: b - x[i]}
    cons.append(l)
    cons.append(u)

for output in range(m):
    t = {'type': 'ineq',
         'fun': lambda x, i=output: tech_fn(x)[i] - targets[i]}
    cons.append(t)

第二种方法是添加一个生成 lambda 的工厂函数。

于 2014-09-23T07:09:46.453 回答