繁体   English   中英

错误的指数拟合与`scipy.optimize.curve_fit`

[英]Wrong exponential fit with `scipy.optimize.curve_fit`

我正在尝试对一些数据进行指数拟合,但似乎无法强迫scipy.optimize.curve_fit给我带来令人愉悦的结果。

我将代码简化为以下示例,包括根据经验得出的与数据拟合的手册。

import matplotlib.pylab as plt
import numpy
import scipy.stats

x = [25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42,
     43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60,
     61, 62, 63, 64]
y = [9, 9, 10, 10, 10, 10, 11, 11, 11, 11, 12, 12, 12, 12, 13, 13, 13, 14, 14,
     14, 14, 15, 15, 16, 16, 17, 17, 18, 19, 20, 21, 22, 24, 25, 27, 30, 31,
     32, 37, 37]

def fitting_function(x, a, b, c):
    return a * numpy.exp(b * x) + c

plt.plot(x, y, 'o', label='Original data')
OptimalValues, Covariance = scipy.optimize.curve_fit(fitting_function, x, y)
plt.plot(x, fitting_function(x, *OptimalValues), '-',
         label='Fitted Curve (%0.2e*e^%sx+%0.2e)' % (OptimalValues[0],
                                              OptimalValues[1],
                                              OptimalValues[2]))
ManualFit = [0.1 * numpy.exp(0.09 * i) + 8 for i in x]
plt.plot(x, ManualFit, '-', label='Manual Fit (%s*e^%sx+%s)' % (0.1, 0.09, 8))
plt.legend(loc='best')
plt.show()

上面代码的结果

根据此处有关堆栈溢出的其他答案,一个明显的解决方案是为curve_fit提供合理的初始猜测。 如果我通过将下面的行放在我的代码的相应位置(第16和17行)来执行此操作,则解释器会抱怨ValueError因为它以某种方式试图将guess广播到len(x)len(y0 (即操作数不能为与形状(0)(40)一起广播

guess = (0.1, 0.1, 10)
OptimalValues, Covariance = scipy.optimize.curve_fit(fitting_function, x, y,
                                                     p0=guess)

在这种情况下,如何获取scipy.optimize.curve_fit给我有意义的输出?

将您的xy列表转换为numpy数组,它将正常工作。 我发现要获得满意的拟合度,您需要包括初始猜测。 因此,此代码:

import matplotlib.pylab as plt
import numpy
import scipy.stats

x = numpy.array([25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42,
     43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60,
     61, 62, 63, 64])
y = numpy.array([9, 9, 10, 10, 10, 10, 11, 11, 11, 11, 12, 12, 12, 12, 13, 13, 13, 14, 14,
     14, 14, 15, 15, 16, 16, 17, 17, 18, 19, 20, 21, 22, 24, 25, 27, 30, 31,
     32, 37, 37])

def fitting_function(x, a, b, c):
    return a * numpy.exp(b * x) + c

plt.plot(x, y, 'o', label='Original data')

guess =(0.1,0.1,10)
OptimalValues, Covariance = scipy.optimize.curve_fit(fitting_function, x, y,
                                                     p0=guess)

plt.plot(x, fitting_function(x, *OptimalValues), '-',
         label='Fitted Curve (%0.2e*e^%sx+%0.2e)' % (OptimalValues[0],
                                              OptimalValues[1],
                                              OptimalValues[2]))
ManualFit = [0.1 * numpy.exp(0.09 * i) + 8 for i in x]
plt.plot(x, ManualFit, '-', label='Manual Fit (%s*e^%sx+%s)' % (0.1, 0.09, 8))
plt.legend(loc='best')
plt.show()

产生此图:

在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM