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
For some reason I am not able to get a curve fit based on my data. I am following the exponential example from here: How to do exponential and logarithmic curve fitting in Python? I found only polynomial fitting
But I am using an two arrays rather than made up random data. I am new to python!
There are a few issues with your code.
numpy.ndarray
: the numpy
and scipy
routines are meant to work with numpy.ndarray
and they use them internally. You should use them as well.np.exp(-1000)
is already approximated to zero in Python3The following code tentatively address all these issues:
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()