使用 Scipy 进行曲线拟合会导致意外结果
我有一个可以适合给定函数的数据集。我使用 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()
如有任何帮助,我们将不胜感激。这是供参考的data.txt
:
X | Y |
---|---|
-0.523598776 | 0.530580093 |
-0.436332313 | 1.016423844 |
-0.34906585 | 6.38245854 |
-0.261799388 | 18.70139225 |
-0.174532925 | 30.7389007 |
0.174532925 | 13.59465343 |
0.261799388 | 4.011313119 |
0.34906585 | 0.805865977 |
0.436332313 | 0.50894953 |
0.523598776 | 0.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):
And here is what I got from Matplotlib:
Any help would be appreciated. This is the data.txt
for reference:
X | Y |
---|---|
-0.523598776 | 0.530580093 |
-0.436332313 | 1.016423844 |
-0.34906585 | 6.38245854 |
-0.261799388 | 18.70139225 |
-0.174532925 | 30.7389007 |
0.174532925 | 13.59465343 |
0.261799388 | 4.011313119 |
0.34906585 | 0.805865977 |
0.436332313 | 0.50894953 |
0.523598776 | 0.253654518 |
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您在
x==b
处有一个奇点(您的函数趋于无穷大)。这使得curve_fit
很难找到“交叉”任何数据点的b
值。由于您的数据大约以零为中心,因此您会更幸运地提供一个初始值,例如You have a singularity at
x==b
(your function tends to infinity). That makes it very difficult forcurve_fit
to find a value ofb
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