首页 文章

拟合指数曲线误差

提问于
浏览
0
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit

def func(x, a, b, c):
    return a * np.exp(-b * x) + c

x =  [333,500,1000,2000,5000,10000]

y = [195.3267, 233.0235, 264.5914,294.8728, 328.3523,345.4688]

popt, pcov = curve_fit(func, x, y)

plt.figure()
plt.plot(x, y, 'ko', label="Original Noised Data")
plt.plot(x, func(x, *popt), 'r-', label="Fitted Curve")
plt.legend()
plt.show()

错误:C:\ Users \ Aidan \ Anaconda3 \ lib \ site-packages \ scipy \ optimize \ minpack.py:794:OptimizeWarning:无法估计参数的协方差类别= OptimizeWarning)-------- -------------------------------------------------- ----------------- TypeError Traceback(最近一次调用last)in()14 plt.figure()15 plt.plot(x,y,'ko',label =“原始噪声数据“)---> 16 plt.plot(x,func(x,* popt),'r - ',label =”Fitted Curve“)17 plt.legend()18 plt.show()in func (x,a,b,c)4 5 def func(x,a,b,c):----> 6返回a * np.exp(-b * x)c 7 8 x = [333,500,1000 ,2000,5000,10000] TypeError:'numpy.float64'对象不能解释为整数

出于某种原因,我无法根据我的数据得到曲线拟合 . 我从这里开始关注指数示例:How to do exponential and logarithmic curve fitting in Python? I found only polynomial fitting

但我使用的是两个数组而不是随机数据 . 我是python的新手!

1 回答

  • 1

    您的代码存在一些问题 .

    • 您使用列表而不是 numpy.ndarraynumpyscipy 例程适用于 numpy.ndarray 并且它们在内部使用它们 . 你也应该使用它们 .

    • 您的数据和功能可能会出现溢出问题,例如在Python3中 np.exp(-1000) 已经近似为零

    • 您正在尝试使用一个不太适合您的数据的函数 . 它看起来更像是指数恢复而不是衰变 .

    以下代码暂时解决了所有这些问题:

    import numpy as np
    import matplotlib.pyplot as plt
    from scipy.optimize import curve_fit
    
    def func(x, a, b, c):
        return a * (1 - np.exp(-b * x)) + c
    
    x =  np.array([333.0,500.0,1000.0,2000.0,5000.0,10000.0]) / 1000
    y = np.array([195.3267, 233.0235, 264.5914,294.8728, 328.3523,345.4688]) / 10
    
    popt, pcov = curve_fit(func, x, y)
    print(popt)
    
    plt.figure()
    plt.plot(x, y, 'ko', label="Original Noised Data")
    plt.plot(x, func(x, *popt), 'r-', label="Fitted Curve")
    plt.legend()
    plt.show()
    

相关问题