Pythonデータフィッティング——べき乗関数y=ax^b


Pythonデータフィッティング——べき乗関数y=ax^b
from scipy.optimize import curve_fit
import numpy as np
import matplotlib.pyplot as plt
#      
xdata = [2,3,4,5,6,7]
ydata = [2400,5300,8000,9700,10700,11200]

plt.plot(xdata,ydata,'b-')

###       , y = a * x^b ###
def target_func(x, a, b):
    return a * (x ** b)

###            ###
popt, pcov = curve_fit(target_func, xdata, ydata)

### R^2   ###
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)

#     
y = [target_func(i,popt[0],popt[1]) for i in xdata]
plt.plot(xdata,y,'r--')
plt.show()
###      ###
print("a = %f  b = %f   R2 = %f" % (popt[0], popt[1], r_squared))

print(ydata, calc_ydata)