[抱歉,我是python和堆栈流的新手。所以我不能发布图片。
我想用python中的curve_fit函数进行幂定律回归。但是结果对我来说很奇怪。我使用excel进一步检查。两者之间看起来差别很大。黑线是来自curve_fit的结果,红线是来自excel的结果。有人能让我知道其中的区别吗?谢谢!
x=[164000,400,13000,700,57000,108,12000]
y=[0.011970,0.000098,0.066100,0.004300,0.042600,0.000061,0.002858 ]
def f(x,a,b):
return a*x**b
popt,pocv=curve_fit(f,x,y)
ax.set_xscale("log")
ax.set_yscale("log")
ax.set_ylim(0.00001,0.1)
ax.set_xlim(10,1000000)
ax.scatter(x,y)
px=np.linspace(10,1000000,1000)
#parameter form curve_fit
py=a*px**b
[enter image description here][1]
#parameter from excel
pyy=3E-6*px**0.8305
ax.loglog(px,pyy,color="red")
ax.loglog(px,py,color="k")
您正在对数日志空间中绘制数据的事实应该为适合于日志空间提供一个很好的提示。即,将np.log(a*x**b)
设置为np.log(y)
。可以实际运行并很合适的脚本修改如下:
import numpy as np
from scipy.optimize import curve_fit
import matplotlib.pyplot as plt
x=[164000,400,13000,700,57000,108,12000]
y=[0.011970,0.000098,0.066100,0.004300,0.042600,0.000061,0.002858 ]
def f(x, a, b):
return np.log(a*x**b)
popt,pcov=curve_fit(f, x, np.log(y), [1.e-6, 0.9])
ax = plt.gca()
ax.set_xscale("log")
ax.set_yscale("log")
ax.set_ylim(0.00001,0.1)
ax.set_xlim(10,1000000)
ax.scatter(x,y)
px = np.linspace(10,1000000,1000)
a, b = popt
print("Parameters: a=%g, b=%g" % (a, b))
#parameter form curve_fit
py=a*px**b
#parameter from excel
pyy=3e-6*px**0.8305
ax.loglog(px,pyy, color="red")
ax.loglog(px,py, color="k")
plt.show()
始终确保提供参数的初始值,并确保打印出结果。举例来说,运行此命令将打印出Parameters: a=2.78612e-06, b=0.829763
并显示两条预测线几乎彼此重叠。
为了获得更好的曲线拟合体验,您可能会发现lmfit
(https://lmfit.github.io/lmfit-py/)很有用(是的,我是第一作者,有偏见)。使用lmfit
,您的适合范围可能是:
import numpy as np
from scipy.optimize import curve_fit
import matplotlib.pyplot as plt
from lmfit import Model
x=[164000,400,13000,700,57000,108,12000]
y=[0.011970,0.000098,0.066100,0.004300,0.042600,0.000061,0.002858 ]
def f(x, a, b):
return np.log(a*x**b)
model = Model(f)
params = model.make_params(a=1.e-6, b=0.9)
result = model.fit(np.log(y), params, x=x)
print(result.fit_report())
px = np.linspace(10,1000000,1000)
plt.scatter(x,y)
plt.loglog(px, np.exp(result.eval(x=px)), color="k")
plt.show()
请注意,对于lmfit,参数将使用您的f()
模型函数中的名称进行命名。这将打印出适合的报告,其中包括估计的不确定性:
[[Model]]
Model(f)
[[Fit Statistics]]
# fitting method = leastsq
# function evals = 16
# data points = 7
# variables = 2
chi-square = 14.7591170
reduced chi-square = 2.95182340
Akaike info crit = 9.22165592
Bayesian info crit = 9.11347621
[[Variables]]
a: 2.7861e-06 +/- 6.3053e-06 (226.31%) (init = 1e-06)
b: 0.82976271 +/- 0.25700150 (30.97%) (init = 0.9)
[[Correlations]] (unreported correlations are < 0.100)
C(a, b) = -0.958