Python 用平方根函数拟合问题数据
我尝试使用python和模块scipy.optimize来适应平方根函数。用于打印和拟合的代码如下所示Python 用平方根函数拟合问题数据,python,curve-fitting,data-fitting,scipy-optimize,Python,Curve Fitting,Data Fitting,Scipy Optimize,我尝试使用python和模块scipy.optimize来适应平方根函数。用于打印和拟合的代码如下所示 def curve(x, a, b): return np.sqrt(a+b*x) xaxis = np.linspace(30, 1400, 10000) farbe = ['tab:green', 'tab:orange', 'tab:blue'] fill = ['left', 'top', 'none'] k = 0 for i in data: popt, p
def curve(x, a, b):
return np.sqrt(a+b*x)
xaxis = np.linspace(30, 1400, 10000)
farbe = ['tab:green', 'tab:orange', 'tab:blue']
fill = ['left', 'top', 'none']
k = 0
for i in data:
popt, pcov = curve_fit(curve, data[i].velo, data[i].avgFR)
plt.errorbar(data[i].velo, data[i].avgFR,data[i].avgFRError, xerr=None,
fmt="o", fillstyle = fill[k],alpha = 0.9,markersize=8,
markeredgewidth=2,
linewidth=3, # width of plot line
elinewidth=2,# width of error bar line
capsize=5, # cap length for error bar
capthick=1, # cap thickness for error bar
label = str(i),
color = farbe[k])
plt.plot(xaxis, curve(xaxis, *popt),color = farbe[k], linewidth = 3)
k += 1
#plt.xscale('log')
plt.legend()
plt.show()
如果我执行脚本,则拟合看起来是这样的。出什么事了?有没有更好的方法用平方根函数拟合我的数据
编辑:
我得到以下信息:
__main__:2: RuntimeWarning: invalid value encountered in sqrt
__main__:2: RuntimeWarning: invalid value encountered in sqrt
__main__:2: RuntimeWarning: invalid value encountered in sqrt
发生的情况是:
a+b*x<0
可以为拟合设置边界
在这种情况下,您可以检查是否发生了这种不平等,并返回与您的数据非常不同的值
您可以使用其他拟合例程,也许
lmfit
会有所帮助。我怀疑,在对给定数据的模型参数(a,b)进行优化期间,优化器被迫在平方根ie下计算负数
f=sqrt(a+bx),其中a+bx<0
如果是这种情况,可以通过将bounds
参数传递到curve fit
并强制执行b>0
(自x>0起)来解决此问题
这将把问题限制在
0我知道这不是最优雅的解决方案,但至少它是有效的。我没有拟合sqrt数据,而是计算数据的平方,并用线性函数拟合
看起来不错 当sqrt函数的输入为负时,您将得到该警告。您可能希望通过指定curve\u fit
函数的边界来约束数据。
popt, pcov = curve_fit(curve, data[i].velo, data[i].avgFR,bounds=(0, [1, 1]))