scipy-为什么COBYLA不遵守约束?

Mik*_*and 1 scipy lexical-scope

我正在使用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
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

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

pv.*_*pv. 5

COBYLA 在事实上尊重所有你给的范围。

问题出在cons清单的构建上。即,lambda中的变量与Python(和Javascript)中其他内部作用域的函数的绑定是词汇性的,并且不会以您假定的方式运行:http : //eev.ee/blog/2011/04/24/gotcha- python-scoping-closures /循环完成后,变量lowerupper具有值0inf,变量factor具有value 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)
Run Code Online (Sandbox Code Playgroud)

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