python - scipy.optimize.leastsq 有界约束

标签 python optimization scipy mathematical-optimization

我正在 scipy/numpy 中寻找一个优化例程,它可以解决非线性最小二乘类型问题(例如,将参数函数拟合到大型数据集),但包括边界和约束(例如,最小值和最大值)待优化参数)。目前我正在使用 mpfit 的 python 版本(从 idl 翻译...):这显然不是最佳的,虽然它工作得很好。

python/scipy/etc 中的高效例程可能会很棒! 这里非常欢迎任何意见:-)

谢谢!

最佳答案

scipy.optimize.least_squares在 scipy 0.17 中(2016 年 1 月) 处理边界;使用它,而不是这个 hack。


有界约束可以很容易地变成二次的, 并与其余部分一起被最小化。
假设您要最小化 10 个平方和 Σ f_i(p)^2, 所以你的 func(p) 是一个 10 向量 [f0(p) ... f9(p)],
并且还希望 0 <= p_i <= 1 用于 3 个参数。
考虑“浴缸函数” max( - p, 0, p - 1 ), 这是 0 内 0 .. 1 和正外,就像一个\_____/浴缸。
如果我们给 leastsq 13 长的向量

[ f0(p), f1(p), ... f9(p), w*tub(p0), w*tub(p1), w*tub(p2) ]

如果 w = 100,它将最小化手数的平方和: 浴缸将约束 0 <= p <= 1。 一般 lo <= p <= hi 类似。
以下代码只是一个运行 leastsq 的包装器 与例如这样一个 13 长的向量要最小化。

# leastsq_bounds.py
# see also test_leastsq_bounds.py on gist.github.com/denis-bz

from __future__ import division
import numpy as np
from scipy.optimize import leastsq

__version__ = "2015-01-10 jan  denis"  # orig 2012


#...............................................................................
def leastsq_bounds( func, x0, bounds, boundsweight=10, **kwargs ):
    """ leastsq with bound conatraints lo <= p <= hi
    run leastsq with additional constraints to minimize the sum of squares of
        [func(p) ...]
        + boundsweight * [max( lo_i - p_i, 0, p_i - hi_i ) ...]

    Parameters
    ----------
    func() : a list of function of parameters `p`, [err0 err1 ...]
    bounds : an n x 2 list or array `[[lo_0,hi_0], [lo_1, hi_1] ...]`.
        Use e.g. [0, inf]; do not use NaNs.
        A bound e.g. [2,2] pins that x_j == 2.
    boundsweight : weights the bounds constraints
    kwargs : keyword args passed on to leastsq

    Returns
    -------
    exactly as for leastsq,
http://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.leastsq.html

    Notes
    -----
    The bounds may not be met if boundsweight is too small;
    check that with e.g. check_bounds( p, bounds ) below.

    To access `x` in `func(p)`, `def func( p, x=xouter )`
    or make it global, or `self.x` in a class.

    There are quite a few methods for box constraints;
    you'll maybe sing a longer song ...
    Comments are welcome, test cases most welcome.

"""
    # Example: test_leastsq_bounds.py

    if bounds is not None  and  boundsweight > 0:
        check_bounds( x0, bounds )
        if "args" in kwargs:  # 8jan 2015
            args = kwargs["args"]
            del kwargs["args"]
        else:
            args = ()
#...............................................................................
        funcbox = lambda p: \
            np.hstack(( func( p, *args ),
                        _inbox( p, bounds, boundsweight ))) 
    else:
        funcbox = func
    return leastsq( funcbox, x0, **kwargs )


def _inbox( X, box, weight=1 ):
    """ -> [tub( Xj, loj, hij ) ... ]
        all 0  <=>  X in box, lo <= X <= hi
    """
    assert len(X) == len(box), \
        "len X %d != len box %d" % (len(X), len(box))
    return weight * np.array([
        np.fmax( lo - x, 0 ) + np.fmax( 0, x - hi )
            for x, (lo,hi) in zip( X, box )])

# def tub( x, lo, hi ):
#     """ \___/  down to lo, 0 lo .. hi, up from hi """
#     return np.fmax( lo - x, 0 ) + np.fmax( 0, x - hi )

#...............................................................................
def check_bounds( X, box ):
    """ print Xj not in box, loj <= Xj <= hij
        return nr not in
    """
    nX, nbox = len(X), len(box)
    assert nX == nbox, \
        "len X %d != len box %d" % (nX, nbox)
    nnotin = 0
    for j, x, (lo,hi) in zip( range(nX), X, box ):
        if not (lo <= x <= hi):
            print "check_bounds: x[%d] %g is not in box %g .. %g" % (j, x, lo, hi)
            nnotin += 1
    return nnotin

关于python - scipy.optimize.leastsq 有界约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9878558/

相关文章:

python - 访问 kivy 弹出父级

python - pandas 中的 dcast 和聚合长度

linux - Linux inotify API 的效率如何?

MySQL - 可以利用 order by desc limit 1 来优化 3 个子查询的查询来重试最新记录吗?

optimization - 优化的汇编代码 (BLAS)

python - PageRank 计算中矩阵向量积的稀疏矩阵

python - TypeError : src is not a numpy array, 既不是标量。无流

python - PyQt - 将 QAction 连接到函数

python - python中最快的成对距离度量

python - 如何使用 numpy 按季度分组并计算数组的平均值?