![](/img/trans.png)
[英]Why can't SciPy's curve_fit find the covariance/give me sensical parameters for this higher order gaussian function?
[英]Why doesn't Scipy's curve_fit give the correct result for the following problem(s)?
代码:
from scipy.optimize import curve_fit
import numpy as np
from numpy import *
def func(x, a, b):
return ff(x,a,b)
ff= lambda x,a,b: eval("1/(a*x+b)")
xdata = [1 ,2, 4, 6, 8, 10]
ydata = [0.22, 0.1, 0.06, 0.04, 0.03, 0.024]
popt, pcov = curve_fit(func, xdata, ydata)
print('\n', '[a b] for the best fit = ', popt,'\n')
当它运行时它给出
[a b] for the best fit = [ 4.62673137 -0.04794652]
同时根据我的科学计算器(或通过手动解决),答案应该是:
[a b] for the best fit = [ 0.9232 4.05396]
我反复测试了该程序,这不是它没有提供正确结果的唯一示例。
我检查了你的计算:
import matplotlib.pyplot as plt
plt.scatter(xdata, ydata)
plt.scatter(xdata, func(np.array(xdata), 4.62673137, -0.04794652), c='r')
plt.scatter(xdata, func(np.array(xdata), 0.9232, 4.05396), c='g')
plt.show()
并发现curve_fit()
给出了良好的拟合参数。 问题在于您的其他解决方案。
不要使用from X import *
。 在某些情况下,它使代码极难管理。
如果不需要,请不要使用eval()
。 在这种情况下:
def func(x, a, b):
return 1. / (a * x + b)
更短更清晰。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.