使用 Scipy 进行曲线拟合会导致意外结果

发布于 2025-01-17 04:29:47 字数 1548 浏览 3 评论 0原文

我有一个可以适合给定函数的数据集。我使用 Desmos 图形计算器进行了计算,并得到了预期的结果。但是当我使用 Matplotlib 实现它时,我得到了一条完全不同的曲线,并且我无法找出代码中的错误。这是我的代码:

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

data = np.loadtxt('data.txt')


def func(x, a, b):
    return a/(np.sin((x-b)/2))**4

x = data[:, 0]
y = data[:, 1]

popt, pcov = curve_fit(func, x, y)

plt.plot(x, y, 'ko', label="Observed data points")


plt.plot(x, func(x, *popt), 'r-', label="Fitted Curve")


plt.legend()
plt.show()

这是预期的图(使用 Desmos 绘制): 在此处输入图像描述

以下是我从 Matplotlib 获得的内容: 在此处输入图像描述

如有任何帮助,我们将不胜感激。这是供参考的data.txt

XY
-0.5235987760.530580093
-0.4363323131.016423844
-0.349065856.38245854
-0.26179938818.70139225
-0.17453292530.7389007
0.17453292513.59465343
0.2617993884.011313119
0.349065850.805865977
0.4363323130.50894953
0.5235987760.253654518

I have a data set which I can fit to a given function. I did it using Desmos graphing calculator and got the expected results. But when I implement it using Matplotlib, I get a totally different curve and I can't figure out the error in my code. Here is my code:

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

data = np.loadtxt('data.txt')


def func(x, a, b):
    return a/(np.sin((x-b)/2))**4

x = data[:, 0]
y = data[:, 1]

popt, pcov = curve_fit(func, x, y)

plt.plot(x, y, 'ko', label="Observed data points")


plt.plot(x, func(x, *popt), 'r-', label="Fitted Curve")


plt.legend()
plt.show()

Here is the expected plot (plotted using Desmos): enter image description here

And here is what I got from Matplotlib: enter image description here

Any help would be appreciated. This is the data.txt for reference:

XY
-0.5235987760.530580093
-0.4363323131.016423844
-0.349065856.38245854
-0.26179938818.70139225
-0.17453292530.7389007
0.17453292513.59465343
0.2617993884.011313119
0.349065850.805865977
0.4363323130.50894953
0.5235987760.253654518

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

嗼ふ静 2025-01-24 04:29:48

您在 x==b 处有一个奇点(您的函数趋于无穷大)。这使得 curve_fit 很难找到“交叉”任何数据点的 b 值。由于您的数据大约以零为中心,因此您会更幸运地提供一个初始值,例如

popt, pcov = curve_fit(func, x, y, [0.0, 0.0])

You have a singularity at x==b (your function tends to infinity). That makes it very difficult for curve_fit to find a value of b that "crosses" any of your data points. Since your data is about zero centered, you'll have better luck providing a an initial value such as

popt, pcov = curve_fit(func, x, y, [0.0, 0.0])
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文