曲线拟合与python错误

时间:2017-04-05 12:34:24

标签: python scipy curve-fitting scientific-computing function-fitting

我试图将我的数据放到(cos(x))^n。理论上n的价值是2,但我的数据应该给我1.7左右。当我定义我的拟合函数并尝试curve_fit时,我收到错误

def f(x,a,b,c):
   return a+b*np.power(np.cos(x),c)

param, extras = curve_fit(f, x, y)

这是我的数据

x   y               error
90  3.3888756187    1.8408898986
60  2.7662844365    1.6632150903
45  2.137309503     1.4619540017
30  1.5256883339    1.2351875703
0   1.4665463518    1.2110104672

错误如下所示:

  

/usr/local/lib/python3.5/dist-packages/ipykernel_launcher.py:4:   RuntimeWarning:删除后在电源中遇到无效值   来自sys.path的cwd。

     

/usr/lib/python3/dist-packages/scipy/optimize/minpack.py:690:   OptimizeWarning:无法估计参数的协方差   类别= OptimizeWarning)

1 个答案:

答案 0 :(得分:4)

问题是cos(x)可能会变为负值,然后cos(x) ^ n可能会被取消定义。插图:

np.cos(90)
-0.44807361612917013

,例如

np.cos(90) ** 1.7
nan

这会导致您收到两条错误消息。

如果您修改模型,它可以正常工作,例如到a + b * np.cos(c * x + d)。然后情节如下:

enter image description here

下面的代码可以在一些内联注释中找到:

import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit


def f(x, a, b, c, d):

    return a + b * np.cos(c * x + d)

# your data
xdata = [90, 60, 45, 30, 0]
ydata = [3.3888756187, 2.7662844365, 2.137309503, 1.5256883339, 1.4665463518]

# plot data
plt.plot(xdata, ydata, 'bo', label='data')

# fit the data
popt, pcov = curve_fit(f, xdata, ydata, p0=[3., .5, 0.1, 10.])

# plot the result
xdata_new = np.linspace(0, 100, 200)
plt.plot(xdata_new, f(xdata_new, *popt), 'r-', label='fit')
plt.legend(loc='best')
plt.show()