多元最小二乘法

2024-09-20 07:31:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个优化问题需要在python中解决。总体结构是

def foo(a, b, c, d, e):
    # do something and return one value


def bar(a, b, c, d, e, f, g, h, i, j):
    # do something and return one value


def func():
    return foo(a, b, c, d, e) - bar(a, b, c, d, e, f, g, h, i, j)

我想使用least_squares最小化并返回{}的值,其中平方差是foo和{}之间的最小值。我不知道该如何使用least_squares。在

我试过了:

^{pr2}$

如何使x成为f, g, h, i and j最小值列表的返回值?在


Tags: andreturnfoovaluedefbar结构do
1条回答
网友
1楼 · 发布于 2024-09-20 07:31:39

当前定义问题的方式相当于最大化bar(假设您将func传递给一个最小化函数)。由于不改变参数aefunc基本上是常数与bar的结果之间的差异;由于负号,它将被尝试最大化,因为这样会最小化整个函数。在

我想你想要最小化的是两个函数的绝对值或平方差。我用一个简单的例子来说明,假设函数只返回参数之和:

from scipy.optimize import minimize

def foo(a, b, c, d, e):
    # do something and return one value

    return a + b + c + d + e

def bar(a, b, c, d, e, f, g, h, i, j):
    # do something and return one value
    return a + b + c + d + e + f + g + h + i + j

def func1(x):
    # your definition, the total difference
    return foo(x[0], x[1], x[2], x[3], x[4]) - bar(x[0], x[1], x[2], x[3], x[4], x[5], x[6], x[7], x[8], x[9])

def func2(x):
    # quadratic difference
    return (foo(x[0], x[1], x[2], x[3], x[4]) - bar(x[0], x[1], x[2], x[3], x[4], x[5], x[6], x[7], x[8], x[9]))**2

# Initial values for all variables
x0 = (0, 0, 0, 0, 0, 0.5, 0.5, 0.5, 0.05, 0.5)

# Constraints
# lb = [0,0,0,0,-0.9]
# ub = [1, 100, 1, 0.5, 0.9]
# for illustration, a, b, c, d, e are fixed to 0; that should of course be changed
bnds = ((0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0., 1), (0., 100.), (0, 1), (0, 0.5), (-0.9, 0.9))

res1 = minimize(func1, x0, method='SLSQP', bounds=bnds)
res2 = minimize(func2, x0, method='SLSQP', bounds=bnds)

然后你得到:

^{pr2}$

以及

^{3}$

如上所述,所有参数都将到达上限,以最大化bar,从而最小化{}。在

对于自适应函数func2,您将收到:

res2.fun
5.7408853312979541e-19  # which is basically 0

res2.x
array([ 0.        ,  0.        ,  0.        ,  0.        ,  0.        ,
    0.15254237,  0.15254237,  0.15254237,  0.01525424, -0.47288136])

因此,正如预期的那样,对于这个简单的例子,我们可以选择参数,使这两个函数之间的差值变为0。显然,参数的结果不是唯一的,它们也可能都是0。在

我希望这有助于使您的实际功能发挥作用。在

编辑:

正如您所要求的least_square,这也很好(使用上面的函数定义);那么总的差别就可以了:

from scipy.optimize import least_squares

lb = [0,0,0,0,0,0,0,0,0,-0.9]
ub = [0.1,0.1,0.1,0.1,0.1,1, 100, 1, 0.5, 0.9]
res_lsq = least_squares(func1, x0, bounds=(lb, ub))

然后您将得到与上述相同的结果:

res_lsq.x
array([  1.00000000e-10,   1.00000000e-10,   1.00000000e-10,
         1.00000000e-10,   1.00000000e-10,   1.52542373e-01,
         1.52542373e-01,   1.52542373e-01,   1.52542373e-02,
        -4.72881356e-01])

res_lsq.fun
array([ -6.88463034e-11])  # basically 0

由于5个参数在这个问题中不会改变,所以我会将它们固定到一个特定的值,并且不会将它们传递给优化调用。在

相关问题 更多 >