Python data fitting power function y=ax ^ b

from scipy.optimize import curve_fit
import numpy as np
import matplotlib.pyplot as plt
#power function fitting 
xdata = [2,3,4,5,6,7]
ydata = [2400,5300,8000,9700,10700,11200]
plt.plot(xdata,ydata,'b-')
###define a fitting function, y = a * x^b ###
def target_func(x, a, b):
return a * (x ** b)
###using fitting functions to obtain eigenvalues ###
popt, pcov = curve_fit(target_func, xdata, ydata)
### R ^2 calculations ###
calc_ydata = [target_func(i, popt[0], popt[1]) for i in xdata]
res_ydata = np.array(ydata) - np.array(calc_ydata)
ss_res = np.sum(res_ydata ** 2)
ss_tot = np.sum((ydata - np.mean(ydata)) ** 2)
r_squared = 1 - (ss_res / ss_tot)
#fitted values 
y = [target_func(i,popt[0],popt[1]) for i in xdata]
plt.plot(xdata,y,'r--')
plt.show()
###output results ###
print("a = %f  b = %f   R2 = %f" % (popt[0], popt[1], r_squared))
print(ydata, calc_ydata)

Related articles