使用limfit.minimize在Python中最小化目标函数

我对lmfit.minimize最小化程序包有问题.实际上,我无法为我的问题创建正确的目标函数.

问题定义

>我的函数:yn = a_11 * x1 ** 2 a_12 * x2 ** 2 … a_m * xn ** 2,其中xn-未知数,a_m-
              系数. n = 1..N,m = 1..M
>就我而言,对于x1,..,x5,N = 5;对于y1,y2,y3,M = 3.

我需要找到最佳值:x1,x2,…,x5,以便可以满足y

我的问题:

>错误:ValueError:操作数不能与形状(3,)(3,5)一起广播.
>我是否在Python中正确创建了问题的目标函数?

我的代码:

import numpy as np
from lmfit import Parameters, minimize

def func(x,a):
    return np.dot(a, x**2)

def residual(pars, a, y):
    vals = pars.valuesdict()
    x = vals['x']
    model = func(x,a)
    return y - model

def main():
    # simple one: a(M,N) = a(3,5)
    a = np.array([ [ 0, 0, 1, 1, 1 ],
                   [ 1, 0, 1, 0, 1 ],
                   [ 0, 1, 0, 1, 0 ] ])
    # true values of x
    x_true = np.array([10, 13, 5, 8, 40])
    # data without noise
    y = func(x_true,a)

    #************************************
    # Apriori x0
    x0 = np.array([2, 3, 1, 4, 20])
    fit_params = Parameters()
    fit_params.add('x', value=x0)

    out = minimize(residual, fit_params, args=(a, y))
    print out
if __name__ == '__main__':
    main()

解决方法:

下面的代码直接使用scipy.optimize.minimize()即可解决此问题.注意,随着点yn的增加,您将趋于获得与x_true相同的结果,否则将存在多个解决方案.您可以通过添加边界来最大限度地减少不良约束优化的影响(请参阅下面使用的bounds参数).

import numpy as np
from scipy.optimize import minimize

def residual(x, a, y):
    s = ((y - a.dot(x**2))**2).sum()
    return s

def main():
    M = 3
    N = 5
    a = np.random.random((M, N))
    x_true = np.array([10, 13, 5, 8, 40])
    y = a.dot(x_true**2)

    x0 = np.array([2, 3, 1, 4, 20])
    bounds = [[0, None] for x in x0]
    out = minimize(residual, x0=x0, args=(a, y), method='L-BFGS-B', bounds=bounds)
    print(out.x)

如果M&== N,您还可以使用scipy.optimize.leastsq来完成此任务:

import numpy as np
from scipy.optimize import leastsq

def residual(x, a, y):
    return y - a.dot(x**2)

def main():
    M = 5
    N = 5
    a = np.random.random((M, N))
    x_true = np.array([10, 13, 5, 8, 40])
    y = a.dot(x_true**2)

    x0 = np.array([2, 3, 1, 4, 20])
    out = leastsq(residual, x0=x0, args=(a, y))
    print(out[0])
上一篇:Scipy讲解


下一篇:scipy.optimize.minimize||非线性规划