具有平方根函数的问题数据拟合

问题描述 投票:0回答:3

我尝试使用python和模块scipy.optimize将this experimental data拟合为平方根函数。绘制和拟合的代码如下所示。

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()

如果执行脚本,则适合的外观类似于this。怎么了?有没有更好的方法可以用平方根函数拟合数据?

编辑:我收到以下消息:

__main__:2: RuntimeWarning: invalid value encountered in sqrt
__main__:2: RuntimeWarning: invalid value encountered in sqrt
__main__:2: RuntimeWarning: invalid value encountered in sqrt
python curve-fitting data-fitting scipy-optimize
3个回答
0
投票

发生的是:a+b*x < 0

您可以设置适合范围。

您可以检查这种不平等是否发生,并且在这种情况下返回的值与您的数据非常不同。

您可以使用其他拟合例程,也许lmfit会有所帮助。


0
投票

我怀疑在给定数据的情况下对模型参数(a,b)进行优化时,优化器被迫求平方根下的负数,即。

f = sqrt(a + bx),其中a + bx <0

如果是这种情况,您可以通过将bounds参数传递给curve fit并强制执行该b>0(从x> 0开始)来解决该问题。

popt, pcov = curve_fit(curve, data[i].velo, data[i].avgFR,bounds=(0, [1, 1]))

这会将问题限制为0 <= a <= 1, 0 <= b <= 1。确保为您的问题选择适当的界限。祝你好运!


0
投票

我知道这不是最优雅的解决方案,但至少它能起作用。我不想用sqrt数据拟合来计算数据的平方并用线性函数拟合the result it self看起来不错。

© www.soinside.com 2019 - 2024. All rights reserved.