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)

你可能感兴趣的:(Python,算法,数据分析,python,人工智能,机器学习)