python 3.x - new error in old code in numpy exp -
recently working on data able obtain curve using curve_fit after saving plot , values obtained returned same code later find not work.
#! python 3.5.2 import numpy np import matplotlib.pyplot plt import scipy.stats scipy.optimize import curve_fit data= np.array([ [24, 0.176644513], [27, 0.146382841], [30, 0.129891534], [33, 0.105370908], [38, 0.077820511], [50, 0.047407538]]) x, y = np.array([]), np.array([]) val in data: x = np.append(x, val[0]) y = np.append(y, (val[1]/(1-val[1]))) def f(x, a, b): return (np.exp(-a*x)**b) # original , b values obtained = -0.2 # after rounding b = -0.32 # after rounding plt.scatter(x, y) xcurve = np.linspace(x[0], x[-1], 500) plt.plot(xcurve, f(xcurve,a,b), ls='--', color='k', lw=1) plt.show() # original code values = b = 1 popt, pcov = curve_fit(f, x, y, (a, b))
whereas, curve_fit returned values a, b = -0.2, -0.32 returns: warning (from warnings module): file "c:/users ... line 22 return (np.exp(-a*x)**b) runtimewarning: overflow encountered in exp
the code far aware did not change. thanks
without knowing changed in code, hard changed between state of "working" , "not working". may changes in version of scipy used give different results: there have changes underlying implementation in curve_fit()
on past few years.
but also: curve_fit()
(and underlying python , fortran code uses) requires reasonably initial guesses parameters many problems work @ all. bad guesses parameters, many problems fail.
exponential decay problems seem challenging levenberg-marquardt algorithm (and implementations used curve_fit()
, , require reasonable starting points. it's easy part of parameter space function evaluates zero, , changes in parameter values have no effect.
if possible, if problem involves exponential decay, helpful work in log space. is, model log(f)
, not f
itself. problem in particular, model function exp(-a*x)**b
. mean? a
, b
will correlated.
in addition, may find lmfit
helpful. has model
class curve-fitting, using similar underlying code, allows fixing or setting bounds on of parameters. example problem (approximately):
import numpy np import matplotlib.pyplot plt import scipy.stats scipy.optimize import curve_fit import lmfit data= np.array([ [24, 0.176644513], [27, 0.146382841], [30, 0.129891534], [33, 0.105370908], [38, 0.077820511], [50, 0.047407538]]) x, y = np.array([]), np.array([]) val in data: x = np.append(x, val[0]) y = np.append(y, (val[1]/(1-val[1]))) def f(x, a, b): print("in f: a, b = " , a, b) return (np.exp(-a*x)**b) fmod = lmfit.model(f) params = fmod.make_params(a=-0.2, b=-0.4) # set bounds on parameters params['a'].min = -2 params['a'].max = 0 params['b'].vary = false out = fmod.fit(y, params, x=x) print(out.fit_report()) plt.plot(x, y) plt.plot(x, out.best_fit, '--') plt.show()
Comments
Post a Comment