拟合指数曲线误差

Fitted Exponential Curve Error

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()

Error: C:\Users\Aidan\Anaconda3\lib\site-packages\scipy\optimize\minpack.py:794: OptimizeWarning: Covariance of the parameters could not be estimated
category=OptimizeWarning)

--------------------------------------------------------------------------- TypeError Traceback (most recent call last) in () 14 plt.figure() 15 plt.plot(x, y, 'ko', label="Original Noised Data") ---> 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 return a * np.exp(-b * x) + c 7 8 x = [333,500,1000,2000,5000,10000]

TypeError: 'numpy.float64' object cannot be interpreted as an integer

出于某种原因,我无法根据我的数据进行曲线拟合。我正在关注这里的指数示例:How to do exponential and logarithmic curve fitting in Python? I found only polynomial fitting

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

您的代码存在一些问题。

  • 您使用列表而不是 numpy.ndarraynumpyscipy 例程旨在与 numpy.ndarray 一起使用,并且它们在内部使用它们。你也应该使用它们。
  • 您的数据和函数可能会出现溢出问题,例如np.exp(-1000) 在 Python3
  • 中已经近似为零
  • 您正在尝试拟合不太可能拟合您的数据的函数。它看起来更像是指数恢复而不是衰减。

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

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()