python - 曲线拟合与 python 错误

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

我正在尝试使我的数据适合 (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)。然后情节如下所示:

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

关于python - 曲线拟合与 python 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43231348/

相关文章:

python - 拟合单调曲线(最好在 python 中)

python - 使用 Python 请求与 suiteCRM API V7.9 交互

python - 获取PCAP文件中的所有ip

python - @property 在 Django 中的 models.py 中有两个函数

Python urlopen Windows 身份验证

python - 对数正态分布变量,求似然度

python - 绘制给定数据集的功率谱密度时需要 abs () 方法

python - 如何将反锯齿函数拟合到曲线或绘图?

matlab - 如何使用 Matlab 的 polyfit 获得正确的曲线拟合?

r - 玩完美俄罗斯方 block : how to align and scale two curves using scaling and translation?