I have two columns of data, x and y. I am interested to do power law fit of the form: y=a+b*x^c. Are there packages available in Python which does it?
Power law fit in Python
1.7k Views Asked by Wiz123 AtThere are 2 best solutions below
On
Start by defining a model function
def power(x, a, b, c):
return a + b * x ** c
We can use the curve_fit function from scipy to find the values for a, b, and c which give the best fit.
popt, pcov = curve_fit(power, x, y, p0=initial_guess)
'popt' is a list of the values for a, b, and c which gives the best fit (notice that there is no guarantee a solution exists or that the one you get is the optimal one).
'pcov' is a matrix. The square root of its diagonal is a measure of the uncertainty of the solution.
'initial guess' is a list of three numbers that serve as initial values for a, b, and c in the first iteration of the fitting algorithm. You must provide the values.
Another keyword that you can pass to curve_fit is 'bounds'. This serves to limit the range the algorithm searches for values for the parameters a, b, and c. 'bounds' can take a tuple of two lists. The first list are the bottom limits for each parameter, while the second list is for the top bounds.
Here is an example.
x = [ 2.5, 5. , 10. , 20. , 40. , 160. ]
y = [ 82933.97231252, 195697.01890895, 411424.83454658,
689365.13501311, 1100703.42291616, 3069058.97376933]
initial_guess = [1e4, 1e4, 0.5]
popt, pcov = curve_fit(power, x, y, p0=initial_guess)
You should get
popt = array([-8.38814011e+04, 9.58024081e+04, 6.88182131e-01])
pcov = array([[ 1.49036273e+09, -4.72459139e+08, 8.87583051e+02],
[-4.72459139e+08, 1.72727658e+08, -3.30764877e+02],
[ 8.87583051e+02, -3.30764877e+02, 6.37612550e-04]])
fig, ax = plt.subplots()
ax.plot(x,y, ls='None', marker='.', ms=10)
X = np.linspace(0, 200, 201)
ax.plot(X, power(X, *popt))

The following fits two parameters with scipy least_squares (which is really nice, really powerful); you can easily modify it for a + b x^c --
scipy.optimize.curve_fit is a wrapper for least_squares or leastsq.
If you have some background in statistics, see SO how-to-properly-fit-data-to-a-power-law-in-python.