为什么 scipy.optimize.curve_fit 无法正确拟合数据?

2023-11-30

一段时间以来我一直在尝试使用函数来拟合某些数据scipy.optimize.curve_fit但我确实有困难。我真的看不出这行不通的任何原因。

# encoding: utf-8
from __future__ import (print_function,
                        division,
                        unicode_literals,
                        absolute_import,
                        with_statement)
import numpy as np
from scipy.optimize import curve_fit
import matplotlib.pyplot as mpl

x, y, e_y = np.loadtxt('data.txt', unpack=True)

def f(x, a, k):
    return (1/(np.sqrt(1 + a*((k-x)**2))))

popt, pcov = curve_fit(f, x, y, maxfev = 100000000)

mpl.plot(x, f(x, *popt), 'r-', label='Fit')
mpl.plot(x, y, 'rx', label='Original')
mpl.legend(loc='best')
mpl.savefig('curve.pdf')
print(popt)

# correct values which should be calculated
# a=0.003097
# k=35.4

Here is the plot-image which is produced by upper code: enter image description here

data.txt:
#x      y       e_y
4.4     0.79    0.13
19.7    4.9     0.8
23.5    7.3     1.2
29.7    17      2.79
30.7    21.5    3.52
34      81      13.28
34.6    145     23.77
35.4    610     100
36.3    115     18.85
38.1    38      6.23
43.7    14      2.3
56.2    6.2     1.02
64.7    4.6     0.75
79.9    3.2     0.52
210     0.98    0.16

首先尽量不要增加maxfev如此之大,这通常表明其他地方出了问题!玩玩我可以通过以下添加来适应:

def f(x, b, a, k):
    return (b/(np.sqrt(1 + a*((k-x)**2))))

popt, pcov = curve_fit(f, x, y, p0=[20, 600.0, 35.0])

首先给出您给出的拟合函数的最大值为 1,因为您数据中的峰值是 600,所以它永远不会拟合。所以我添加了一个整体因素b。其次,尝试帮助可怜的老curve_fit。如果通过肉眼你可以看到它的峰值x~35然后通过告诉它p0。这需要对函数如何工作有一定的直觉,但如果您要使用曲线拟合函数,这一点非常重要。

enter image description here

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

为什么 scipy.optimize.curve_fit 无法正确拟合数据? 的相关文章

随机推荐