【发布时间】:2020-07-12 05:13:12
【问题描述】:
我正在尝试使用scipy curve_fit 将函数y= 1-a(1-bx)**n 拟合到一些实验数据中。该模型仅在 y>0 时存在,因此我剪裁计算值以强制执行此操作。
代码如下所示
import numpy as np
import scipy.optimize
import matplotlib.pyplot as plt
# Driver function for scipy.minimize
def driver_func(x, xobs, yobs):
# Evaluate the fit function with the current parameter estimates
ynew = myfunc(xobs, *x)
yerr = np.sum((ynew - yobs) ** 2)
return yerr
# Define function
def myfunc(x, a, b, n):
y = 1.0 - a * np.power(1.0 - b * x, n)
y = np.clip(y, 0.00, None )
return y
if __name__ == "__main__":
# Initialise data
yobs = np.array([0.005, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.004,
0.048, 0.119, 0.199, 0.277, 0.346, 0.395, 0.444, 0.469,
0.502, 0.527, 0.553, 0.582, 0.595, 0.603, 0.612, 0.599])
xobs = np.array([0.013, 0.088, 0.159, 0.230, 0.292, 0.362, 0.419, 0.471,
0.528, 0.585, 0.639, 0.687, 0.726, 0.772, 0.814, 0.854,
0.889, 0.924, 0.958, 0.989, 1.015, 1.045, 1.076, 1.078])
# Initial guess
p0 = [2.0, 0.5, 2.0]
# Check fit pre-regression
yold = myfunc(xobs, *p0)
plt.plot(xobs, yobs, 'ko', label='data', fillstyle='none')
plt.plot(xobs, yold, 'g-', label='pre-fit: a=%4.2f, b=%4.2f, n=%4.2f' % tuple(p0))
# Fit curve using SCIPY CURVE_FIT
try:
popt, pcov = scipy.optimize.curve_fit(myfunc, xobs, yobs, p0=p0)
except:
print("Could not fit data using SCIPY curve_fit")
else:
ynew = myfunc(xobs, *popt)
plt.plot(xobs, ynew, 'r-', label='post-curve_fit: a=%4.2f, b=%4.2f, n=%4.2f' % tuple(popt))
# Fit curve using SCIPY MINIMIZE
res = scipy.optimize.minimize(driver_func, p0, args=(xobs, yobs), method='Nelder-Mead')
ynw2 = myfunc(xobs, *res.x)
plt.plot(xobs, ynw2, 'y-', label='post-minimize: a=%4.2f, b=%4.2f, n=%4.2f' % tuple(res.x))
plt.legend()
plt.show()
我也使用 SCIPY MINIMIZE 来实现同样的目的。如下图所示,MINIMIZE 有效,但 CURVE_FIT 基本上用完评估并放弃,即使开始的猜测与 MINIMIZE 解决方案相差不远(至少在视觉上)。希望有任何关于为什么 curve_fit 似乎在这里不起作用的想法。
谢谢!
更新: 在 mikuszefski 的 cmets 之后,我做了以下调整 1. 去掉fit函数中的裁剪,如下:
def myfunc_noclip(x, a, b, n):
y = 1.0 - a * np.power(1.0 - b * x, n)
return y
-
通过删除低于阈值的数据来引入裁剪数组
ymin = 0.01 xclp = xobs[np.where(yobs >= ymin)] yclp = yobs[np.where(yobs >= ymin)] -
改进了最初的猜测(再次直观地)
p0 = [1.75, 0.5, 2.0] -
更新了对 curve_fit 的调用
popt, pcov = scipy.optimize.curve_fit(myfunc_noclip, xclp, yclp, p0=p0)
但这似乎没有帮助,如下图所示:
stackoverflow 上的其他帖子似乎表明 scipy curve_fit 在拟合参数之一是指数的情况下拟合曲线有问题,例如
SciPy curve_fit not working when one of the parameters to fit is a power
所以我猜我有同样的问题。虽然不知道如何解决它......
【问题讨论】:
标签: python-3.x curve-fitting scipy-optimize