为什么scipy.optimize.curve_fit不会产生最适合我积分的线?

时间:2013-10-31 18:07:12

标签: python optimization scipy curve-fitting

我有一组数据点,(下面代码中的x和y),我试图通过我的点创建一个最适合的线性线。我正在使用scipy.optimize.curve_fit。我的代码产生一条线,但不是最合适的线。我试过给我的渐变和拦截使用函数模型参数,但每次它产生完全相同的行,不适合我的数据点。

蓝点是我的数据点,红线应该适合:

enter image description here

如果有人能指出我哪里出错了,我将非常感激:

import numpy as np
import matplotlib.pyplot as mpl
import scipy as sp
import scipy.optimize as opt

x=[1.0,2.5,3.5,4.0,1.1,1.8,2.2,3.7]
y=[6.008,15.722,27.130,33.772,5.257,9.549,11.098,28.828]
trialX = np.linspace(1.0,4.0,1000)                         #Trial values of x

def f(x,m,c):                                        #Defining the function y(x)=(m*x)+c
    return (x*m)+c

popt,pcov=opt.curve_fit(f,x,y)                       #Returning popt and pcov
ynew=f(trialX,*popt)                                                  

mpl.plot(x,y,'bo')
mpl.plot(trialX,ynew,'r-')
mpl.show()

2 个答案:

答案 0 :(得分:5)

您也可以使用numpy.polyfit来获得最佳拟合线:

import numpy as np
import matplotlib.pyplot as mpl

x=[1.0,2.5,3.5,4.0,1.1,1.8,2.2,3.7]
y=[6.008,15.722,27.130,33.772,5.257,9.549,11.098,28.828]
trialX = np.linspace(1.0,4.0,1000)                         #Trial values of x

#get the first order coefficients 
fit = np.polyfit(x, y, 1)

#apply 
ynew = trialX * fit[0] + fit[1]                                              

mpl.plot(x,y,'bo')
mpl.plot(trialX,ynew,'r-')
mpl.show()

以下是输出:enter image description here

答案 1 :(得分:2)

编辑:此行为现已在当前版本的scipy中修补,以使.curve_fit更加万无一失:

https://github.com/scipy/scipy/issues/3037


出于某种原因,.curve_fit确实希望输入是一个numpy数组,并且如果你将它传递给常规列表会给你错误的结果(恕我直言,这是意外的行为,可能是一个错误)。将x的定义更改为:

x=np.array([1.0,2.5,3.5,4.0,1.1,1.8,2.2,3.7])

你得到:

enter image description here

我猜测从m*x开始,其中m是一个整数而x是一个列表,它将产生该列表的m个副本,显然你正在寻找的结果!< / p>