如何解决scipy 的指数衰减只给出阶跃函数
我正在尝试对一组数据进行指数拟合:
import matplotlib.pyplot as plt
import numpy as np
import scipy.optimize as opt
def func(x,a,b,c):
return a * np.exp(x / -b) + c
epr_data = np.loadtxt('T2_text',skiprows=1)
time = epr_data[:,1]
intensity = epr_data[:,2]
optimizedParameters,pcov = opt.curve_fit(func,time,intensity)
print(optimizedParameters)
plt.plot(time,intensity,func(time,*optimizedParameters),label="fit")
plt.show()
但我只是得到这个步骤函数和这些参数:
[1.88476367e+05 1.00000000e+00 6.49563230e+03]
以及此错误消息:
OptimizeWarning: Covariance of the parameters could not be estimated
warnings.warn('Covariance of the parameters could not be estimated'
编辑:
我想用强度绘制时间和第一行
编辑 2:
import matplotlib.pyplot as plt
import numpy as np
import scipy.optimize as opt
def func(x,2]
c0 = np.mean(intensity[-10:])
a0 = intensity[0]-c0
th = time[np.searchsorted(-intensity+c0,-0.5*a0)]
b0 = th / np.log(2)
optimizedParameters,p0=(a0,b0,c0))
print(optimizedParameters)
plt.plot(time,label='data')
plt.plot(time,label="fit")
plt.legend()
plt.show()
解决方法
首先,修复您的 plot
函数调用。要通过一次调用绘制两条曲线,您必须为每条曲线提供 x
和 y
值:
plt.plot(time,intensity,time,func(time,*optimizedParameters),label="fit")
对于标签,调用 plot
两次可能更简单:
plt.plot(time,label="data")
plt.plot(time,label="fit")
如果我们有您的数据,解决 curve_fit
生成的警告会更容易。然而,经验表明,curve_fit
使用的参数的默认初始猜测(全为 1)很可能只是一个非常糟糕的猜测。
尝试帮助 curve_fit
为其数值优化例程提供更好的起点。以下代码显示了如何计算 a
、b
和 c
的粗略猜测。使用参数 curve_fit
将这些传递给 p0=(a0,b0,c0)
。
# Assume that the time series is long enough that the tail
# has flattened out to approximately random noise around c.
c0 = np.mean(intensity[-10:])
# This assumes time[0] is 0.
a0 = intensity[0] - c0
# Rough guess of the half-life.
th = time[np.searchsorted(-intensity+c0,-0.5*a0)]
b0 = th / np.log(2)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。