Python Forum
curve fitting matlotlib scipy - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Data Science (https://python-forum.io/forum-44.html)
+--- Thread: curve fitting matlotlib scipy (/thread-29567.html)



curve fitting matlotlib scipy - Cjstarling - Sep-10-2020

Hi, Could someone please advise me how I can improve the fit of my curve such that the fit goes through all my points and resembles the graph below?

from scipy.optimize import curve_fit
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np

m=np.array([155.9,133.7,6.4,57.9])
t=np.array([100,150,200,250])


def exponential(x, a, b):
    return abs(a*(1-2*np.exp(-b*x)))

pars, cov = curve_fit(f=exponential, xdata=t, ydata=m, p0 = [0, 0], bounds=(-np.inf, np.inf))

fig = plt.figure()
ax = fig.add_axes([0, 0, 1, 1])
ax.scatter(t, m, s=50, color='#00b3b3', label='Data')
ax.plot(t, exponential(t, *pars), linestyle='--', linewidth=2, color='black')
[Image: 2227418_orig.gif]

I'm trying to fit the solid line. I'm expecting the fit would be like the dashed line with no abs() in the fit code (although clearly that's not what the data is doing).

Many thanks. Cam


RE: curve fitting matlotlib scipy - Cjstarling - Sep-15-2020

As far as I can tell; my script does fit the points but it is doing it over a far larger region than I would like. I've experimented by changing the bounds, to no effect. I've also experimented with changing the initial estimate p0; varied y values cause the fit to become flat.

Besides the bounds and initial estimate p0, I can't see what the problem would. Do I perhaps need a different type of custom curve fitting?


RE: curve fitting matlotlib scipy - Cjstarling - Sep-15-2020

does the abs() function even work in this sense for fitting(abs(a*(1-2*np.exp(-b*x)))?