【问题标题】:Python: curve_fit for least squares minimizationPython:用于最小二乘最小化的曲线拟合
【发布时间】:2017-09-22 15:10:10
【问题描述】:

假设我有一个由t 参数化的模型f。我想要t 的最佳值,以使∑ₓ (f(x, t) - y(x))² 最小化。这就是最小二乘优化的目的。

在下面的例子中

from numpy import *
from scipy.optimize import curve_fit

x = arange(100)

t_true = 30
y = 1. / (1 + exp(-(x - t_true) / 5.))

f = lambda x, t: [0. if xi < t else 1. for xi in x]
t_opt, t_cor = curve_fit(f, x, y, p0=(20.))

plot(x, y)
plot(x, f(x, t_opt))

print(t_cor)

为什么我得到t_opt=20 而不是接近t_opt=30

另外,为什么是t_cor=inf?我得到的结果是:

其中蓝色是数据,绿色是拟合模型,但我希望看起来像这样:

我确实预料到了这一点,因为第二张图像的残差平方和肯定小于第一张图像的平方和,并且显然没有局部最小值,优化可能会卡住。那么为什么这不起作用呢?

【问题讨论】:

  • 你想找到x的最佳值(比如xopt),它给出了距离(y(x)-xopt)的最小误差?
  • @SaulloCastro 不,我的模型是函数f,它由t 参数化。我想要t 的最佳值,使∑ₓ (f(x, t) - y(x))² 最小化

标签: python scipy least-squares


【解决方案1】:

curve_fit is a wrapper 周围 least_sq 使用以下错误函数:

 def error(params, x, y):
    return np.sum((func(x, params) - y)**2)

在您的问题中,curve_fit 不起作用,因为您尝试拟合的方程式与您用来生成 y 的方程式非常不同。

适合这种情况的推荐函数是(t 未知):

def f(x, t):
    return 1. / (1 + exp(-(x - t) / 5.))

有了这个推荐的拟合函数,curve_fit 就可以了,或者你可以直接使用scipy.optimize.leastsq,比如:

import numpy as np
from numpy import exp
from scipy.optimize import leastsq, curve_fit

x = np.arange(100)

t_true = 30

def f(x, t):
    return 1. / (1 + exp(-(x - t) / 5.))

y = f(x, t_true)

def error(t, x, y):
    return np.sum((f(x, t) - y)**2)

t_opt, t_cor = leastsq(error, args=(x, y), x0=1.)
print('least_sq', t_opt, t_cor)

t_opt2, t_cor2 = curve_fit(f, x, y, p0=(0,))
print('curve_fit', t_opt2, t_cor2)

这会给你:

least_sq [ 30.00000007] 2
curve_fit [ 30.] [[ 0.]]

【讨论】:

  • 谢谢,但我的问题是为什么 curve_fit 不起作用 :) 关键是,我需要 Levenberg-Marquardt 算法(curve_fit 可以使用)进行基准测试,但文档leastsq 没有说明它使用哪种算法。
  • @theV0ID 如果您在curve_fit 中使用上面相同的函数f(x, t),它应该也可以工作,因为curve_fit 只是leastsq 的包装器
  • @theV0ID 似乎问题出在您传递给curve_fit的函数上
  • 谢谢。 “你试图拟合的方程与你用来生成y的方程非常不同”是什么意思?是不是curve_fit 无法对可靠的梯度进行采样?但是,为什么leastsq 工作呢?换句话说:leastsq 做了什么 curve_fit 不做的事情?
  • @我认为您用于生成数据的方程与拟合方程相差太大。在这种情况下,即使curve_fit 可以为您的拟合方程找到最佳系数,这也不够。这不是curve_fit 的问题 我更新了示例,显示curve_fit 如何给出与leastsq 相同的结果
猜你喜欢
  • 2014-03-05
  • 2013-06-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-29
  • 1970-01-01
相关资源
最近更新 更多