简体   繁体   中英

Exponential Decay Curve fit on Python. Error: Optimizewarning

I am trying to make a curvefit for my data. I am using the exponential function as I need tau (time constant) for further analysis. I am new to Python and trying the scipy curvefit function for the first time. However, I just obtain a straight line and the code gives OptimizeWarning: Covariance of the parameters could not be estimated warnings.warn

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


x = np. array( [ 246, 248, 250, 252, 254,256, 258, 260, 262, 264, 266, 268, 270, 272, 274, 276, 278, 280, 282,284])
y = np.array( [ 6.38954156, 6.32462716 ,6.21843495,5.96263661, 5.66970206, 5.37948873, 5.06358679 ,4.83386528 ,4.64262524, 4.5091623,  4.38658648, 4.46124359, 4.52878251, 4.56084217 ,4.47660524,4.5323503,  4.46626654, 4.58289275, 4.42962004, 4.29622583])

def curvefit( x, a, invtau,c):
      return a * np.exp(-x*invtau)+c
popt, pcov = curve_fit( curvefit, x, y)   #Curvefit
a, invtau, c = popt         #summarize the parameter values
x_new = np.arange(min(x), max(x),1)
y_new = curvefit (x_new, a, invtau, c)
plt.figure()
plt.plot(x, y, label='data')
plt.plot (x_new, y_new, '--', label='fit')
plt.legend (loc='upper right')

I saw that the output of y_new is same for all the rows because of which it gives a straight line.

Question: How to estimate the parameters to make a curvefit for my data?

This is the output I get

Set some good starting values for your fit parameters. The default will be 1 for all parameters ( a , invtau and c ), but especially a and invtau will be far from 1. Then, the optimizer algorithm will fail to find a good minimum.

I tried with

popt, pcov = curve_fit( curvefit, x, y, p0=[1, 1/250, 4])   #Curvefit

which yields a decent fit, and values for a , invtau and c of 4335942530.560109 , 0.0865584128551326 and 4.238729282912057 , respectively.

(Note that I had the starting value for a as 1 , which is still far away from its actual value. But having invtau closer to its actual value, lets the algorithm then also find a good fit for a . It is overall still better to provide more accurate starting values for all parameters, and since you're modeling your data, you probably know what to expect for those values, and use that as a starting point.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM