曲线拟合有 python 错误

Curve fitting with python error

我正在尝试使我的数据适合 (cos(x))^nn 的值理论上是 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: invalid value encountered in power after removing the cwd from sys.path.

/usr/lib/python3/dist-packages/scipy/optimize/minpack.py:690: OptimizeWarning: Covariance of the parameters could not be estimated
category=OptimizeWarning)

问题是 cos(x) 可以变成负数,然后 cos(x) ^ n 可以不确定。插图:

np.cos(90)
-0.44807361612917013

例如

np.cos(90) ** 1.7
nan

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

它工作正常,如果你修改你的模型,例如至 a + b * np.cos(c * x + d)。然后情节如下所示:

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

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